This is going to be ignored.
This will also be ignored.
You can also use more advanced structures:
Example #1 Advanced escaping
The header above will say 'This is an example'.
'C' style comments end at the first */ encountered. Make sure you don't
nest 'C' style comments. It is easy to make this mistake if you are trying
to comment out a large block of code.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Types
Table of Contents
* Introduction
* Booleans
* Integers
* Floating point numbers
* Strings
* Arrays
* Objects
* Resources
* NULL
* Pseudo-types and variables used in this documentation
* Type Juggling
----------------------------------------------------------------------
Introduction
PHP supports eight primitive types.
Four scalar types:
* boolean
* integer
* float (floating-point number, aka double)
* string
Two compound types:
* array
* object
And finally two special types:
* resource
* NULL
This manual also introduces some pseudo-types for readability reasons:
* mixed
* number
* callback
And the pseudo-variable $....
Some references to the type "double" may remain in the manual. Consider
double the same as float; the two names exist only for historic reasons.
The type of a variable is not usually set by the programmer; rather, it is
decided at runtime by PHP depending on the context in which that variable
is used.
Note: To check the type and value of an expression, use the var_dump()
function.
To get a human-readable representation of a type for debugging, use the
gettype() function. To check for a certain type, do not use gettype(),
but rather the is_type functions. Some examples:
To forcibly convert a variable to a certain type, either cast the variable
or use the settype() function on it.
Note that a variable may be evaluated with different values in certain
situations, depending on what type it is at the time. For more
information, see the section on Type Juggling. The type comparison tables
may also be useful, as they show examples of various type-related
comparisons.
----------------------------------------------------------------------
----------------------------------------------------------------------
Booleans
This is the simplest type. A boolean expresses a truth value. It can be
either TRUE or FALSE.
Note: The boolean type was introduced in PHP 4.
Syntax
To specify a boolean literal, use the keywords TRUE or FALSE. Both are
case-insensitive.
Typically, the result of an operator which returns a boolean value is
passed on to a control structure.
\n";
}
// ...because this can be used with exactly the same meaning:
if ($show_separators) {
echo "foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>
The above example will output:
My name is "MyName". I am printing some Foo.
Now, I am printing some Bar2.
This should print a capital 'A': A
It is also possible to use the Heredoc syntax to pass data to function
arguments:
Example #3 Heredoc in arguments example
As of PHP 5.3.0, it's possible to initialize static variables and class
properties/constants using the Heredoc syntax:
Example #4 Using Heredoc to initialize static values
Starting with PHP 5.3.0, the opening Heredoc identifier may optionally be
enclosed in double quotes:
Example #5 Using double quotes in Heredoc
Note:
Heredoc support was added in PHP 4.
Nowdoc
Nowdocs are to single-quoted strings what heredocs are to double-quoted
strings. A nowdoc is specified similarly to a heredoc, but no parsing is
done inside a nowdoc. The construct is ideal for embedding PHP code or
other large blocks of text without the need for escaping. It shares some
features in common with the SGML construct, in that it
declares a block of text which is not for parsing.
A nowdoc is identified with the same <<< sequence used for heredocs, but
the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'.
All the rules for heredoc identifiers also apply to nowdoc identifiers,
especially those regarding the appearance of the closing identifier.
Example #6 Nowdoc string quoting example
foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'MyName';
echo <<<'EOT'
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41
EOT;
?>
The above example will output:
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41
Note:
Unlike heredocs, nowdocs can be used in any static data context. The
typical example is initializing class properties or constants:
Example #7 Static data example
Note:
Nowdoc support was added in PHP 5.3.0.
Variable parsing
When a string is specified in double quotes or with heredoc, variables are
parsed within it.
There are two types of syntax: a simple one and a complex one. The simple
syntax is the most common and convenient. It provides a way to embed a
variable, an array value, or an object property in a string with a minimum
of effort.
The complex syntax was introduced in PHP 4, and can be recognised by the
curly braces surrounding the expression.
Simple syntax
If a dollar sign ($) is encountered, the parser will greedily take as many
tokens as possible to form a valid variable name. Enclose the variable
name in curly braces to explicitly specify the end of the name.
The above example will output:
He drank some apple juice.
He drank some juice made of .
Similarly, an array index or an object property can be parsed. With array
indices, the closing square bracket (]) marks the end of the index. The
same rules apply to object properties as to simple variables.
Example #8 Simple syntax example
"purple");
echo "He drank some $juices[0] juice.".PHP_EOL;
echo "He drank some $juices[1] juice.".PHP_EOL;
echo "He drank some juice made of $juice[0]s.".PHP_EOL; // Won't work
echo "He drank some $juices[koolaid1] juice.".PHP_EOL;
class people {
public $john = "John Smith";
public $jane = "Jane Smith";
public $robert = "Robert Paulsen";
public $smith = "Smith";
}
$people = new people();
echo "$people->john drank some $juices[0] juice.".PHP_EOL;
echo "$people->john then said hello to $people->jane.".PHP_EOL;
echo "$people->john's wife greeted $people->robert.".PHP_EOL;
echo "$people->robert greeted the two $people->smiths."; // Won't work
?>
The above example will output:
He drank some apple juice.
He drank some orange juice.
He drank some juice made of s.
He drank some purple juice.
John Smith drank some apple juice.
John Smith then said hello to Jane Smith.
John Smith's wife greeted Robert Paulsen.
Robert Paulsen greeted the two .
For anything more complex, you should use the complex syntax.
Complex (curly) syntax
This isn't called complex because the syntax is complex, but because it
allows for the use of complex expressions.
Any scalar variable, array element or object property with a string
representation can be included via this syntax. Simply write the
expression the same way as it would appear outside the string, and then
wrap it in { and }. Since { can not be escaped, this syntax will only be
recognised when the $ immediately follows the {. Use {\$ to get a literal
{$. Some examples to make it clear:
width}00 centimeters broad.";
// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";
// Works
echo "This works: {$arr[4][3]}";
// This is wrong for the same reason as $foo[bar] is wrong outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}";
// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";
// Works.
echo "This works: " . $arr['foo'][3];
echo "This works too: {$obj->values[3]->name}";
echo "This is the value of the var named $name: {${$name}}";
echo "This is the value of the var named by the return value of getName(): {${getName()}}";
echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";
// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>
It is also possible to access class properties using variables within
strings using this syntax.
$bar}\n";
echo "{$foo->$baz[1]}\n";
?>
The above example will output:
I am bar.
I am bar.
Note:
Functions, method calls, static class variables, and class constants
inside {$} work since PHP 5. However, the value accessed will be
interpreted as the name of a variable in the scope in which the string
is defined. Using single curly braces ({}) will not work for accessing
the return values of functions or methods or the values of class
constants or static class variables.
String access and modification by character
Characters within strings may be accessed and modified by specifying the
zero-based offset of the desired character after the string using square
array brackets, as in $str[42]. Think of a string as an array of
characters for this purpose. The functions substr() and substr_replace()
can be used when you want to extract or replace more than 1 character.
Note: Strings may also be accessed using braces, as in $str{42}, for the
same purpose.
Warning
Writing to an out of range offset pads the string with spaces. Non-integer
types are converted to integer. Illegal offset type emits E_NOTICE.
Negative offset emits E_NOTICE in write but reads empty string. Only the
first character of an assigned string is used. Assigning empty string
assigns NULL byte.
Example #9 Some string examples
Note:
Accessing variables of other types (not including arrays or objects
implementing the appropriate interfaces) using [] or {} silently returns
NULL.
Useful functions and operators
Strings may be concatenated using the '.' (dot) operator. Note that the
'+' (addition) operator will not work for this. See String operators for
more information.
There are a number of useful functions for string manipulation.
See the string functions section for general functions, and the regular
expression functions or the Perl-compatible regular expression functions
for advanced find & replace functionality.
There are also functions for URL strings, and functions to encrypt/decrypt
strings (mcrypt and mhash).
Finally, see also the character type functions.
Converting to string
A value can be converted to a string using the (string) cast or the
strval() function. String conversion is automatically done in the scope of
an expression where a string is needed. This happens when using the echo()
or print() functions, or when a variable is compared to a string. The
sections on Types and Type Juggling will make the following clearer. See
also the settype() function.
A boolean TRUE value is converted to the string "1". Boolean FALSE is
converted to "" (the empty string). This allows conversion back and forth
between boolean and string values.
An integer or float is converted to a string representing the number
textually (including the exponent part for floats). Floating point numbers
can be converted using exponential notation (4.1E+6).
Note:
The decimal point character is defined in the script's locale (category
LC_NUMERIC). See the setlocale() function.
Arrays are always converted to the string "Array"; because of this, echo()
and print() can not by themselves show the contents of an array. To view a
single element, use a construction such as echo $arr['foo']. See below for
tips on viewing the entire contents.
Objects in PHP 4 are always converted to the string "Object". To print the
values of object properties for debugging reasons, read the paragraphs
below. To get an object's class name, use the get_class() function. As of
PHP 5, the __toString method is used when applicable.
Resources are always converted to strings with the structure "Resource id
#1", where 1 is the unique number assigned to the resource by PHP at
runtime. Do not rely upon this structure; it is subject to change. To get
a resource's type, use the get_resource_type() function.
NULL is always converted to an empty string.
As stated above, directly converting an array, object, or resource to a
string does not provide any useful information about the value beyond its
type. See the functions print_r() and var_dump() for more effective means
of inspecting the contents of these types.
Most PHP values can also be converted to strings for permanent storage.
This method is called serialization, and is performed by the serialize()
function. If the PHP engine was built with WDDX support, PHP values can
also be serialized as well-formed XML text.
String conversion to numbers
When a string is evaluated in a numeric context, the resulting value and
type are determined as follows.
If the string does not contain any of the characters '.', 'e', or 'E' and
the numeric value fits into integer type limits (as defined by
PHP_INT_MAX), the string will be evaluated as an integer. In all other
cases it will be evaluated as a float.
The value is given by the initial portion of the string. If the string
starts with valid numeric data, this will be the value used. Otherwise,
the value will be 0 (zero). Valid numeric data is an optional sign,
followed by one or more digits (optionally containing a decimal point),
followed by an optional exponent. The exponent is an 'e' or 'E' followed
by one or more digits.
For more information on this conversion, see the Unix manual page for
strtod(3).
To test any of the examples in this section, cut and paste the examples
and insert the following line to see what's going on:
\n";
?>
Do not expect to get the code of one character by converting it to
integer, as is done in C. Use the ord() and chr() functions to convert
between ASCII codes and characters.
----------------------------------------------------------------------
----------------------------------------------------------------------
Arrays
An array in PHP is actually an ordered map. A map is a type that
associates values to keys. This type is optimized for several different
uses; it can be treated as an array, list (vector), hash table (an
implementation of a map), dictionary, collection, stack, queue, and
probably more. As array values can be other arrays, trees and
multidimensional arrays are also possible.
Explanation of those data structures is beyond the scope of this manual,
but at least one example is provided for each of them. For more
information, look towards the considerable literature that exists about
this broad topic.
Syntax
Specifying with array()
An array can be created by the array() language construct. It takes as
parameters any number of comma-separated key => value pairs.
array( key => value
, ...
)
// key may only be an integer or string
// value may be any value of any type
"bar", 12 => true);
echo $arr["foo"]; // bar
echo $arr[12]; // 1
?>
A key may be either an integer or a string. If a key is the standard
representation of an integer, it will be interpreted as such (i.e. "8"
will be interpreted as 8, while "08" will be interpreted as "08"). Floats
in key are truncated to integer. The indexed and associative array types
are the same type in PHP, which can both contain integer and string
indices.
A value can be any PHP type.
Note:
Attempting to access an array key which has not been defined is the same
as accessing any other undefined variable: an E_NOTICE-level error
message will be issued, and the result will be NULL.
array(6 => 5, 13 => 9, "a" => 42));
echo $arr["somearray"][6]; // 5
echo $arr["somearray"][13]; // 9
echo $arr["somearray"]["a"]; // 42
?>
If a key is not specified for a value, the maximum of the integer indices
is taken and the new key will be that value plus 1. If a key that already
has an assigned value is specified, that value will be overwritten.
43, 32, 56, "b" => 12);
// ...this array
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
?>
Warning
Before PHP 4.3.0, appending to an array in which the current maximum key
was negative would create a new key as described above. Since PHP 4.3.0,
the new key will be 0.
Using TRUE as key will evaluate to integer 1 as a key. Using FALSE as key
will evaluate to integer 0 as a key. Using NULL as a key will evaluate to
the empty string. Using the empty string as a key will create (or
overwrite) a key with the empty string and its value; it is not the same
as using empty brackets.
Arrays and objects can not be used as keys. Doing so will result in a
warning: Illegal offset type.
Creating/modifying with square bracket syntax
An existing array can be modified by explicitly setting values in it.
This is done by assigning values to the array, specifying the key in
brackets. The key can also be omitted, resulting in an empty pair of
brackets ([]).
$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type
If $arr doesn't exist yet, it will be created, so this is also an
alternative way to create an array. To change a certain value, assign a
new value to that element using its key. To remove a key/value pair, call
the unset() function on it.
1, 12 => 2);
$arr[] = 56; // This is the same as $arr[13] = 56;
// at this point of the script
$arr["x"] = 42; // This adds a new element to
// the array with key "x"
unset($arr[5]); // This removes the element from the array
unset($arr); // This deletes the whole array
?>
Note:
As mentioned above, if no key is specified, the maximum of the existing
integer indices is taken, and the new key will be that maximum value
plus 1. If no integer indices exist yet, the key will be 0 (zero).
Note that the maximum integer key used for this need not currently exist
in the array. It need only have existed in the array at some time since
the last time the array was re-indexed. The following example
illustrates:
$value) {
unset($array[$i]);
}
print_r($array);
// Append an item (note that the new key is 5, instead of 0).
$array[] = 6;
print_r($array);
// Re-index:
$array = array_values($array);
$array[] = 7;
print_r($array);
?>
The above example will output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Array
(
)
Array
(
[5] => 6
)
Array
(
[0] => 6
[1] => 7
)
Useful functions
There are quite a few useful functions for working with arrays. See the
array functions section.
Note:
The unset() function allows removing keys from an array. Be aware that
the array will not be reindexed. If a true "remove and shift" behavior
is desired, the array can be reindexed using the array_values()
function.
'one', 2 => 'two', 3 => 'three');
unset($a[2]);
/* will produce an array that would have been defined as
$a = array(1 => 'one', 3 => 'three');
and NOT
$a = array(1 => 'one', 2 =>'three');
*/
$b = array_values($a);
// Now $b is array(0 => 'one', 1 =>'three')
?>
The foreach control structure exists specifically for arrays. It provides
an easy way to traverse an array.
Array do's and don'ts
Why is $foo[bar] wrong?
Always use quotes around a string literal array index. For example,
$foo['bar'] is correct, while $foo[bar] is not. But why? It is common to
encounter this kind of syntax in old scripts:
This is wrong, but it works. The reason is that this code has an undefined
constant (bar) rather than a string ('bar' - notice the quotes). PHP may
in future define constants which, unfortunately for such code, have the
same name. It works because PHP automatically converts a bare string (an
unquoted string which does not correspond to any known symbol) into a
string which contains the bare string. For instance, if there is no
defined constant named bar, then PHP will substitute in the string 'bar'
and use that.
Note: This does not mean to always quote the key. Do not quote keys
which are constants or variables, as this will prevent PHP from
interpreting them.
The above example will output:
Checking 0:
Notice: Undefined index: $i in /path/to/script.html on line 9
Bad:
Good: 1
Notice: Undefined index: $i in /path/to/script.html on line 11
Bad:
Good: 1
Checking 1:
Notice: Undefined index: $i in /path/to/script.html on line 9
Bad:
Good: 2
Notice: Undefined index: $i in /path/to/script.html on line 11
Bad:
Good: 2
More examples to demonstrate this behaviour:
'apple', 'veggie' => 'carrot');
// Correct
print $arr['fruit']; // apple
print $arr['veggie']; // carrot
// Incorrect. This works but also throws a PHP error of level E_NOTICE because
// of an undefined constant named fruit
//
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit]; // apple
// This defines a constant to demonstrate what's going on. The value 'veggie'
// is assigned to a constant named fruit.
define('fruit', 'veggie');
// Notice the difference now
print $arr['fruit']; // apple
print $arr[fruit]; // carrot
// The following is okay, as it's inside a string. Constants are not looked for
// within strings, so no E_NOTICE occurs here
print "Hello $arr[fruit]"; // Hello apple
// With one exception: braces surrounding arrays within strings allows constants
// to be interpreted
print "Hello {$arr[fruit]}"; // Hello carrot
print "Hello {$arr['fruit']}"; // Hello apple
// This will not work, and will result in a parse error, such as:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// This of course applies to using superglobals in strings as well
print "Hello $arr['fruit']";
print "Hello $_GET['foo']";
// Concatenation is another option
print "Hello " . $arr['fruit']; // Hello apple
?>
When error_reporting is set to show E_NOTICE level errors (by setting it
to E_ALL, for example), such uses will become immediately visible. By
default, error_reporting is set not to show notices.
As stated in the syntax section, what's inside the square brackets ('['
and ']') must be an expression. This means that code like this works:
This is an example of using a function return value as the array index.
PHP also knows about constants:
Note that E_ERROR is also a valid identifier, just like bar in the first
example. But the last example is in fact the same as writing:
because E_ERROR equals 1, etc.
So why is it bad then?
At some point in the future, the PHP team might want to add another
constant or keyword, or a constant in other code may interfere. For
example, it is already wrong to use the words empty and default this way,
since they are reserved keywords.
Note: To reiterate, inside a double-quoted string, it's valid to not
surround array indexes with quotes so "$foo[bar]" is valid. See the
above examples for details on why as well as the section on variable
parsing in strings.
Converting to array
For any of the types: integer, float, string, boolean and resource,
converting a value to an array results in an array with a single element
with index zero and the value of the scalar which was converted. In other
words, (array)$scalarValue is exactly the same as array($scalarValue).
If an object is converted to an array, the result is an array whose
elements are the object's properties. The keys are the member variable
names, with a few notable exceptions: integer properties are unaccessible;
private variables have the class name prepended to the variable name;
protected variables have a '*' prepended to the variable name. These
prepended values have null bytes on either side. This can result in some
unexpected behaviour:
The above will appear to have two keys named 'AA', although one of them is
actually named '\0A\0A'.
Converting NULL to an array results in an empty array.
Comparing
It is possible to compare arrays with the array_diff() function and with
array operators.
Examples
The array type in PHP is very versatile. Here are some examples:
'red',
'taste' => 'sweet',
'shape' => 'round',
'name' => 'apple',
4 // key will be 0
);
$b = array('a', 'b', 'c');
// . . .is completely equivalent with this:
$a = array();
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name'] = 'apple';
$a[] = 4; // key will be 0
$b = array();
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// After the above code is executed, $a will be the array
// array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round',
// 'name' => 'apple', 0 => 4), and $b will be the array
// array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c').
?>
Example #1 Using array()
4,
'OS' => 'Linux',
'lang' => 'english',
'short_tags' => true
);
// strictly numerical keys
$array = array( 7,
8,
0,
156,
-10
);
// this is the same as array(0 => 7, 1 => 8, ...)
$switching = array( 10, // key = 0
5 => 6,
3 => 7,
'a' => 4,
11, // key = 6 (maximum of integer-indices was 5)
'8' => 2, // key = 8 (integer!)
'02' => 77, // key = '02'
0 => 12 // the value 10 will be overwritten by 12
);
// empty array
$empty = array();
?>
Example #2 Collection
The above example will output:
Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?
Changing the values of the array directly is possible since PHP 5 by
passing them by reference. Before that, a workaround is necessary:
Example #3 Changing element in the loop
$color) {
$colors[$key] = strtoupper($color);
}
print_r($colors);
?>
The above example will output:
Array
(
[0] => RED
[1] => BLUE
[2] => GREEN
[3] => YELLOW
)
This example creates a one-based array.
Example #4 One-based index
'January', 'February', 'March');
print_r($firstquarter);
?>
The above example will output:
Array
(
[1] => 'January'
[2] => 'February'
[3] => 'March'
)
Example #5 Filling an array
Arrays are ordered. The order can be changed using various sorting
functions. See the array functions section for more information. The
count() function can be used to count the number of items in an array.
Example #6 Sorting an array
Because the value of an array can be anything, it can also be another
array. This enables the creation of recursive and multi-dimensional
arrays.
Example #7 Recursive and multi-dimensional arrays
array ( "a" => "orange",
"b" => "banana",
"c" => "apple"
),
"numbers" => array ( 1,
2,
3,
4,
5,
6
),
"holes" => array ( "first",
5 => "second",
"third"
)
);
// Some examples to address values in the array above
echo $fruits["holes"][5]; // prints "second"
echo $fruits["fruits"]["a"]; // prints "orange"
unset($fruits["holes"][0]); // remove "first"
// Create a new multi-dimensional array
$juices["apple"]["green"] = "good";
?>
Array assignment always involves value copying. Use the reference operator
to copy an array by reference.
----------------------------------------------------------------------
----------------------------------------------------------------------
Objects
Object Initialization
To create a new object, use the new statement to instantiate a class:
do_foo();
?>
For a full discussion, see the Classes and Objects chapter.
Converting to object
If an object is converted to an object, it is not modified. If a value of
any other type is converted to an object, a new instance of the stdClass
built-in class is created. If the value was NULL, the new instance will be
empty. Arrays convert to an object with properties named by keys, and
corresponding values. For any other value, a member variable named scalar
will contain the value.
scalar; // outputs 'ciao'
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
Resources
A resource is a special variable, holding a reference to an external
resource. Resources are created and used by special functions. See the
appendix for a listing of all these functions and the corresponding
resource types.
Note: The resource type was introduced in PHP 4
See also the get_resource_type() function.
Converting to resource
As resource variables hold special handlers to opened files, database
connections, image canvas areas and the like, converting to a resource
makes no sense.
Freeing resources
Thanks to the reference-counting system introduced with PHP 4's Zend
Engine, a resource with no more references to it is detected
automatically, and it is freed by the garbage collector. For this reason,
it is rarely necessary to free the memory manually.
Note: Persistent database links are an exception to this rule. They are
not destroyed by the garbage collector. See the persistent connections
section for more information.
----------------------------------------------------------------------
----------------------------------------------------------------------
NULL
The special NULL value represents a variable with no value. NULL is the
only possible value of type NULL.
Note: The null type was introduced in PHP 4.
A variable is considered to be null if:
* it has been assigned the constant NULL.
* it has not been set to any value yet.
* it has been unset().
Syntax
There is only one value of type null, and that is the case-insensitive
keyword NULL.
See also the functions is_null() and unset().
Casting to NULL
Casting a variable to null will remove the variable and unset its value.
----------------------------------------------------------------------
----------------------------------------------------------------------
Pseudo-types and variables used in this documentation
mixed
mixed indicates that a parameter may accept multiple (but not necessarily
all) types.
gettype() for example will accept all PHP types, while str_replace() will
accept strings and arrays.
number
number indicates that a parameter can be either integer or float.
callback
Some functions like call_user_func() or usort() accept user-defined
callback functions as a parameter. Callback functions can not only be
simple functions, but also object methods, including static class methods.
A PHP function is passed by its name as a string. Any built-in or
user-defined function can be used, except language constructs such as:
array(), echo(), empty(), eval(), exit(), isset(), list(), print() or
unset().
A method of an instantiated object is passed as an array containing an
object at index 0 and the method name at index 1.
Static class methods can also be passed without instantiating an object of
that class by passing the class name instead of an object at index 0.
Apart from common user-defined function, create_function() can also be
used to create an anonymous callback function. As of PHP 5.3.0 it is
possible to also pass a closure to a callback parameter.
Example #1 Callback function examples
Example #2 Callback example using a Closure
The above example will output:
2 4 6 8 10
Note: In PHP4, it was necessary to use a reference to create a callback
that points to the actual object, and not a copy of it. For more
details, see References Explained.
Note:
Callbacks registered with functions such as call_user_func() and
call_user_func_array() will not be called if there is an uncaught
exception thrown in a previous callback.
void
void as a return type means that the return value is useless. void in a
parameter list means that the function doesn't accept any parameters.
...
$... in function prototypes means and so on. This variable name is used
when a function can take an endless number of arguments.
----------------------------------------------------------------------
----------------------------------------------------------------------
Type Juggling
PHP does not require (or support) explicit type definition in variable
declaration; a variable's type is determined by the context in which the
variable is used. That is to say, if a string value is assigned to
variable $var, $var becomes a string. If an integer value is then assigned
to $var, it becomes an integer.
An example of PHP's automatic type conversion is the addition operator
'+'. If either operand is a float, then both operands are evaluated as
floats, and the result will be a float. Otherwise, the operands will be
interpreted as integers, and the result will also be an integer. Note that
this does not change the types of the operands themselves; the only change
is in how the operands are evaluated and what the type of the expression
itself is.
If the last two examples above seem odd, see String conversion to numbers.
To force a variable to be evaluated as a certain type, see the section on
Type casting. To change the type of a variable, see the settype()
function.
To test any of the examples in this section, use the var_dump() function.
Note:
The behaviour of an automatic conversion to array is currently
undefined.
Also, because PHP supports indexing into strings via offsets using the
same syntax as array indexing, the following example holds true for all
PHP versions:
See the section titled String access by character for more information.
Type Casting
Type casting in PHP works much as it does in C: the name of the desired
type is written in parentheses before the variable which is to be cast.
The casts allowed are:
* (int), (integer) - cast to integer
* (bool), (boolean) - cast to boolean
* (float), (double), (real) - cast to float
* (string) - cast to string
* (array) - cast to array
* (object) - cast to object
* (unset) - cast to NULL (PHP 5)
(binary) casting and b prefix forward support was added in PHP 5.2.1
Note that tabs and spaces are allowed inside the parentheses, so the
following are functionally equivalent:
Casting literal strings and variables to binary strings:
Note:
Instead of casting a variable to a string, it is also possible to
enclose the variable in double quotes.
It may not be obvious exactly what will happen when casting between
certain types. For more information, see these sections:
* Converting to boolean
* Converting to integer
* Converting to float
* Converting to string
* Converting to array
* Converting to object
* Converting to resource
* Converting to NULL
* The type comparison tables
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Variables
Table of Contents
* Basics
* Predefined Variables
* Variable scope
* Variable variables
* Variables From External Sources
----------------------------------------------------------------------
Basics
Variables in PHP are represented by a dollar sign followed by the name of
the variable. The variable name is case-sensitive.
Variable names follow the same rules as other labels in PHP. A valid
variable name starts with a letter or underscore, followed by any number
of letters, numbers, or underscores. As a regular expression, it would be
expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
Note: For our purposes here, a letter is a-z, A-Z, and the bytes from
127 through 255 (0x7f-0xff).
Note: $this is a special variable that can't be assigned.
Tip
See also the Userland Naming Guide.
For information on variable related functions, see the Variable Functions
Reference.
By default, variables are always assigned by value. That is to say, when
you assign an expression to a variable, the entire value of the original
expression is copied into the destination variable. This means, for
instance, that after assigning one variable's value to another, changing
one of those variables will have no effect on the other. For more
information on this kind of assignment, see the chapter on Expressions.
PHP also offers another way to assign values to variables: assign by
reference. This means that the new variable simply references (in other
words, "becomes an alias for" or "points to") the original variable.
Changes to the new variable affect the original, and vice versa.
To assign by reference, simply prepend an ampersand (&) to the beginning
of the variable which is being assigned (the source variable). For
instance, the following code snippet outputs 'My name is Bob' twice:
One important thing to note is that only named variables may be assigned
by reference.
It is not necessary to initialize variables in PHP however it is a very
good practice. Uninitialized variables have a default value of their type
depending on the context in which they are used - booleans default to
FALSE, integers and floats default to zero, strings (e.g. used in echo())
are set as an empty string and arrays become to an empty array.
Example #1 Default values of uninitialized variables
25
var_dump($unset_int);
// Float/double usage; outputs 'float(1.25)'
$unset_float += 1.25;
var_dump($unset_float);
// Array usage; outputs array(1) { [3]=> string(3) "def" }
$unset_arr[3] = "def"; // array() + array(3 => "def") => array(3 => "def")
var_dump($unset_arr);
// Object usage; creates new stdClass object (see http://www.php.net/manual/en/reserved.classes.php)
// Outputs: object(stdClass)#1 (1) { ["foo"]=> string(3) "bar" }
$unset_obj->foo = 'bar';
var_dump($unset_obj);
?>
Relying on the default value of an uninitialized variable is problematic
in the case of including one file into another which uses the same
variable name. It is also a major security risk with register_globals
turned on. E_NOTICE level error is issued in case of working with
uninitialized variables, however not in the case of appending elements to
the uninitialized array. isset() language construct can be used to detect
if a variable has been already initialized.
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Variables
PHP provides a large number of predefined variables to any script which it
runs. Many of these variables, however, cannot be fully documented as they
are dependent upon which server is running, the version and setup of the
server, and other factors. Some of these variables will not be available
when PHP is run on the command line. For a listing of these variables,
please see the section on Reserved Predefined Variables.
Warning
In PHP 4.2.0 and later, the default value for the PHP directive
register_globals is off. This is a major change in PHP. Having
register_globals off affects the set of predefined variables available in
the global scope. For example, to get DOCUMENT_ROOT you'll use
$_SERVER['DOCUMENT_ROOT'] instead of $DOCUMENT_ROOT, or $_GET['id'] from
the URL http://www.example.com/test.php?id=3 instead of $id, or
$_ENV['HOME'] instead of $HOME.
For related information on this change, read the configuration entry for
register_globals, the security chapter on Using Register Globals , as well
as the PHP >> 4.1.0 and >> 4.2.0 Release Announcements.
Using the available PHP Reserved Predefined Variables, like the
superglobal arrays, is preferred.
From version 4.1.0 onward, PHP provides an additional set of predefined
arrays containing variables from the web server (if applicable), the
environment, and user input. These new arrays are rather special in that
they are automatically global--i.e., automatically available in every
scope. For this reason, they are often known as "superglobals". (There is
no mechanism in PHP for user-defined superglobals.) The superglobals are
listed below; however, for a listing of their contents and further
discussion on PHP predefined variables and their natures, please see the
section Reserved Predefined Variables. Also, you'll notice how the older
predefined variables ($HTTP_*_VARS) still exist. As of PHP 5.0.0, the long
PHP predefined variable arrays may be disabled with the
register_long_arrays directive.
Note: Variable variables
Superglobals cannot be used as variable variables inside functions or
class methods.
Note:
Even though both the superglobal and HTTP_*_VARS can exist at the same
time; they are not identical, so modifying one will not change the
other.
If certain variables in variables_order are not set, their appropriate PHP
predefined arrays are also left empty.
----------------------------------------------------------------------
----------------------------------------------------------------------
Variable scope
The scope of a variable is the context within which it is defined. For the
most part all PHP variables only have a single scope. This single scope
spans included and required files as well. For example:
Here the $a variable will be available within the included b.inc script.
However, within user-defined functions a local function scope is
introduced. Any variable used inside a function is by default limited to
the local function scope. For example:
This script will not produce any output because the echo statement refers
to a local version of the $a variable, and it has not been assigned a
value within this scope. You may notice that this is a little bit
different from the C language in that global variables in C are
automatically available to functions unless specifically overridden by a
local definition. This can cause some problems in that people may
inadvertently change a global variable. In PHP global variables must be
declared global inside a function if they are going to be used in that
function.
The global keyword
First, an example use of global:
Example #1 Using global
The above script will output 3. By declaring $a and $b global within the
function, all references to either variable will refer to the global
version. There is no limit to the number of global variables that can be
manipulated by a function.
A second way to access variables from the global scope is to use the
special PHP-defined $GLOBALS array. The previous example can be rewritten
as:
Example #2 Using $GLOBALS instead of global
The $GLOBALS array is an associative array with the name of the global
variable being the key and the contents of that variable being the value
of the array element. Notice how $GLOBALS exists in any scope, this is
because $GLOBALS is a superglobal. Here's an example demonstrating the
power of superglobals:
Example #3 Example demonstrating superglobals and scope
Note:
Using global keyword outside a function is not an error. It can be used
if the file is included from inside a function.
Using static variables
Another important feature of variable scoping is the static variable. A
static variable exists only in a local function scope, but it does not
lose its value when program execution leaves this scope. Consider the
following example:
Example #4 Example demonstrating need for static variables
This function is quite useless since every time it is called it sets $a to
0 and prints 0. The $a++ which increments the variable serves no purpose
since as soon as the function exits the $a variable disappears. To make a
useful counting function which will not lose track of the current count,
the $a variable is declared static:
Example #5 Example use of static variables
Now, $a is initialized only in first call of function and every time the
test() function is called it will print the value of $a and increment it.
Static variables also provide one way to deal with recursive functions. A
recursive function is one which calls itself. Care must be taken when
writing a recursive function because it is possible to make it recurse
indefinitely. You must make sure you have an adequate way of terminating
the recursion. The following simple function recursively counts to 10,
using the static variable $count to know when to stop:
Example #6 Static variables with recursive functions
Note:
Static variables may be declared as seen in the examples above. Trying
to assign values to these variables which are the result of expressions
will cause a parse error.
Example #7 Declaring static variables
Note:
Static declarations are resolved in compile-time.
Note:
Using global keyword outside a function is not an error. It can be used
if the file is included from inside a function.
References with global and static variables
The Zend Engine 1, driving PHP 4, implements the static and global
modifier for variables in terms of references. For example, a true global
variable imported inside a function scope with the global statement
actually creates a reference to the global variable. This can lead to
unexpected behaviour which the following example addresses:
The above example will output:
NULL
object(stdClass)(0) {
}
A similar behaviour applies to the static statement. References are not
stored statically:
property++;
return $obj;
}
function &get_instance_noref() {
static $obj;
echo 'Static object: ';
var_dump($obj);
if (!isset($obj)) {
// Assign the object to the static variable
$obj = new stdclass;
}
$obj->property++;
return $obj;
}
$obj1 = get_instance_ref();
$still_obj1 = get_instance_ref();
echo "\n";
$obj2 = get_instance_noref();
$still_obj2 = get_instance_noref();
?>
The above example will output:
Static object: NULL
Static object: NULL
Static object: NULL
Static object: object(stdClass)(1) {
["property"]=>
int(1)
}
This example demonstrates that when assigning a reference to a static
variable, it's not remembered when you call the &get_instance_ref()
function a second time.
----------------------------------------------------------------------
----------------------------------------------------------------------
Variable variables
Sometimes it is convenient to be able to have variable variable names.
That is, a variable name which can be set and used dynamically. A normal
variable is set with a statement such as:
A variable variable takes the value of a variable and treats that as the
name of a variable. In the above example, hello, can be used as the name
of a variable by using two dollar signs. i.e.
At this point two variables have been defined and stored in the PHP symbol
tree: $a with contents "hello" and $hello with contents "world".
Therefore, this statement:
produces the exact same output as:
i.e. they both produce: hello world.
In order to use variable variables with arrays, you have to resolve an
ambiguity problem. That is, if you write $$a[1] then the parser needs to
know if you meant to use $a[1] as a variable, or if you wanted $$a as the
variable and then the [1] index from that variable. The syntax for
resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for
the second.
Class properties may also be accessed using variable property names. The
variable property name will be resolved within the scope from which the
call is made. For instance, if you have an expression such as $foo->$bar,
then the local scope will be examined for $bar and its value will be used
as the name of the property of $foo. This is also true if $bar is an array
access.
Example #1 Variable function example
$bar . "\n";
echo $foo->$baz[1] . "\n";
?>
The above example will output:
I am bar.
I am bar.
Warning
Please note that variable variables cannot be used with PHP's Superglobal
arrays within functions or class methods. The variable $this is also a
special variable that cannot be referenced dynamically.
----------------------------------------------------------------------
----------------------------------------------------------------------
Variables From External Sources
HTML Forms (GET and POST)
When a form is submitted to a PHP script, the information from that form
is automatically made available to the script. There are many ways to
access this information, for example:
Example #1 A simple HTML form
Depending on your particular setup and personal preferences, there are
many ways to access data from your HTML forms. Some examples are:
Example #2 Accessing data from a simple POST HTML form
Using a GET form is similar except you'll use the appropriate GET
predefined variable instead. GET also applies to the QUERY_STRING (the
information after the '?' in a URL). So, for example,
http://www.example.com/test.php?id=3 contains GET data which is accessible
with $_GET['id']. See also $_REQUEST and import_request_variables().
Note:
Superglobal arrays, like $_POST and $_GET, became available in PHP 4.1.0
Note:
Dots and spaces in variable names are converted to underscores. For
example becomes $_REQUEST["a_b"].
As shown, before PHP 4.2.0 the default value for register_globals was on.
The PHP community is encouraging all to not rely on this directive as it's
preferred to assume it's off and code accordingly.
Note:
The magic_quotes_gpc configuration directive affects Get, Post and
Cookie values. If turned on, value (It's "PHP!") will automagically
become (It\'s \"PHP!\"). Escaping is needed for DB insertion. See also
addslashes(), stripslashes() and magic_quotes_sybase.
PHP also understands arrays in the context of form variables (see the
related faq). You may, for example, group related variables together, or
use this feature to retrieve values from a multiple select input. For
example, let's post a form to itself and upon submission display the data:
Example #3 More complex form variables
';
echo htmlspecialchars(print_r($_POST, true));
echo '';
}
?>
IMAGE SUBMIT variable names
When submitting a form, it is possible to use an image instead of the
standard submit button with a tag like:
When the user clicks somewhere on the image, the accompanying form will be
transmitted to the server with two additional variables, sub_x and sub_y.
These contain the coordinates of the user click within the image. The
experienced may note that the actual variable names sent by the browser
contains a period rather than an underscore, but PHP converts the period
to an underscore automatically.
HTTP Cookies
PHP transparently supports HTTP cookies as defined by >> Netscape's Spec.
Cookies are a mechanism for storing data in the remote browser and thus
tracking or identifying return users. You can set cookies using the
setcookie() function. Cookies are part of the HTTP header, so the
SetCookie function must be called before any output is sent to the
browser. This is the same restriction as for the header() function. Cookie
data is then available in the appropriate cookie data arrays, such as
$_COOKIE, $HTTP_COOKIE_VARS as well as in $_REQUEST. See the setcookie()
manual page for more details and examples.
If you wish to assign multiple values to a single cookie variable, you may
assign it as an array. For example:
That will create two separate cookies although MyCookie will now be a
single array in your script. If you want to set just one cookie with
multiple values, consider using serialize() or explode() on the value
first.
Note that a cookie will replace a previous cookie by the same name in your
browser unless the path or domain is different. So, for a shopping cart
application you may want to keep a counter and pass this along. i.e.
Example #4 A setcookie() example
Dots in incoming variable names
Typically, PHP does not alter the names of variables when they are passed
into a script. However, it should be noted that the dot (period, full
stop) is not a valid character in a PHP variable name. For the reason,
look at it:
Now, what the parser sees is a variable named $varname, followed by the
string concatenation operator, followed by the barestring (i.e. unquoted
string which doesn't match any known key or reserved words) 'ext'.
Obviously, this doesn't have the intended result.
For this reason, it is important to note that PHP will automatically
replace any dots in incoming variable names with underscores.
Determining variable types
Because PHP determines the types of variables and converts them
(generally) as needed, it is not always obvious what type a given variable
is at any one time. PHP includes several functions which find out what
type a variable is, such as: gettype(), is_array(), is_float(), is_int(),
is_object(), and is_string(). See also the chapter on Types.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Constants
Table of Contents
* Syntax
* Magic constants
A constant is an identifier (name) for a simple value. As the name
suggests, that value cannot change during the execution of the script
(except for magic constants, which aren't actually constants). A constant
is case-sensitive by default. By convention, constant identifiers are
always uppercase.
The name of a constant follows the same rules as any label in PHP. A valid
constant name starts with a letter or underscore, followed by any number
of letters, numbers, or underscores. As a regular expression, it would be
expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
Tip
See also the Userland Naming Guide.
Example #1 Valid and invalid constant names
Note: For our purposes here, a letter is a-z, A-Z, and the ASCII
characters from 127 through 255 (0x7f-0xff).
Like superglobals, the scope of a constant is global. You can access
constants anywhere in your script without regard to scope. For more
information on scope, read the manual section on variable scope.
----------------------------------------------------------------------
Syntax
You can define a constant by using the define()-function or by using the
const keyword outside a class definition as of PHP 5.3.0. Once a constant
is defined, it can never be changed or undefined.
Only scalar data (boolean, integer, float and string) can be contained in
constants. It is possible to define constants as a resource, but it should
be avoided, as it can cause unexpected results.
You can get the value of a constant by simply specifying its name. Unlike
with variables, you should not prepend a constant with a $. You can also
use the function constant() to read a constant's value if you wish to
obtain the constant's name dynamically. Use get_defined_constants() to get
a list of all defined constants.
Note: Constants and (global) variables are in a different namespace.
This implies that for example TRUE and $TRUE are generally different.
If you use an undefined constant, PHP assumes that you mean the name of
the constant itself, just as if you called it as a string (CONSTANT vs
"CONSTANT"). An error of level E_NOTICE will be issued when this happens.
See also the manual entry on why $foo[bar] is wrong (unless you first
define() bar as a constant). If you simply want to check if a constant is
set, use the defined() function.
These are the differences between constants and variables:
* Constants do not have a dollar sign ($) before them;
* Constants may only be defined using the define() function, not by
simple assignment;
* Constants may be defined and accessed anywhere without regard to
variable scoping rules;
* Constants may not be redefined or undefined once they have been set;
and
* Constants may only evaluate to scalar values.
Example #1 Defining Constants
Example #2 Defining Constants using the const keyword
Note:
As opposed to defining constants using define(), constants defined using
the const keyword must be declared at the top-level scope because they
are defined at compile-time. This means that they cannot be declared
inside functions, loops or if statements.
See also Class Constants.
----------------------------------------------------------------------
----------------------------------------------------------------------
Magic constants
PHP provides a large number of predefined constants to any script which it
runs. Many of these constants, however, are created by various extensions,
and will only be present when those extensions are available, either via
dynamic loading or because they have been compiled in.
There are seven magical constants that change depending on where they are
used. For example, the value of __LINE__ depends on the line that it's
used on in your script. These special constants are case-insensitive and
are as follows:
A few "magical" PHP constants
Name Description
__LINE__ The current line number of the file.
The full path and filename of the file. If used inside an
include, the name of the included file is returned. Since
__FILE__ PHP 4.0.2, __FILE__ always contains an absolute path with
symlinks resolved whereas in older versions it contained
relative path under some circumstances.
The directory of the file. If used inside an include, the
directory of the included file is returned. This is
__DIR__ equivalent to dirname(__FILE__). This directory name does
not have a trailing slash unless it is the root directory.
(Added in PHP 5.3.0.)
The function name. (Added in PHP 4.3.0) As of PHP 5 this
__FUNCTION__ constant returns the function name as it was declared
(case-sensitive). In PHP 4 its value is always lowercased.
The class name. (Added in PHP 4.3.0) As of PHP 5 this
__CLASS__ constant returns the class name as it was declared
(case-sensitive). In PHP 4 its value is always lowercased.
__METHOD__ The class method name. (Added in PHP 5.0.0) The method name
is returned as it was declared (case-sensitive).
__NAMESPACE__ The name of the current namespace (case-sensitive). This
constant is defined in compile-time (Added in PHP 5.3.0).
See also get_class(), get_object_vars(), file_exists() and
function_exists().
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Expressions
Expressions are the most important building stones of PHP. In PHP, almost
anything you write is an expression. The simplest yet most accurate way to
define an expression is "anything that has a value".
The most basic forms of expressions are constants and variables. When you
type "$a = 5", you're assigning '5' into $a. '5', obviously, has the value
5, or in other words '5' is an expression with the value of 5 (in this
case, '5' is an integer constant).
After this assignment, you'd expect $a's value to be 5 as well, so if you
wrote $b = $a, you'd expect it to behave just as if you wrote $b = 5. In
other words, $a is an expression with the value of 5 as well. If
everything works right, this is exactly what will happen.
Slightly more complex examples for expressions are functions. For
instance, consider the following function:
Assuming you're familiar with the concept of functions (if you're not,
take a look at the chapter about functions), you'd assume that typing $c =
foo() is essentially just like writing $c = 5, and you're right. Functions
are expressions with the value of their return value. Since foo() returns
5, the value of the expression 'foo()' is 5. Usually functions don't just
return a static value but compute something.
Of course, values in PHP don't have to be integers, and very often they
aren't. PHP supports four scalar value types: integer values, floating
point values (float), string values and boolean values (scalar values are
values that you can't 'break' into smaller pieces, unlike arrays, for
instance). PHP also supports two composite (non-scalar) types: arrays and
objects. Each of these value types can be assigned into variables or
returned from functions.
PHP takes expressions much further, in the same way many other languages
do. PHP is an expression-oriented language, in the sense that almost
everything is an expression. Consider the example we've already dealt
with, '$a = 5'. It's easy to see that there are two values involved here,
the value of the integer constant '5', and the value of $a which is being
updated to 5 as well. But the truth is that there's one additional value
involved here, and that's the value of the assignment itself. The
assignment itself evaluates to the assigned value, in this case 5. In
practice, it means that '$a = 5', regardless of what it does, is an
expression with the value 5. Thus, writing something like '$b = ($a = 5)'
is like writing '$a = 5; $b = 5;' (a semicolon marks the end of a
statement). Since assignments are parsed in a right to left order, you can
also write '$b = $a = 5'.
Another good example of expression orientation is pre- and post-increment
and decrement. Users of PHP and many other languages may be familiar with
the notation of variable++ and variable--. These are increment and
decrement operators. In PHP, like in C, there are two types of increment -
pre-increment and post-increment. Both pre-increment and post-increment
essentially increment the variable, and the effect on the variable is
identical. The difference is with the value of the increment expression.
Pre-increment, which is written '++$variable', evaluates to the
incremented value (PHP increments the variable before reading its value,
thus the name 'pre-increment'). Post-increment, which is written
'$variable++' evaluates to the original value of $variable, before it was
incremented (PHP increments the variable after reading its value, thus the
name 'post-increment').
A very common type of expressions are comparison expressions. These
expressions evaluate to either FALSE or TRUE. PHP supports > (bigger
than), >= (bigger than or equal to), == (equal), != (not equal), <
(smaller than) and <= (smaller than or equal to). The language also
supports a set of strict equivalence operators: === (equal to and same
type) and !== (not equal to or not same type). These expressions are most
commonly used inside conditional execution, such as if statements.
The last example of expressions we'll deal with here is combined
operator-assignment expressions. You already know that if you want to
increment $a by 1, you can simply write '$a++' or '++$a'. But what if you
want to add more than one to it, for instance 3? You could write '$a++'
multiple times, but this is obviously not a very efficient or comfortable
way. A much more common practice is to write '$a = $a + 3'. '$a + 3'
evaluates to the value of $a plus 3, and is assigned back into $a, which
results in incrementing $a by 3. In PHP, as in several other languages
like C, you can write this in a shorter way, which with time would become
clearer and quicker to understand as well. Adding 3 to the current value
of $a can be written '$a += 3'. This means exactly "take the value of $a,
add 3 to it, and assign it back into $a". In addition to being shorter and
clearer, this also results in faster execution. The value of '$a += 3',
like the value of a regular assignment, is the assigned value. Notice that
it is NOT 3, but the combined value of $a plus 3 (this is the value that's
assigned into $a). Any two-place operator can be used in this
operator-assignment mode, for example '$a -= 5' (subtract 5 from the value
of $a), '$b *= 7' (multiply the value of $b by 7), etc.
There is one more expression that may seem odd if you haven't seen it in
other languages, the ternary conditional operator:
If the value of the first subexpression is TRUE (non-zero), then the
second subexpression is evaluated, and that is the result of the
conditional expression. Otherwise, the third subexpression is evaluated,
and that is the value.
The following example should help you understand pre- and post-increment
and expressions in general a bit better:
Some expressions can be considered as statements. In this case, a
statement has the form of 'expr ;' that is, an expression followed by a
semicolon. In '$b = $a = 5;', '$a = 5' is a valid expression, but it's not
a statement by itself. '$b = $a = 5;' however is a valid statement.
One last thing worth mentioning is the truth value of expressions. In many
events, mainly in conditional execution and loops, you're not interested
in the specific value of the expression, but only care about whether it
means TRUE or FALSE. The constants TRUE and FALSE (case-insensitive) are
the two possible boolean values. When necessary, an expression is
automatically converted to boolean. See the section about type-casting for
details about how.
PHP provides a full and powerful implementation of expressions, and
documenting it entirely goes beyond the scope of this manual. The above
examples should give you a good idea about what expressions are and how
you can construct useful expressions. Throughout the rest of this manual
we'll write expr to indicate any valid PHP expression.
----------------------------------------------------------------------
----------------------------------------------------------------------
Operators
Table of Contents
* Operator Precedence
* Arithmetic Operators
* Assignment Operators
* Bitwise Operators
* Comparison Operators
* Error Control Operators
* Execution Operators
* Incrementing/Decrementing Operators
* Logical Operators
* String Operators
* Array Operators
* Type Operators
An operator is something that takes one or more values (or expressions, in
programming jargon) and yields another value (so that the construction
itself becomes an expression).
Operators can be grouped according to the number of values they take.
Unary operators take only one value, for example ! (the logical not
operator) or ++ (the increment operator). Binary operators take two
values, such as the familiar arithmetical operators + (plus) and -
(minus), and the majority of PHP operators fall into this category.
Finally, there is a single ternary operator, ? :, which takes three
values; this is usually referred to simply as "the ternary operator"
(although it could perhaps more properly be called the conditional
operator).
A full list of PHP operators follows in the section Operator Precedence.
This also explains operator Presedence and Associativity, which govern
exactly how expressions containing several different operators are
evaluated.
----------------------------------------------------------------------
Operator Precedence
The precedence of an operator specifies how "tightly" it binds two
expressions together. For example, in the expression 1 + 5 * 3, the answer
is 16 and not 18 because the multiplication ("*") operator has a higher
precedence than the addition ("+") operator. Parentheses may be used to
force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18.
When operators have equal precedence, their associativity decides whether
they are evaluated starting from the right, or starting from the left -
see the examples below.
The following table lists the operators in order of precedence, with the
highest-precedence ones at the top. Operators on the same line have equal
precedence, in which case associativity decides the order of evaluation.
Operator Precedence
Associativity Operators Additional Information
non-associative clone new clone and new
left [ array()
non-associative ++ -- increment/decrement
right ~ - (int) (float) (string) (array) types
(object) (bool) @
non-associative instanceof types
right ! logical
left * / % arithmetic
left + - . arithmetic and string
left << >> bitwise
non-associative < <= > >= <> comparison
non-associative == != === !== comparison
left & bitwise and references
left ^ bitwise
left | bitwise
left && logical
left || logical
left ? : ternary
right = += -= *= /= .= %= &= |= ^= <<= assignment
>>= =>
left and logical
left xor logical
left or logical
left , many uses
For operators of equal precedence, left associativity means that
evaluation proceeds from left to right, and right associativity means the
opposite.
Example #1 Associativity
$a = 5, $b = 5
// mixing ++ and + produces undefined behavior
$a = 1;
echo ++$a + $a++; // may print 4 or 5
?>
Use of parentheses, even when not strictly necessary, can often increase
readability of the code.
Note:
Although = has a lower precedence than most other operators, PHP will
still allow expressions similar to the following: if (!$a = foo()), in
which case the return value of foo() is put into $a.
----------------------------------------------------------------------
----------------------------------------------------------------------
Arithmetic Operators
Remember basic arithmetic from school? These work just like those.
Arithmetic Operators
Example Name Result
-$a Negation Opposite of $a.
$a + $b Addition Sum of $a and $b.
$a - $b Subtraction Difference of $a and $b.
$a * $b Multiplication Product of $a and $b.
$a / $b Division Quotient of $a and $b.
$a % $b Modulus Remainder of $a divided by $b.
The division operator ("/") returns a float value unless the two operands
are integers (or strings that get converted to integers) and the numbers
are evenly divisible, in which case an integer value will be returned.
Operands of modulus are converted to integers (by stripping the decimal
part) before processing.
The result of the modulus operator % has the same sign as the dividend -
that is, the result of $a % $b will have the same sign as $a. For example:
See also the manual page on Math functions.
----------------------------------------------------------------------
----------------------------------------------------------------------
Assignment Operators
The basic assignment operator is "=". Your first inclination might be to
think of this as "equal to". Don't. It really means that the left operand
gets set to the value of the expression on the rights (that is, "gets set
to").
The value of an assignment expression is the value assigned. That is, the
value of "$a = 3" is 3. This allows you to do some tricky things:
For arrays, assigning a value to a named key is performed using the "=>"
operator. The precedence of this operator is the same as other assignment
operators.
In addition to the basic assignment operator, there are "combined
operators" for all of the binary arithmetic, array union and string
operators that allow you to use a value in an expression and then set its
value to the result of that expression. For example:
Note that the assignment copies the original variable to the new one
(assignment by value), so changes to one will not affect the other. This
may also have relevance if you need to copy something like a large array
inside a tight loop.
An exception to the usual assignment by value behaviour within PHP occurs
with objects, which are assigned by reference in PHP 5. Objects may be
explicitly copied via the clone keyword.
Assignment by Reference
Assignment by reference is also supported, using the "$var = &$othervar;"
syntax. Assignment by reference means that both variables end up pointing
at the same data, and nothing is copied anywhere.
Example #1 Assigning by reference
As of PHP 5, the new operator returns a reference automatically, so
assigning the result of new by reference results in an E_DEPRECATED
message in PHP 5.3 and later, and an E_STRICT message in earlier versions.
For example, this code will result in a warning:
More information on references and their potential uses can be found in
the References Explained section of the manual.
----------------------------------------------------------------------
----------------------------------------------------------------------
Bitwise Operators
Bitwise operators allow evaluation and manipulation of specific bits
within an integer.
Bitwise Operators
Example Name Result
$a & $b And Bits that are set in both $a and $b are set.
$a | $b Or (inclusive or) Bits that are set in either $a or $b are set.
$a ^ $b Xor (exclusive or) Bits that are set in $a or $b but not both are
set.
~ $a Not Bits that are set in $a are not set, and vice
versa.
$a << $b Shift left Shift the bits of $a $b steps to the left
(each step means "multiply by two")
$a >> $b Shift right Shift the bits of $a $b steps to the right
(each step means "divide by two")
Bit shifting in PHP is arithmetic. Bits shifted off either end are
discarded. Left shifts have zeros shifted in on the right while the sign
bit is shifted out on the left, meaning the sign of an operand is not
preserved. Right shifts have copies of the sign bit shifted in on the
left, meaning the sign of an operand is preserved.
Use parentheses to ensure the desired precedence. For example, $a & $b ==
true evaluates the equivalency then the bitwise and; while ($a & $b) ==
true evaluates the bitwise and then the equivalency.
Be aware of data type conversions. If both the left-hand and right-hand
parameters are strings, the bitwise operator will operate on the
characters' ASCII values.
PHP's error_reporting ini setting uses bitwise values,
providing a real-world demonstration of turning
bits off. To show all errors, except for notices,
the php.ini file instructions say to use:
E_ALL & ~E_NOTICE
This works by starting with E_ALL:
00000000000000000111011111111111
Then taking the value of E_NOTICE...
00000000000000000000000000001000
... and inverting it via ~:
11111111111111111111111111110111
Finally, it uses AND (&) to find the bits turned
on in both values:
00000000000000000111011111110111
Another way to accomplish that is using XOR (^)
to find bits that are on in only one value or the other:
E_ALL ^ E_NOTICE
error_reporting can also be used to demonstrate turning bits on.
The way to show just errors and recoverable errors is:
E_ERROR | E_RECOVERABLE_ERROR
This process combines E_ERROR
00000000000000000000000000000001
and
00000000000000000001000000000000
using the OR (|) operator
to get the bits turned on in either value:
00000000000000000001000000000001
Example #1 Bitwise AND, OR and XOR operations on integers
The above example will output:
--------- --------- -- ---------
result value op test
--------- --------- -- ---------
Bitwise AND
( 0 = 0000) = ( 0 = 0000) & ( 5 = 0101)
( 1 = 0001) = ( 1 = 0001) & ( 5 = 0101)
( 0 = 0000) = ( 2 = 0010) & ( 5 = 0101)
( 4 = 0100) = ( 4 = 0100) & ( 5 = 0101)
( 0 = 0000) = ( 8 = 1000) & ( 5 = 0101)
Bitwise Inclusive OR
( 5 = 0101) = ( 0 = 0000) | ( 5 = 0101)
( 5 = 0101) = ( 1 = 0001) | ( 5 = 0101)
( 7 = 0111) = ( 2 = 0010) | ( 5 = 0101)
( 5 = 0101) = ( 4 = 0100) | ( 5 = 0101)
(13 = 1101) = ( 8 = 1000) | ( 5 = 0101)
Bitwise Exclusive OR (XOR)
( 5 = 0101) = ( 0 = 0000) ^ ( 5 = 0101)
( 4 = 0100) = ( 1 = 0001) ^ ( 5 = 0101)
( 7 = 0111) = ( 2 = 0010) ^ ( 5 = 0101)
( 1 = 0001) = ( 4 = 0100) ^ ( 5 = 0101)
(13 = 1101) = ( 8 = 1000) ^ ( 5 = 0101)
Example #2 Bitwise XOR operations on strings
Example #3 Bit shifting on integers
> $places;
p($res, $val, '>>', $places, 'copy of sign bit shifted into left side');
$val = 4;
$places = 2;
$res = $val >> $places;
p($res, $val, '>>', $places);
$val = 4;
$places = 3;
$res = $val >> $places;
p($res, $val, '>>', $places, 'bits shift out right side');
$val = 4;
$places = 4;
$res = $val >> $places;
p($res, $val, '>>', $places, 'same result as above; can not shift beyond 0');
echo "\n--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---\n";
$val = -4;
$places = 1;
$res = $val >> $places;
p($res, $val, '>>', $places, 'copy of sign bit shifted into left side');
$val = -4;
$places = 2;
$res = $val >> $places;
p($res, $val, '>>', $places, 'bits shift out right side');
$val = -4;
$places = 3;
$res = $val >> $places;
p($res, $val, '>>', $places, 'same result as above; can not shift beyond -1');
echo "\n--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---\n";
$val = 4;
$places = 1;
$res = $val << $places;
p($res, $val, '<<', $places, 'zeros fill in right side');
$val = 4;
$places = (PHP_INT_SIZE * 8) - 4;
$res = $val << $places;
p($res, $val, '<<', $places);
$val = 4;
$places = (PHP_INT_SIZE * 8) - 3;
$res = $val << $places;
p($res, $val, '<<', $places, 'sign bits get shifted out');
$val = 4;
$places = (PHP_INT_SIZE * 8) - 2;
$res = $val << $places;
p($res, $val, '<<', $places, 'bits shift out left side');
echo "\n--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---\n";
$val = -4;
$places = 1;
$res = $val << $places;
p($res, $val, '<<', $places, 'zeros fill in right side');
$val = -4;
$places = (PHP_INT_SIZE * 8) - 3;
$res = $val << $places;
p($res, $val, '<<', $places);
$val = -4;
$places = (PHP_INT_SIZE * 8) - 2;
$res = $val << $places;
p($res, $val, '<<', $places, 'bits shift out left side, including sign bit');
/*
* Ignore this bottom section,
* it is just formatting to make output clearer.
*/
function p($res, $val, $op, $places, $note = '') {
$format = '%0' . (PHP_INT_SIZE * 8) . "b\n";
printf("Expression: %d = %d %s %d\n", $res, $val, $op, $places);
echo " Decimal:\n";
printf(" val=%d\n", $val);
printf(" res=%d\n", $res);
echo " Binary:\n";
printf(' val=' . $format, $val);
printf(' res=' . $format, $res);
if ($note) {
echo " NOTE: $note\n";
}
echo "\n";
}
?>
Output of the above example on 32 bit machines:
--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---
Expression: 2 = 4 >> 1
Decimal:
val=4
res=2
Binary:
val=00000000000000000000000000000100
res=00000000000000000000000000000010
NOTE: copy of sign bit shifted into left side
Expression: 1 = 4 >> 2
Decimal:
val=4
res=1
Binary:
val=00000000000000000000000000000100
res=00000000000000000000000000000001
Expression: 0 = 4 >> 3
Decimal:
val=4
res=0
Binary:
val=00000000000000000000000000000100
res=00000000000000000000000000000000
NOTE: bits shift out right side
Expression: 0 = 4 >> 4
Decimal:
val=4
res=0
Binary:
val=00000000000000000000000000000100
res=00000000000000000000000000000000
NOTE: same result as above; can not shift beyond 0
--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---
Expression: -2 = -4 >> 1
Decimal:
val=-4
res=-2
Binary:
val=11111111111111111111111111111100
res=11111111111111111111111111111110
NOTE: copy of sign bit shifted into left side
Expression: -1 = -4 >> 2
Decimal:
val=-4
res=-1
Binary:
val=11111111111111111111111111111100
res=11111111111111111111111111111111
NOTE: bits shift out right side
Expression: -1 = -4 >> 3
Decimal:
val=-4
res=-1
Binary:
val=11111111111111111111111111111100
res=11111111111111111111111111111111
NOTE: same result as above; can not shift beyond -1
--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---
Expression: 8 = 4 << 1
Decimal:
val=4
res=8
Binary:
val=00000000000000000000000000000100
res=00000000000000000000000000001000
NOTE: zeros fill in right side
Expression: 1073741824 = 4 << 28
Decimal:
val=4
res=1073741824
Binary:
val=00000000000000000000000000000100
res=01000000000000000000000000000000
Expression: -2147483648 = 4 << 29
Decimal:
val=4
res=-2147483648
Binary:
val=00000000000000000000000000000100
res=10000000000000000000000000000000
NOTE: sign bits get shifted out
Expression: 0 = 4 << 30
Decimal:
val=4
res=0
Binary:
val=00000000000000000000000000000100
res=00000000000000000000000000000000
NOTE: bits shift out left side
--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---
Expression: -8 = -4 << 1
Decimal:
val=-4
res=-8
Binary:
val=11111111111111111111111111111100
res=11111111111111111111111111111000
NOTE: zeros fill in right side
Expression: -2147483648 = -4 << 29
Decimal:
val=-4
res=-2147483648
Binary:
val=11111111111111111111111111111100
res=10000000000000000000000000000000
Expression: 0 = -4 << 30
Decimal:
val=-4
res=0
Binary:
val=11111111111111111111111111111100
res=00000000000000000000000000000000
NOTE: bits shift out left side, including sign bit
Output of the above example on 64 bit machines:
--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---
Expression: 2 = 4 >> 1
Decimal:
val=4
res=2
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=0000000000000000000000000000000000000000000000000000000000000010
NOTE: copy of sign bit shifted into left side
Expression: 1 = 4 >> 2
Decimal:
val=4
res=1
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=0000000000000000000000000000000000000000000000000000000000000001
Expression: 0 = 4 >> 3
Decimal:
val=4
res=0
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=0000000000000000000000000000000000000000000000000000000000000000
NOTE: bits shift out right side
Expression: 0 = 4 >> 4
Decimal:
val=4
res=0
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=0000000000000000000000000000000000000000000000000000000000000000
NOTE: same result as above; can not shift beyond 0
--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---
Expression: -2 = -4 >> 1
Decimal:
val=-4
res=-2
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100
res=1111111111111111111111111111111111111111111111111111111111111110
NOTE: copy of sign bit shifted into left side
Expression: -1 = -4 >> 2
Decimal:
val=-4
res=-1
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100
res=1111111111111111111111111111111111111111111111111111111111111111
NOTE: bits shift out right side
Expression: -1 = -4 >> 3
Decimal:
val=-4
res=-1
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100
res=1111111111111111111111111111111111111111111111111111111111111111
NOTE: same result as above; can not shift beyond -1
--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---
Expression: 8 = 4 << 1
Decimal:
val=4
res=8
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=0000000000000000000000000000000000000000000000000000000000001000
NOTE: zeros fill in right side
Expression: 4611686018427387904 = 4 << 60
Decimal:
val=4
res=4611686018427387904
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=0100000000000000000000000000000000000000000000000000000000000000
Expression: -9223372036854775808 = 4 << 61
Decimal:
val=4
res=-9223372036854775808
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=1000000000000000000000000000000000000000000000000000000000000000
NOTE: sign bits get shifted out
Expression: 0 = 4 << 62
Decimal:
val=4
res=0
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=0000000000000000000000000000000000000000000000000000000000000000
NOTE: bits shift out left side
--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---
Expression: -8 = -4 << 1
Decimal:
val=-4
res=-8
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100
res=1111111111111111111111111111111111111111111111111111111111111000
NOTE: zeros fill in right side
Expression: -9223372036854775808 = -4 << 61
Decimal:
val=-4
res=-9223372036854775808
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100
res=1000000000000000000000000000000000000000000000000000000000000000
Expression: 0 = -4 << 62
Decimal:
val=-4
res=0
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100
res=0000000000000000000000000000000000000000000000000000000000000000
NOTE: bits shift out left side, including sign bit
Warning
Don't right shift for more than 32 bits on 32 bits systems. Don't left
shift in case it results to number longer than 32 bits. Use functions from
the gmp extension for bitwise manipulation on numbers beyond PHP_INT_MAX.
See also pack(), unpack(), gmp_and(), gmp_or(), gmp_xor(), gmp_testbit(),
gmp_clrbit()
----------------------------------------------------------------------
----------------------------------------------------------------------
Comparison Operators
Comparison operators, as their name implies, allow you to compare two
values. You may also be interested in viewing the type comparison tables,
as they show examples of various type related comparisons.
Comparison Operators
Example Name Result
$a == $b Equal TRUE if $a is equal to $b after type
juggling.
$a === $b Identical TRUE if $a is equal to $b, and they are
of the same type. (introduced in PHP 4)
$a != $b Not equal TRUE if $a is not equal to $b after type
juggling.
$a <> $b Not equal TRUE if $a is not equal to $b after type
juggling.
TRUE if $a is not equal to $b, or they
$a !== $b Not identical are not of the same type. (introduced in
PHP 4)
$a < $b Less than TRUE if $a is strictly less than $b.
$a > $b Greater than TRUE if $a is strictly greater than $b.
$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.
$a >= $b Greater than or equal TRUE if $a is greater than or equal to
to $b.
If you compare a number with a string or the comparison involves numerical
strings, then each string is converted to a number and the comparison
performed numerically. These rules also apply to the switch statement. The
type conversion does not take place when the comparison is === or !== as
this involves comparing the type as well as the value.
true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("10" == "1e1"); // 10 == 10 -> true
var_dump(100 == "1e2"); // 100 == 100 -> true
switch ("a") {
case 0:
echo "0";
break;
case "a": // never reached because "a" is already matched with 0
echo "a";
break;
}
?>
For various types, comparison is done according to the following table (in
order).
Comparison with Various Types
Type of Operand 1 Type of Operand 2 Result
null or string string Convert NULL to "", numerical or
lexical comparison
bool or null anything Convert to bool, FALSE < TRUE
Built-in classes can define its own
comparison, different classes are
object object uncomparable, same class - compare
properties the same way as arrays (PHP
4), PHP 5 has its own explanation
string, resource string, resource Translate strings and resources to
or number or number numbers, usual math
Array with fewer members is smaller,
if key from operand 1 is not found in
array array operand 2 then arrays are
uncomparable, otherwise - compare
value by value (see following example)
array anything array is always greater
object anything object is always greater
Example #1 Transcription of standard array comparison
count($op2)) {
return 1; // $op1 > $op2
}
foreach ($op1 as $key => $val) {
if (!array_key_exists($key, $op2)) {
return null; // uncomparable
} elseif ($val < $op2[$key]) {
return -1;
} elseif ($val > $op2[$key]) {
return 1;
}
}
return 0; // $op1 == $op2
}
?>
See also strcasecmp(), strcmp(), Array operators, and the manual section
on Types.
Warning
Comparison of floating point numbers
Because of the way floats are represented internally, you should not test
two floats for equality.
See the documentation for float for more information.
Ternary Operator
Another conditional operator is the "?:" (or ternary) operator.
Example #2 Assigning a default value
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1
evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.
Since PHP 5.3, it is possible to leave out the middle part of the ternary
operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to
TRUE, and expr3 otherwise.
Note: Please note that the ternary operator is a statement, and that it
doesn't evaluate to a variable, but to the result of a statement. This
is important to know if you want to return a variable by reference. The
statement return $var == 42 ? $a : $b; in a return-by-reference function
will therefore not work and a warning is issued in later PHP versions.
Note:
It is recommended that you avoid "stacking" ternary expressions. PHP's
behaviour when using more than one ternary operator within a single
statement is non-obvious:
Example #3 Non-obvious Ternary Behaviour
----------------------------------------------------------------------
----------------------------------------------------------------------
Error Control Operators
PHP supports one error control operator: the at sign (@). When prepended
to an expression in PHP, any error messages that might be generated by
that expression will be ignored.
If the track_errors feature is enabled, any error message generated by the
expression will be saved in the variable $php_errormsg. This variable will
be overwritten on each error, so check early if you want to use it.
Note: The @-operator works only on expressions. A simple rule of thumb
is: if you can take the value of something, you can prepend the @
operator to it. For instance, you can prepend it to variables, function
and include() calls, constants, and so forth. You cannot prepend it to
function or class definitions, or conditional structures such as if and
foreach, and so forth.
See also error_reporting() and the manual section for Error Handling and
Logging functions.
Warning
Currently the "@" error-control operator prefix will even disable error
reporting for critical errors that will terminate script execution. Among
other things, this means that if you use "@" to suppress errors from a
certain function and either it isn't available or has been mistyped, the
script will die right there with no indication as to why.
----------------------------------------------------------------------
----------------------------------------------------------------------
Execution Operators
PHP supports one execution operator: backticks (``). Note that these are
not single-quotes! PHP will attempt to execute the contents of the
backticks as a shell command; the output will be returned (i.e., it won't
simply be dumped to output; it can be assigned to a variable). Use of the
backtick operator is identical to shell_exec().
$output";
?>
Note:
The backtick operator is disabled when safe mode is enabled or
shell_exec() is disabled.
See also the manual section on Program Execution functions, popen()
proc_open(), and Using PHP from the commandline.
----------------------------------------------------------------------
----------------------------------------------------------------------
Incrementing/Decrementing Operators
PHP supports C-style pre- and post-increment and decrement operators.
Note: The increment/decrement operators do not affect boolean values.
Decrementing NULL values has no effect too, but incrementing them
results in 1.
Increment/decrement Operators
Example Name Effect
++$a Pre-increment Increments $a by one, then returns $a.
$a++ Post-increment Returns $a, then increments $a by one.
--$a Pre-decrement Decrements $a by one, then returns $a.
$a-- Post-decrement Returns $a, then decrements $a by one.
Here's a simple example script:
Postincrement";
$a = 5;
echo "Should be 5: " . $a++ . " \n";
echo "Should be 6: " . $a . " \n";
echo "Preincrement ";
$a = 5;
echo "Should be 6: " . ++$a . " \n";
echo "Should be 6: " . $a . " \n";
echo "Postdecrement ";
$a = 5;
echo "Should be 5: " . $a-- . " \n";
echo "Should be 4: " . $a . " \n";
echo "Predecrement ";
$a = 5;
echo "Should be 4: " . --$a . " \n";
echo "Should be 4: " . $a . " \n";
?>
PHP follows Perl's convention when dealing with arithmetic operations on
character variables and not C's. For example, in PHP and Perl $a = 'Z';
$a++; turns $a into 'AA', while in C a = 'Z'; a++; turns a into '[' (ASCII
value of 'Z' is 90, ASCII value of '[' is 91). Note that character
variables can be incremented but not decremented and even so only plain
ASCII characters (a-z and A-Z) are supported. Incrementing/decrementing
other character variables has no effect, the original string is unchanged.
Example #1 Arithmetic Operations on Character Variables
The above example will output:
X
Y
Z
AA
AB
AC
Incrementing or decrementing booleans has no effect.
----------------------------------------------------------------------
----------------------------------------------------------------------
Logical Operators
Logical Operators
Example Name Result
$a and $b And TRUE if both $a and $b are TRUE.
$a or $b Or TRUE if either $a or $b is TRUE.
$a xor $b Xor TRUE if either $a or $b is TRUE, but not both.
! $a Not TRUE if $a is not TRUE.
$a && $b And TRUE if both $a and $b are TRUE.
$a || $b Or TRUE if either $a or $b is TRUE.
The reason for the two different variations of "and" and "or" operators is
that they operate at different precedences. (See Operator Precedence.)
Example #1 Logical operators illustrated
The above example will output something similar to:
bool(true)
bool(false)
bool(false)
bool(true)
----------------------------------------------------------------------
----------------------------------------------------------------------
String Operators
There are two string operators. The first is the concatenation operator
('.'), which returns the concatenation of its right and left arguments.
The second is the concatenating assignment operator ('.='), which appends
the argument on the right side to the argument on the left side. Please
read Assignment Operators for more information.
See also the manual sections on the String type and String functions.
----------------------------------------------------------------------
----------------------------------------------------------------------
Array Operators
Array Operators
Example Name Result
$a + $b Union Union of $a and $b.
$a == $b Equality TRUE if $a and $b have the same key/value pairs.
$a === $b Identity TRUE if $a and $b have the same key/value pairs in
the same order and of the same types.
$a != $b Inequality TRUE if $a is not equal to $b.
$a <> $b Inequality TRUE if $a is not equal to $b.
$a !== $b Non-identity TRUE if $a is not identical to $b.
The + operator returns the right-hand array appended to the left-hand
array; for keys that exist in both arrays, the elements from the left-hand
array will be used, and the matching elements from the right-hand array
will be ignored.
"apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
$c = $a + $b; // Union of $a and $b
echo "Union of \$a and \$b: \n";
var_dump($c);
$c = $b + $a; // Union of $b and $a
echo "Union of \$b and \$a: \n";
var_dump($c);
?>
When executed, this script will print the following:
Union of $a and $b:
array(3) {
["a"]=>
string(5) "apple"
["b"]=>
string(6) "banana"
["c"]=>
string(6) "cherry"
}
Union of $b and $a:
array(3) {
["a"]=>
string(4) "pear"
["b"]=>
string(10) "strawberry"
["c"]=>
string(6) "cherry"
}
Elements of arrays are equal for the comparison if they have the same key
and value.
Example #1 Comparing arrays
"banana", "0" => "apple");
var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>
See also the manual sections on the Array type and Array functions.
----------------------------------------------------------------------
----------------------------------------------------------------------
Type Operators
instanceof is used to determine whether a PHP variable is an instantiated
object of a certain class:
Example #1 Using instanceof with classes
The above example will output:
bool(true)
bool(false)
instanceof can also be used to determine whether a variable is an
instantiated object of a class that inherits from a parent class:
Example #2 Using instanceof with inherited classes
The above example will output:
bool(true)
bool(true)
To check if an object is not an instanceof a class, the logical not
operator can be used.
Example #3 Using instanceof to check if object is not an instanceof a
class
The above example will output:
bool(true)
Lastly, instanceof can also be used to determine whether a variable is an
instantiated object of a class that implements an interface:
Example #4 Using instanceof for class
The above example will output:
bool(true)
bool(true)
Although instanceof is usually used with a literal classname, it can also
be used with another object or a string variable:
Example #5 Using instanceof with other variables
The above example will output:
bool(true)
bool(true)
bool(false)
There are a few pitfalls to be aware of. Before PHP version 5.1.0,
instanceof would call __autoload() if the class name did not exist. In
addition, if the class was not loaded, a fatal error would occur. This can
be worked around by using a dynamic class reference, or a string variable
containing the class name:
Example #6 Avoiding classname lookups and fatal errors with instanceof in
PHP 5.0
The above example will output:
bool(false)
The instanceof operator was introduced in PHP 5. Before this time is_a()
was used but is_a() has since been deprecated in favor of instanceof. Note
that as of PHP 5.3.0, is_a() is no longer deprecated.
See also get_class() and is_a().
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Control Structures
Table of Contents
* Introduction
* if
* else
* elseif/else if
* Alternative syntax for control structures
* while
* do-while
* for
* foreach
* break
* continue
* switch
* declare
* return
* require
* include
* require_once
* include_once
* goto
----------------------------------------------------------------------
Introduction
Any PHP script is built out of a series of statements. A statement can be
an assignment, a function call, a loop, a conditional statement or even a
statement that does nothing (an empty statement). Statements usually end
with a semicolon. In addition, statements can be grouped into a
statement-group by encapsulating a group of statements with curly braces.
A statement-group is a statement by itself as well. The various statement
types are described in this chapter.
----------------------------------------------------------------------
----------------------------------------------------------------------
if
The if construct is one of the most important features of many languages,
PHP included. It allows for conditional execution of code fragments. PHP
features an if structure that is similar to that of C:
if (expr)
statement
As described in the section about expressions, expression is evaluated to
its Boolean value. If expression evaluates to TRUE, PHP will execute
statement, and if it evaluates to FALSE - it'll ignore it. More
information about what values evaluate to FALSE can be found in the
'Converting to boolean' section.
The following example would display a is bigger than b if $a is bigger
than $b:
$b)
echo "a is bigger than b";
?>
Often you'd want to have more than one statement to be executed
conditionally. Of course, there's no need to wrap each statement with an
if clause. Instead, you can group several statements into a statement
group. For example, this code would display a is bigger than b if $a is
bigger than $b, and would then assign the value of $a into $b:
$b) {
echo "a is bigger than b";
$b = $a;
}
?>
If statements can be nested infinitely within other if statements, which
provides you with complete flexibility for conditional execution of the
various parts of your program.
----------------------------------------------------------------------
----------------------------------------------------------------------
else
Often you'd want to execute a statement if a certain condition is met, and
a different statement if the condition is not met. This is what else is
for. else extends an if statement to execute a statement in case the
expression in the if statement evaluates to FALSE. For example, the
following code would display a is greater than b if $a is greater than $b,
and a is NOT greater than b otherwise:
$b) {
echo "a is greater than b";
} else {
echo "a is NOT greater than b";
}
?>
The else statement is only executed if the if expression evaluated to
FALSE, and if there were any elseif expressions - only if they evaluated
to FALSE as well (see elseif).
----------------------------------------------------------------------
----------------------------------------------------------------------
elseif/else if
elseif, as its name suggests, is a combination of if and else. Like else,
it extends an if statement to execute a different statement in case the
original if expression evaluates to FALSE. However, unlike else, it will
execute that alternative expression only if the elseif conditional
expression evaluates to TRUE. For example, the following code would
display a is bigger than b, a equal to b or a is smaller than b:
$b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>
There may be several elseifs within the same if statement. The first
elseif expression (if any) that evaluates to TRUE would be executed. In
PHP, you can also write 'else if' (in two words) and the behavior would be
identical to the one of 'elseif' (in a single word). The syntactic meaning
is slightly different (if you're familiar with C, this is the same
behavior) but the bottom line is that both would result in exactly the
same behavior.
The elseif statement is only executed if the preceding if expression and
any preceding elseif expressions evaluated to FALSE, and the current
elseif expression evaluated to TRUE.
Note: Note that elseif and else if will only be considered exactly the
same when using curly brackets as in the above example. When using a
colon to define your if/elseif conditions, you must not separate else if
into two words, or PHP will fail with a parse error.
$b):
echo $a." is greater than ".$b;
else if($a == $b): // Will not compile.
echo "The above line causes a parse error.";
endif;
/* Correct Method: */
if($a > $b):
echo $a." is greater than ".$b;
elseif($a == $b): // Note the combination of the words.
echo $a." equals ".$b;
else:
echo $a." is neither greater than or equal to ".$b;
endif;
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
Alternative syntax for control structures
PHP offers an alternative syntax for some of its control structures;
namely, if, while, for, foreach, and switch. In each case, the basic form
of the alternate syntax is to change the opening brace to a colon (:) and
the closing brace to endif;, endwhile;, endfor;, endforeach;, or
endswitch;, respectively.
A is equal to 5
In the above example, the HTML block "A is equal to 5" is nested within an
if statement written in the alternative syntax. The HTML block would be
displayed only if $a is equal to 5.
The alternative syntax applies to else and elseif as well. The following
is an if structure with elseif and else in the alternative format:
Note:
Mixing syntaxes in the same control block is not supported.
See also while, for, and if for further examples.
----------------------------------------------------------------------
----------------------------------------------------------------------
while
while loops are the simplest type of loop in PHP. They behave just like
their C counterparts. The basic form of a while statement is:
while (expr)
statement
The meaning of a while statement is simple. It tells PHP to execute the
nested statement(s) repeatedly, as long as the while expression evaluates
to TRUE. The value of the expression is checked each time at the beginning
of the loop, so even if this value changes during the execution of the
nested statement(s), execution will not stop until the end of the
iteration (each time PHP runs the statements in the loop is one
iteration). Sometimes, if the while expression evaluates to FALSE from the
very beginning, the nested statement(s) won't even be run once.
Like with the if statement, you can group multiple statements within the
same while loop by surrounding a group of statements with curly braces, or
by using the alternate syntax:
while (expr):
statement
...
endwhile;
The following examples are identical, and both print the numbers 1 through
10:
----------------------------------------------------------------------
----------------------------------------------------------------------
do-while
do-while loops are very similar to while loops, except the truth
expression is checked at the end of each iteration instead of in the
beginning. The main difference from regular while loops is that the first
iteration of a do-while loop is guaranteed to run (the truth expression is
only checked at the end of the iteration), whereas it may not necessarily
run with a regular while loop (the truth expression is checked at the
beginning of each iteration, if it evaluates to FALSE right from the
beginning, the loop execution would end immediately).
There is just one syntax for do-while loops:
0);
?>
The above loop would run one time exactly, since after the first
iteration, when truth expression is checked, it evaluates to FALSE ($i is
not bigger than 0) and the loop execution ends.
Advanced C users may be familiar with a different usage of the do-while
loop, to allow stopping execution in the middle of code blocks, by
encapsulating them with do-while (0), and using the break statement. The
following code fragment demonstrates this:
Don't worry if you don't understand this right away or at all. You can
code scripts and even powerful scripts without using this 'feature'. Since
PHP 5.3.0, it is possible to use goto operator instead of this hack.
----------------------------------------------------------------------
----------------------------------------------------------------------
for
for loops are the most complex loops in PHP. They behave like their C
counterparts. The syntax of a for loop is:
for (expr1; expr2; expr3)
statement
The first expression (expr1) is evaluated (executed) once unconditionally
at the beginning of the loop.
In the beginning of each iteration, expr2 is evaluated. If it evaluates to
TRUE, the loop continues and the nested statement(s) are executed. If it
evaluates to FALSE, the execution of the loop ends.
At the end of each iteration, expr3 is evaluated (executed).
Each of the expressions can be empty or contain multiple expressions
separated by commas. In expr2, all expressions separated by a comma are
evaluated but the result is taken from the last part. expr2 being empty
means the loop should be run indefinitely (PHP implicitly considers it as
TRUE, like C). This may not be as useless as you might think, since often
you'd want to end the loop using a conditional break statement instead of
using the for truth expression.
Consider the following examples. All of them display the numbers 1 through
10:
10) {
break;
}
echo $i;
}
/* example 3 */
$i = 1;
for (; ; ) {
if ($i > 10) {
break;
}
echo $i;
$i++;
}
/* example 4 */
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
?>
Of course, the first example appears to be the nicest one (or perhaps the
fourth), but you may find that being able to use empty expressions in for
loops comes in handy in many occasions.
PHP also supports the alternate "colon syntax" for for loops.
for (expr1; expr2; expr3):
statement
...
endfor;
Its a common thing to many users to iterate though arrays like in the
example below.
'Kalle', 'salt' => 856412),
Array('name' => 'Pierre', 'salt' => 215863)
);
for($i = 0; $i < sizeof($people); ++$i)
{
$people[$i]['salt'] = rand(000000, 999999);
}
?>
The problem lies in the second for expression. This code can be slow
because it has to calculate the size of the array on each iteration. Since
the size never change, it can be optimized easily using an intermediate
variable to store the size and use in the loop instead of sizeof. The
example below illustrates this:
'Kalle', 'salt' => 856412),
Array('name' => 'Pierre', 'salt' => 215863)
);
for($i = 0, $size = sizeof($people); $i < $size; ++$i)
{
$people[$i]['salt'] = rand(000000, 999999);
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
foreach
PHP 4 introduced a foreach construct, much like Perl and some other
languages. This simply gives an easy way to iterate over arrays. foreach
works only on arrays, and will issue an error when you try to use it on a
variable with a different data type or an uninitialized variable. There
are two syntaxes; the second is a minor but useful extension of the first:
foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement
The first form loops over the array given by array_expression. On each
loop, the value of the current element is assigned to $value and the
internal array pointer is advanced by one (so on the next loop, you'll be
looking at the next element).
The second form does the same thing, except that the current element's key
will be assigned to the variable $key on each loop.
As of PHP 5, it is possible to iterate objects too.
Note:
When foreach first starts executing, the internal array pointer is
automatically reset to the first element of the array. This means that
you do not need to call reset() before a foreach loop.
Note:
Unless the array is referenced, foreach operates on a copy of the
specified array and not the array itself. foreach has some side effects
on the array pointer. Don't rely on the array pointer during or after
the foreach without resetting it.
As of PHP 5, you can easily modify array's elements by preceding $value
with &. This will assign reference instead of copying the value.
This is possible only if iterated array can be referenced (i.e. is
variable), that means the following code won't work:
Warning
Reference of a $value and the last array element remain even after the
foreach loop. It is recommended to destroy it by unset().
Note:
foreach does not support the ability to suppress error messages using
'@'.
You may have noticed that the following are functionally identical:
\n";
}
foreach ($arr as $value) {
echo "Value: $value \n";
}
?>
The following are also functionally identical:
\n";
}
foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value \n";
}
?>
Some more examples to demonstrate usages:
$v.\n";
$i++;
}
/* foreach example 3: key and value */
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);
foreach ($a as $k => $v) {
echo "\$a[$k] => $v.\n";
}
/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";
foreach ($a as $v1) {
foreach ($v1 as $v2) {
echo "$v2\n";
}
}
/* foreach example 5: dynamic arrays */
foreach (array(1, 2, 3, 4, 5) as $v) {
echo "$v\n";
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
break
break ends execution of the current for, foreach, while, do-while or
switch structure.
break accepts an optional numeric argument which tells it how many nested
enclosing structures are to be broken out of.
\n";
}
/* Using the optional argument. */
$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "At 5 \n";
break 1; /* Exit only the switch. */
case 10:
echo "At 10; quitting \n";
break 2; /* Exit the switch and the while. */
default:
break;
}
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
continue
continue is used within looping structures to skip the rest of the current
loop iteration and continue execution at the condition evaluation and then
the beginning of the next iteration.
Note: Note that in PHP the switch statement is considered a looping
structure for the purposes of continue.
continue accepts an optional numeric argument which tells it how many
levels of enclosing loops it should skip to the end of.
Note:
continue 0; and continue 1; is the same as running continue;.
\n";
while (1) {
echo " Middle \n";
while (1) {
echo " Inner \n";
continue 3;
}
echo "This never gets output. \n";
}
echo "Neither does this. \n";
}
?>
Omitting the semicolon after continue can lead to confusion. Here's an
example of what you shouldn't do.
One can expect the result to be:
0
1
3
4
but this script will output:
2
because the entire continue print "$i\n"; is evaluated as a single
expression, and so print() is called only when $i == 2 is true. (The
return value of print is passed to continue as the numeric argument.)
----------------------------------------------------------------------
----------------------------------------------------------------------
switch
The switch statement is similar to a series of IF statements on the same
expression. In many occasions, you may want to compare the same variable
(or expression) with many different values, and execute a different piece
of code depending on which value it equals to. This is exactly what the
switch statement is for.
Note: Note that unlike some other languages, the continue statement
applies to switch and acts similar to break. If you have a switch inside
a loop and wish to continue to the next iteration of the outer loop, use
continue 2.
Note:
Note that switch/case does loose comparision.
The following two examples are two different ways to write the same thing,
one using a series of if and elseif statements, and the other using the
switch statement:
Example #1 switch structure
Example #2 switch structure allows usage of strings
It is important to understand how the switch statement is executed in
order to avoid mistakes. The switch statement executes line by line
(actually, statement by statement). In the beginning, no code is executed.
Only when a case statement is found with a value that matches the value of
the switch expression does PHP begin to execute the statements. PHP
continues to execute the statements until the end of the switch block, or
the first time it sees a break statement. If you don't write a break
statement at the end of a case's statement list, PHP will go on executing
the statements of the following case. For example:
Here, if $i is equal to 0, PHP would execute all of the echo statements!
If $i is equal to 1, PHP would execute the last two echo statements. You
would get the expected behavior ('i equals 2' would be displayed) only if
$i is equal to 2. Thus, it is important not to forget break statements
(even though you may want to avoid supplying them on purpose under certain
circumstances).
In a switch statement, the condition is evaluated only once and the result
is compared to each case statement. In an elseif statement, the condition
is evaluated again. If your condition is more complicated than a simple
compare and/or is in a tight loop, a switch may be faster.
The statement list for a case can also be empty, which simply passes
control into the statement list for the next case.
A special case is the default case. This case matches anything that wasn't
matched by the other cases. For example:
The case expression may be any expression that evaluates to a simple type,
that is, integer or floating-point numbers and strings. Arrays or objects
cannot be used here unless they are dereferenced to a simple type.
The alternative syntax for control structures is supported with switches.
For more information, see Alternative syntax for control structures.
Its possible to use a semicolon instead of a colon after a case like:
----------------------------------------------------------------------
----------------------------------------------------------------------
declare
The declare construct is used to set execution directives for a block of
code. The syntax of declare is similar to the syntax of other flow control
constructs:
declare (directive)
statement
The directive section allows the behavior of the declare block to be set.
Currently only two directives are recognized: the ticks directive (See
below for more information on the ticks directive) and the encoding
directive (See below for more information on the encoding directive).
Note: The encoding directive was added in PHP 5.3.0
The statement part of the declare block will be executed - how it is
executed and what side effects occur during execution may depend on the
directive set in the directive block.
The declare construct can also be used in the global scope, affecting all
code following it (however if the file with declare was included then it
does not affect the parent file).
Ticks
A tick is an event that occurs for every N low-level tickable statements
executed by the parser within the declare block. The value for N is
specified using ticks=N within the declare blocks's directive section.
Not all statements are tickable. Typically, condition expressions and
argument expressions are not tickable.
The event(s) that occur on each tick are specified using the
register_tick_function(). See the example below for more details. Note
that more than one event can occur for each tick.
Example #1 Tick usage example
0) {
$a += 2;
print($a);
}
?>
Example #2 Ticks usage example
0) {
$a += 2;
tick_handler();
print($a);
tick_handler();
}
tick_handler();
?>
See also register_tick_function() and unregister_tick_function().
Encoding
A script's encoding can be specified per-script using the encoding
directive.
Example #3 Declaring an encoding for the script.
Caution
When combined with namespaces, the only legal syntax for declare is
declare(encoding='...'); where ... is the encoding value.
declare(encoding='...') {} will result in a parse error when combined with
namespaces.
The encoding declare value is ignored in PHP 5.3 unless php is compiled
with --enable-zend-multibyte.
Note that PHP does not expose whether --enable-zend-multibyte was used to
compile PHP other than by phpinfo().
----------------------------------------------------------------------
----------------------------------------------------------------------
return
If called from within a function, the return() statement immediately ends
execution of the current function, and returns its argument as the value
of the function call. return() will also end the execution of an eval()
statement or script file.
If called from the global scope, then execution of the current script file
is ended. If the current script file was include()ed or require()ed, then
control is passed back to the calling file. Furthermore, if the current
script file was include()ed, then the value given to return() will be
returned as the value of the include() call. If return() is called from
within the main script file, then script execution ends. If the current
script file was named by the auto_prepend_file or auto_append_file
configuration options in php.ini, then that script file's execution is
ended.
For more information, see Returning values.
Note: Note that since return() is a language construct and not a
function, the parentheses surrounding its arguments are not required. It
is common to leave them out, and you actually should do so as PHP has
less work to do in this case.
Note: If no parameter is supplied, then the parentheses must be omitted
and NULL will be returned. Calling return() with parentheses but with no
arguments will result in a parse error.
Note: You should never use parentheses around your return variable when
returning by reference, as this will not work. You can only return
variables by reference, not the result of a statement. If you use return
($a); then you're not returning a variable, but the result of the
expression ($a) (which is, of course, the value of $a).
----------------------------------------------------------------------
----------------------------------------------------------------------
require()
require() is identical to include() except upon failure it will also
produce a fatal E_COMPILE_ERROR level error. In other words, it will halt
the script whereas include() only emits a warning (E_WARNING) which allows
the script to continue.
See the include() documentation for how this works.
----------------------------------------------------------------------
----------------------------------------------------------------------
include()
The include() statement includes and evaluates the specified file.
The documentation below also applies to require().
Files are included based on the file path given or, if none is given, the
include_path specified. If the file isn't found in the include_path,
include() will finally check in the calling script's own directory and the
current working directory before failing. The include() construct will
emit a warning if it cannot find a file; this is different behavior from
require(), which will emit a fatal error.
If a path is defined - whether absolute (starting with a drive letter or \
on Windows, or / on Unix/Linux systems) or relative to the current
directory (starting with . or ..) - the include_path will be ignored
altogether. For example, if a filename begins with ../, the parser will
look in the parent directory to find the requested file.
For more information on how PHP handles including files and the include
path, see the documentation for include_path.
When a file is included, the code it contains inherits the variable scope
of the line on which the include occurs. Any variables available at that
line in the calling file will be available within the called file, from
that point forward. However, all functions and classes defined in the
included file have the global scope.
Example #1 Basic include() example
vars.php
test.php
If the include occurs inside a function within the calling file, then all
of the code contained in the called file will behave as though it had been
defined inside that function. So, it will follow the variable scope of
that function. An exception to this rule are magic constants which are
evaluated by the parser before the include occurs.
Example #2 Including within functions
When a file is included, parsing drops out of PHP mode and into HTML mode
at the beginning of the target file, and resumes again at the end. For
this reason, any code inside the target file which should be executed as
PHP code must be enclosed within valid PHP start and end tags.
If "URL fopen wrappers" are enabled in PHP (which they are in the default
configuration), you can specify the file to be included using a URL (via
HTTP or other supported wrapper - see Supported Protocols and Wrappers for
a list of protocols) instead of a local pathname. If the target server
interprets the target file as PHP code, variables may be passed to the
included file using a URL request string as used with HTTP GET. This is
not strictly speaking the same thing as including the file and having it
inherit the parent file's variable scope; the script is actually being run
on the remote server and the result is then being included into the local
script.
Warning
Windows versions of PHP prior to PHP 4.3.0 do not support access of remote
files via this function, even if allow_url_fopen is enabled.
Example #3 include() through HTTP
Warning
Security warning
Remote file may be processed at the remote server (depending on the file
extension and the fact if the remote server runs PHP or not) but it still
has to produce a valid PHP script because it will be processed at the
local server. If the file from the remote server should be processed there
and outputted only, readfile() is much better function to use. Otherwise,
special care should be taken to secure the remote script to produce a
valid and desired code.
See also Remote files, fopen() and file() for related information.
Handling Returns: It is possible to execute a return() statement inside an
included file in order to terminate processing in that file and return to
the script which called it. Also, it's possible to return values from
included files. You can take the value of the include call as you would a
normal function. This is not, however, possible when including remote
files unless the output of the remote file has valid PHP start and end
tags (as with any local file). You can declare the needed variables within
those tags and they will be introduced at whichever point the file was
included.
Because include() is a special language construct, parentheses are not
needed around its argument. Take care when comparing return value.
Example #4 Comparing return value of include
Example #5 include() and the return() statement
return.php
noreturn.php
testreturns.php
$bar is the value 1 because the include was successful. Notice the
difference between the above examples. The first uses return() within the
included file while the other does not. If the file can't be included,
FALSE is returned and E_WARNING is issued.
If there are functions defined in the included file, they can be used in
the main file independent if they are before return() or after. If the
file is included twice, PHP 5 issues fatal error because functions were
already declared, while PHP 4 doesn't complain about functions defined
after return(). It is recommended to use include_once() instead of
checking if the file was already included and conditionally return inside
the included file.
Another way to "include" a PHP file into a variable is to capture the
output by using the Output Control Functions with include(). For example:
Example #6 Using output buffering to include a PHP file into a string
In order to automatically include files within scripts, see also the
auto_prepend_file and auto_append_file configuration options in php.ini.
Note: Because this is a language construct and not a function, it cannot
be called using variable functions
See also require(), require_once(), include_once(), get_included_files(),
readfile(), virtual(), and include_path.
----------------------------------------------------------------------
----------------------------------------------------------------------
require_once()
The require_once() statement is identical to require() except PHP will
check if the file has already been included, and if so, not include
(require) it again.
See the include_once() documentation for information about the _once
behaviour, and how it differs from its non _once siblings.
----------------------------------------------------------------------
----------------------------------------------------------------------
include_once()
The include_once() statement includes and evaluates the specified file
during the execution of the script. This is a behavior similar to the
include() statement, with the only difference being that if the code from
a file has already been included, it will not be included again. As the
name suggests, it will be included just once.
include_once() may be used in cases where the same file might be included
and evaluated more than once during a particular execution of a script, so
in this case it may help avoid problems such as function redefinitions,
variable value reassignments, etc.
See the include() documentation for information about how this function
works.
Note:
With PHP 4, _once functionality differs with case-insensitive operating
systems (like Windows) so for example:
Example #1 include_once() with a case insensitive OS in PHP 4
This behaviour changed in PHP 5, so for example with Windows the path is
normalized first so that C:\PROGRA~1\A.php is realized the same as
C:\Program Files\a.php and the file is included just once.
----------------------------------------------------------------------
----------------------------------------------------------------------
goto
The goto operator can be used to jump to another section in the program.
The target point is specified by a label followed by a colon, and the
instruction is given as goto followed by the desired target label. This is
not a full unrestricted goto. The target label must be within the same
file and context, meaning that you cannot jump out of a function or
method, nor can you jump into one. You also cannot jump into any sort of
loop or switch structure. You may jump out of these, and a common use is
to use a goto in place of a multi-level break.
Example #1 goto example
The above example will output:
Bar
Example #2 goto loop example
The above example will output:
j hit 17
Example #3 This will not work
The above example will output:
Fatal error: 'goto' into loop or switch statement is disallowed in
script on line 2
Note:
The goto operator is available as of PHP 5.3.
What's the worse thing that could happen if you use goto?
Image courtesy of >> xkcd
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Functions
Table of Contents
* User-defined functions
* Function arguments
* Returning values
* Variable functions
* Internal (built-in) functions
* Anonymous functions
----------------------------------------------------------------------
User-defined functions
A function may be defined using syntax such as the following:
Example #1 Pseudo code to demonstrate function uses
Any valid PHP code may appear inside a function, even other functions and
class definitions.
Function names follow the same rules as other labels in PHP. A valid
function name starts with a letter or underscore, followed by any number
of letters, numbers, or underscores. As a regular expression, it would be
expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.
Tip
See also the Userland Naming Guide.
Functions need not be defined before they are referenced, except when a
function is conditionally defined as shown in the two examples below.
When a function is defined in a conditional manner such as the two
examples shown. Its definition must be processed prior to being called.
Example #2 Conditional functions
Example #3 Functions within functions
All functions and classes in PHP have the global scope - they can be
called outside a function even if they were defined inside and vice versa.
PHP does not support function overloading, nor is it possible to undefine
or redefine previously-declared functions.
Note: Function names are case-insensitive, though it is usually good
form to call functions as they appear in their declaration.
Both variable number of arguments and default arguments are supported in
functions. See also the function references for func_num_args(),
func_get_arg(), and func_get_args() for more information.
It is possible to call recursive functions in PHP. However avoid recursive
function/method calls with over 100-200 recursion levels as it can smash
the stack and cause a termination of the current script.
Example #4 Recursive functions
----------------------------------------------------------------------
----------------------------------------------------------------------
Function arguments
Information may be passed to functions via the argument list, which is a
comma-delimited list of expressions.
PHP supports passing arguments by value (the default), passing by
reference, and default argument values. Variable-length argument lists are
also supported, see also the function references for func_num_args(),
func_get_arg(), and func_get_args() for more information.
Example #1 Passing arrays to functions
Making arguments be passed by reference
By default, function arguments are passed by value (so that if the value
of the argument within the function is changed, it does not get changed
outside of the function). To allow a function to modify its arguments,
they must be passed by reference.
To have an argument to a function always passed by reference, prepend an
ampersand (&) to the argument name in the function definition:
Example #2 Passing function parameters by reference
Default argument values
A function may define C++-style default values for scalar arguments as
follows:
Example #3 Use of default parameters in functions
The above example will output:
Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.
PHP also allows the use of arrays and the special type NULL as default
values, for example:
Example #4 Using non-scalar types as default values
The default value must be a constant expression, not (for example) a
variable, a class member or a function call.
Note that when using default arguments, any defaults should be on the
right side of any non-default arguments; otherwise, things will not work
as expected. Consider the following code snippet:
Example #5 Incorrect usage of default function arguments
The above example will output:
Warning: Missing argument 2 in call to makeyogurt() in
/usr/local/etc/httpd/htdocs/phptest/functest.html on line 41
Making a bowl of raspberry .
Now, compare the above with this:
Example #6 Correct usage of default function arguments
The above example will output:
Making a bowl of acidophilus raspberry.
Note: As of PHP 5, default values may be passed by reference.
Variable-length argument lists
PHP 4 and above has support for variable-length argument lists in
user-defined functions. This is really quite easy, using the
func_num_args(), func_get_arg(), and func_get_args() functions.
No special syntax is required, and argument lists may still be explicitly
provided with function definitions and will behave as normal.
----------------------------------------------------------------------
----------------------------------------------------------------------
Returning values
Values are returned by using the optional return statement. Any type may
be returned, including arrays and objects. This causes the function to end
its execution immediately and pass control back to the line from which it
was called. See return() for more information.
Note:
If the return() is omitted the value NULL will be returned.
Example #1 Use of return()
A function can not return multiple values, but similar results can be
obtained by returning an array.
Example #2 Returning an array to get multiple values
To return a reference from a function, use the reference operator & in
both the function declaration and when assigning the returned value to a
variable:
Example #3 Returning a reference from a function
For more information on references, please check out References Explained.
----------------------------------------------------------------------
----------------------------------------------------------------------
Variable functions
PHP supports the concept of variable functions. This means that if a
variable name has parentheses appended to it, PHP will look for a function
with the same name as whatever the variable evaluates to, and will attempt
to execute it. Among other things, this can be used to implement
callbacks, function tables, and so forth.
Variable functions won't work with language constructs such as echo(),
print(), unset(), isset(), empty(), include(), require() and the like.
Utilize wrapper functions to make use of any of these constructs as
variable functions.
Example #1 Variable function example
\n";
}
function bar($arg = '')
{
echo "In bar(); argument was '$arg'. \n";
}
// This is a wrapper function around echo
function echoit($string)
{
echo $string;
}
$func = 'foo';
$func(); // This calls foo()
$func = 'bar';
$func('test'); // This calls bar()
$func = 'echoit';
$func('test'); // This calls echoit()
?>
An object method can also be called with the variable functions syntax.
Example #2 Variable method example
$name(); // This calls the Bar() method
}
function Bar()
{
echo "This is Bar";
}
}
$foo = new Foo();
$funcname = "Variable";
$foo->$funcname(); // This calls $foo->Variable()
?>
When calling static methods, the function call is stronger than the static
property operator:
Example #3 Variable method example with static properties
Variable() reading $variable in this scope.
?>
See also call_user_func(), variable variables and function_exists().
----------------------------------------------------------------------
----------------------------------------------------------------------
Internal (built-in) functions
PHP comes standard with many functions and constructs. There are also
functions that require specific PHP extensions compiled in, otherwise
fatal "undefined function" errors will appear. For example, to use image
functions such as imagecreatetruecolor(), PHP must be compiled with GD
support. Or, to use mysql_connect(), PHP must be compiled with MySQL
support. There are many core functions that are included in every version
of PHP, such as the string and variable functions. A call to phpinfo() or
get_loaded_extensions() will show which extensions are loaded into PHP.
Also note that many extensions are enabled by default and that the PHP
manual is split up by extension. See the configuration, installation, and
individual extension chapters, for information on how to set up PHP.
Reading and understanding a function's prototype is explained within the
manual section titled how to read a function definition. It's important to
realize what a function returns or if a function works directly on a
passed in value. For example, str_replace() will return the modified
string while usort() works on the actual passed in variable itself. Each
manual page also has specific information for each function like
information on function parameters, behavior changes, return values for
both success and failure, and availability information. Knowing these
important (yet often subtle) differences is crucial for writing correct
PHP code.
Note: If the parameters given to a function are not what it expects,
such as passing an array where a string is expected, the return value of
the function is undefined. In this case it will likely return NULL but
this is just a convention, and cannot be relied upon.
See also function_exists(), the function reference, get_extension_funcs(),
and dl().
----------------------------------------------------------------------
----------------------------------------------------------------------
Anonymous functions
Anonymous functions, also known as closures, allow the creation of
functions which have no specified name. They are most useful as the value
of callback parameters, but they have many other uses.
Example #1 Anonymous function example
Closures can also be used as the values of variables; PHP automatically
converts such expressions into instances of the Closure internal class.
Assigning a closure to a variable uses the same syntax as any other
assignment, including the trailing semicolon:
Example #2 Anonymous function variable assignment example
Closures may also inherit variables from the parent scope. Any such
variables must be declared in the function header. Inheriting variables
from the parent scope is not the same as using global variables. Global
variables exist in the global scope, which is the same no matter what
function is executing. The parent scope of a closure is the function in
which the closure was declared (not necessarily the function it was called
from). See the following example:
Example #3 Closures and scoping
products[$product] = $quantity;
}
public function getQuantity($product)
{
return isset($this->products[$product]) ? $this->products[$product] :
FALSE;
}
public function getTotal($tax)
{
$total = 0.00;
$callback =
function ($quantity, $product) use ($tax, &$total)
{
$pricePerItem = constant(__CLASS__ . "::PRICE_" .
strtoupper($product));
$total += ($pricePerItem * $quantity) * ($tax + 1.0);
};
array_walk($this->products, $callback);
return round($total, 2);
}
}
$my_cart = new Cart;
// Add some items to the cart
$my_cart->add('butter', 1);
$my_cart->add('milk', 3);
$my_cart->add('eggs', 6);
// Print the total with a 5% sales tax.
print $my_cart->getTotal(0.05) . "\n";
// The result is 54.29
?>
Anonymous functions are currently implemented using the Closure class.
This is an implementation detail and should not be relied upon.
Note: Anonymous functions are available since PHP 5.3.0.
Note: It was not possible to use $this from anonymous function before
PHP 5.4.0.
Note: It is possible to use func_num_args(), func_get_arg(), and
func_get_args() from within a closure.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Classes and Objects
Table of Contents
* Introduction
* The Basics
* Properties
* Class Constants
* Autoloading Classes
* Constructors and Destructors
* Visibility
* Object Inheritance
* Scope Resolution Operator (::)
* Static Keyword
* Class Abstraction
* Object Interfaces
* Overloading
* Object Iteration
* Patterns
* Magic Methods
* Final Keyword
* Object Cloning
* Comparing Objects
* Type Hinting
* Late Static Bindings
* Objects and references
* Object Serialization
* OOP Changelog
----------------------------------------------------------------------
Introduction
Starting with PHP 5, the object model was rewritten to allow for better
performance and more features. This was a major change from PHP 4. PHP 5
has a full object model.
Among the features in PHP 5 are the inclusions of visibility, abstract and
final classes and methods, additional magic methods, interfaces, cloning
and typehinting.
PHP treats objects in the same way as references or handles, meaning that
each variable contains an object reference rather than a copy of the
entire object. See Objects and References
Tip
See also the Userland Naming Guide.
----------------------------------------------------------------------
----------------------------------------------------------------------
The Basics
class
Basic class definitions begin with the keyword class, followed by a class
name, followed by a pair of curly braces which enclose the definitions of
the properties and methods belonging to the class.
The class name can be any valid label which is a not a PHP reserved word.
A valid class name starts with a letter or underscore, followed by any
number of letters, numbers, or underscores. As a regular expression, it
would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.
A class may contain its own constants, variables (called "properties"),
and functions (called "methods").
Example #1 Simple Class definition
var;
}
}
?>
The pseudo-variable $this is available when a method is called from within
an object context. $this is a reference to the calling object (usually the
object to which the method belongs, but possibly another object, if the
method is called statically from the context of a secondary object).
Example #2 Some examples of the $this pseudo-variable
foo();
// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
$b = new B();
$b->bar();
// Note: the next line will issue a warning if E_STRICT is enabled.
B::bar();
?>
The above example will output:
$this is defined (A)
$this is not defined.
$this is defined (B)
$this is not defined.
new
To create an instance of a class, the new keyword must be used. An object
will always be created unless the object has a constructor defined that
throws an exception on error. Classes should be defined before
instantiation (and in some cases this is a requirement).
If a string containing the name of a class is used with new, a new
instance of that class will be created. If the class is in a namespace,
its fully qualified name must be used when doing this.
Example #3 Creating an instance
In the class context, it is possible to create a new object by new self
and new parent.
When assigning an already created instance of a class to a new variable,
the new variable will access the same instance as the object that was
assigned. This behaviour is the same when passing instances to a function.
A copy of an already created object can be made by cloning it.
Example #4 Object Assignment
var = '$assigned will have this value';
$instance = null; // $instance and $reference become null
var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>
The above example will output:
NULL
NULL
object(SimpleClass)#1 (1) {
["var"]=>
string(30) "$assigned will have this value"
}
PHP 5.3.0 introduced a couple of new ways to create instances of an
object:
Example #5 Creating new objects
The above example will output:
bool(true)
bool(true)
bool(true)
extends
A class can inherit the methods and properties of another class by using
the keyword extends in the class declaration. It is not possible to extend
multiple classes; a class can only inherit from one base class.
The inherited methods and properties can be overridden by redeclaring them
with the same name defined in the parent class. However, if the parent
class has defined a method as final, that method may not be overridden. It
is possible to access the overridden methods or static properties by
referencing them with parent::.
When overriding methods, the parameter signature should remain the same or
PHP will generate an E_STRICT level error. This does not apply to the
constructor, which allows overriding with different parameters.
Example #6 Simple Class Inheritance
displayVar();
?>
The above example will output:
Extending class
a default value
----------------------------------------------------------------------
----------------------------------------------------------------------
Properties
Class member variables are called "properties". You may also see them
referred to using other terms such as "attributes" or "fields", but for
the purposes of this reference we will use "properties". They are defined
by using one of the keywords public, protected, or private, followed by a
normal variable declaration. This declaration may include an
initialization, but this initialization must be a constant value--that is,
it must be able to be evaluated at compile time and must not depend on
run-time information in order to be evaluated.
See Visibility for more information on the meanings of public, protected,
and private.
Note:
In order to maintain backward compatibility with PHP 4, PHP 5 will still
accept the use of the keyword var in property declarations instead of
(or in addition to) public, protected, or private. However, var is no
longer required. In versions of PHP from 5.0 to 5.1.3, the use of var
was considered deprecated and would issue an E_STRICT warning, but since
PHP 5.1.3 it is no longer deprecated and does not issue the warning.
If you declare a property using var instead of one of public, protected,
or private, then PHP 5 will treat the property as if it had been
declared as public.
Within class methods the properties, constants, and methods may be
accessed by using the form $this->property (where property is the name of
the property) unless the access is to a static property within the context
of a static class method, in which case it is accessed using the form
self::$property. See Static Keyword for more information.
The pseudo-variable $this is available inside any class method when that
method is called from within an object context. $this is a reference to
the calling object (usually the object to which the method belongs, but
possibly another object, if the method is called statically from the
context of a secondary object).
Example #1 property declarations
Note:
There are some nice functions to handle classes and objects. You might
want to take a look at the Class/Object Functions.
Unlike heredocs, nowdocs can be used in any static data context, including
property declarations.
Example #2 Example of using a nowdoc to initialize a property
Note:
Nowdoc support was added in PHP 5.3.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
Class Constants
It is possible to define constant values on a per-class basis remaining
the same and unchangeable. Constants differ from normal variables in that
you don't use the $ symbol to declare or use them.
The value must be a constant expression, not (for example) a variable, a
property, a result of a mathematical operation, or a function call.
It's also possible for interfaces to have constants. Look at the interface
documentation for examples.
As of PHP 5.3.0, it's possible to reference the class using a variable.
The variable's value can not be a keyword (e.g. self, parent and static).
Example #1 Defining and using a constant
showConstant();
echo $class::constant."\n"; // As of PHP 5.3.0
?>
Example #2 Static data example
Unlike heredocs, nowdocs can be used in any static data context.
Note:
Nowdoc support was added in PHP 5.3.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
Autoloading Classes
Many developers writing object-oriented applications create one PHP source
file per-class definition. One of the biggest annoyances is having to
write a long list of needed includes at the beginning of each script (one
for each class).
In PHP 5, this is no longer necessary. You may define an __autoload
function which is automatically called in case you are trying to use a
class/interface which hasn't been defined yet. By calling this function
the scripting engine is given a last chance to load the class before PHP
fails with an error.
Note:
Prior to 5.3.0, exceptions thrown in the __autoload function could not
be caught in the catch block and would result in a fatal error. From
5.3.0+ exceptions thrown in the __autoload function can be caught in the
catch block, with 1 provision. If throwing a custom exception, then the
custom exception class must be available. The __autoload function may be
used recursively to autoload the custom exception class.
Note:
Autoloading is not available if using PHP in CLI interactive mode.
Note:
If the class name is used e.g. in call_user_func() then it can contain
some dangerous characters such as ../. It is recommended to not use the
user-input in such functions or at least verify the input in
__autoload().
Example #1 Autoload example
This example attempts to load the classes MyClass1 and MyClass2 from the
files MyClass1.php and MyClass2.php respectively.
Example #2 Autoload other example
This example attempts to load the interface ITest.
Example #3 Autoloading with exception handling for 5.3.0+
This example throws an exception and demonstrates the try/catch block.
getMessage(), "\n";
}
?>
The above example will output:
Want to load NonLoadableClass.
Unable to load NonLoadableClass.
Example #4 Autoloading with exception handling for 5.3.0+ - Missing custom
exception
This example throws an exception for a non-loadable, custom exception.
getMessage(), "\n";
}
?>
The above example will output:
Want to load NonLoadableClass.
Want to load MissingException.
Fatal error: Class 'MissingException' not found in testMissingException.php on line 4
See Also
* unserialize()
* unserialize_callback_func
* spl_autoload()
* spl_autoload_register()
----------------------------------------------------------------------
----------------------------------------------------------------------
Constructors and Destructors
Constructor
void __construct ([ mixed $args [, $... ]] )
PHP 5 allows developers to declare constructor methods for classes.
Classes which have a constructor method call this method on each
newly-created object, so it is suitable for any initialization that the
object may need before it is used.
Note: Parent constructors are not called implicitly if the child class
defines a constructor. In order to run a parent constructor, a call to
parent::__construct() within the child constructor is required.
Example #1 using new unified constructors
For backwards compatibility, if PHP 5 cannot find a __construct() function
for a given class, it will search for the old-style constructor function,
by the name of the class. Effectively, it means that the only case that
would have compatibility issues is if the class had a method named
__construct() which was used for different semantics.
Unlike with other methods, PHP will not generate an E_STRICT level error
message when __construct() is overridden with different parameters than
the parent __construct() method has.
As of PHP 5.3.3, methods with the same name as the last element of a
namespaced class name will no longer be treated as constructor. This
change doesn't affect non-namespaced classes.
Example #2 Constructors in namespaced classes
Destructor
void __destruct ( void )
PHP 5 introduces a destructor concept similar to that of other
object-oriented languages, such as C++. The destructor method will be
called as soon as all references to a particular object are removed or
when the object is explicitly destroyed or in any order in shutdown
sequence.
Example #3 Destructor Example
name = "MyDestructableClass";
}
function __destruct() {
print "Destroying " . $this->name . "\n";
}
}
$obj = new MyDestructableClass();
?>
Like constructors, parent destructors will not be called implicitly by the
engine. In order to run a parent destructor, one would have to explicitly
call parent::__destruct() in the destructor body.
The destructor will be called even if script execution is stopped using
exit(). Calling exit() in a destructor will prevent the remaining shutdown
routines from executing.
Note:
Destructors called during the script shutdown have HTTP headers already
sent. The working directory in the script shutdown phase can be
different with some SAPIs (e.g. Apache).
Note:
Attempting to throw an exception from a destructor (called in the time
of script termination) causes a fatal error.
----------------------------------------------------------------------
----------------------------------------------------------------------
Visibility
The visibility of a property or method can be defined by prefixing the
declaration with the keywords public, protected or private. Class members
declared public can be accessed everywhere. Members declared protected can
be accessed only within the class itself and by inherited and parent
classes. Members declared as private may only be accessed by the class
that defines the member.
Property Visibility
Class properties must be defined as public, private, or protected. If
declared using var, the property will be defined as public.
Example #1 Property declaration
public;
echo $this->protected;
echo $this->private;
}
}
$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private
/**
* Define MyClass2
*/
class MyClass2 extends MyClass
{
// We can redeclare the public and protected method, but not private
protected $protected = 'Protected2';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj2 = new MyClass2();
echo $obj2->public; // Works
echo $obj2->private; // Undefined
echo $obj2->protected; // Fatal Error
$obj2->printHello(); // Shows Public, Protected2, Undefined
?>
Note: The PHP 4 method of declaring a variable with the var keyword is
still supported for compatibility reasons (as a synonym for the public
keyword). In PHP 5 before 5.1.3, its usage would generate an E_STRICT
warning.
Method Visibility
Class methods may be defined as public, private, or protected. Methods
declared without any explicit visibility keyword are defined as public.
Example #2 Method Declaration
MyPublic();
$this->MyProtected();
$this->MyPrivate();
}
}
$myclass = new MyClass;
$myclass->MyPublic(); // Works
$myclass->MyProtected(); // Fatal Error
$myclass->MyPrivate(); // Fatal Error
$myclass->Foo(); // Public, Protected and Private work
/**
* Define MyClass2
*/
class MyClass2 extends MyClass
{
// This is public
function Foo2()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate(); // Fatal Error
}
}
$myclass2 = new MyClass2;
$myclass2->MyPublic(); // Works
$myclass2->Foo2(); // Public and Protected work, not Private
class Bar
{
public function test() {
$this->testPrivate();
$this->testPublic();
}
public function testPublic() {
echo "Bar::testPublic\n";
}
private function testPrivate() {
echo "Bar::testPrivate\n";
}
}
class Foo extends Bar
{
public function testPublic() {
echo "Foo::testPublic\n";
}
private function testPrivate() {
echo "Foo::testPrivate\n";
}
}
$myFoo = new foo();
$myFoo->test(); // Bar::testPrivate
// Foo::testPublic
?>
Visibility from other objects
Objects of the same type will have access to each others private and
protected members even though they are not the same instances. This is
because the implementation specific details are already known when inside
those objects.
Example #3 Accessing private members of the same object type
foo = $foo;
}
private function bar()
{
echo 'Accessed the private method.';
}
public function baz(Test $other)
{
// We can change the private property:
$other->foo = 'hello';
var_dump($other->foo);
// We can also call the private method:
$other->bar();
}
}
$test = new Test('test');
$test->baz(new Test('other'));
?>
The above example will output:
string(5) "hello"
Accessed the private method.
----------------------------------------------------------------------
----------------------------------------------------------------------
Object Inheritance
Inheritance is a well-established programming principle, and PHP makes use
of this principle in its object model. This principle will affect the way
many classes and objects relate to one another.
For example, when you extend a class, the subclass inherits all of the
public and protected methods from the parent class. Unless a class
overrides those methods, they will retain their original functionality.
This is useful for defining and abstracting functionality, and permits the
implementation of additional functionality in similar objects without the
need to reimplement all of the shared functionality.
Note:
Unless autoloading is used, then classes must be defined before they are
used. If a class extends another, then the parent class must be declared
before the child class structure. This rule applies to class that
inherit other classes and interfaces.
Example #1 Inheritance Example
printItem('baz'); // Output: 'Foo: baz'
$foo->printPHP(); // Output: 'PHP is great'
$bar->printItem('baz'); // Output: 'Bar: baz'
$bar->printPHP(); // Output: 'PHP is great'
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
Scope Resolution Operator (::)
The Scope Resolution Operator (also called Paamayim Nekudotayim) or in
simpler terms, the double colon, is a token that allows access to static,
constant, and overridden properties or methods of a class.
When referencing these items from outside the class definition, use the
name of the class.
As of PHP 5.3.0, it's possible to reference the class using a variable.
The variable's value can not be a keyword (e.g. self, parent and static).
Paamayim Nekudotayim would, at first, seem like a strange choice for
naming a double-colon. However, while writing the Zend Engine 0.5 (which
powers PHP 3), that's what the Zend team decided to call it. It actually
does mean double-colon - in Hebrew!
Example #1 :: from outside the class definition
Two special keywords self and parent are used to access properties or
methods from inside the class definition.
Example #2 :: from inside the class definition
When an extending class overrides the parents definition of a method, PHP
will not call the parent's method. It's up to the extended class on
whether or not the parent's method is called. This also applies to
Constructors and Destructors, Overloading, and Magic method definitions.
Example #3 Calling a parent's method
myFunc();
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
Static Keyword
Declaring class properties or methods as static makes them accessible
without needing an instantiation of the class. A property declared as
static can not be accessed with an instantiated class object (though a
static method can).
For compatibility with PHP 4, if no visibility declaration is used, then
the property or method will be treated as if it was declared as public.
Because static methods are callable without an instance of the object
created, the pseudo-variable $this is not available inside the method
declared as static.
Static properties cannot be accessed through the object using the arrow
operator ->.
Calling non-static methods statically generates an E_STRICT level warning.
Like any other PHP static variable, static properties may only be
initialized using a literal or constant; expressions are not allowed. So
while you may initialize a static property to an integer or array (for
instance), you may not initialize it to another variable, to a function
return value, or to an object.
As of PHP 5.3.0, it's possible to reference the class using a variable.
The variable's value can not be a keyword (e.g. self, parent and static).
Example #1 Static property example
staticValue() . "\n";
print $foo->my_static . "\n"; // Undefined "Property" my_static
print $foo::$my_static . "\n";
$classname = 'Foo';
print $classname::$my_static . "\n"; // As of PHP 5.3.0
print Bar::$my_static . "\n";
$bar = new Bar();
print $bar->fooStatic() . "\n";
?>
Example #2 Static method example
----------------------------------------------------------------------
----------------------------------------------------------------------
Class Abstraction
PHP 5 introduces abstract classes and methods. Classes defined as abstract
may not be instantiated, and any class that contains at least one abstract
method must also be abstract. Methods defined as abstract simply declare
the method's signature - they cannot define the implementation.
When inheriting from an abstract class, all methods marked abstract in the
parent's class declaration must be defined by the child; additionally,
these methods must be defined with the same (or a less restricted)
visibility. For example, if the abstract method is defined as protected,
the function implementation must be defined as either protected or public,
but not private.
Example #1 Abstract class example
getValue() . "\n";
}
}
class ConcreteClass1 extends AbstractClass
{
protected function getValue() {
return "ConcreteClass1";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass1";
}
}
class ConcreteClass2 extends AbstractClass
{
public function getValue() {
return "ConcreteClass2";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass2";
}
}
$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."\n";
$class2 = new ConcreteClass2;
$class2->printOut();
echo $class2->prefixValue('FOO_') ."\n";
?>
The above example will output:
ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2
Old code that has no user-defined classes or functions named 'abstract'
should run without modifications.
----------------------------------------------------------------------
----------------------------------------------------------------------
Object Interfaces
Object interfaces allow you to create code which specifies which methods a
class must implement, without having to define how these methods are
handled.
Interfaces are defined using the interface keyword, in the same way as a
standard class, but without any of the methods having their contents
defined.
All methods declared in an interface must be public, this is the nature of
an interface.
implements
To implement an interface, the implements operator is used. All methods in
the interface must be implemented within a class; failure to do so will
result in a fatal error. Classes may implement more than one interface if
desired by separating each interface with a comma.
Note:
A class cannot implement two interfaces that share function names, since
it would cause ambiguity.
Note:
Interfaces can be extended like classes using the extends operator.
Note:
The class implementing the interface must use the exact same method
signatures as are defined in the interface. Not doing so will result in
a fatal error.
Constants
Its possible for interfaces to have constants. Interface constants works
exactly like class constants except they cannot be overridden by a
class/interface that inherits it.
Examples
Example #1 Interface example
vars[$name] = $var;
}
public function getHtml($template)
{
foreach($this->vars as $name => $value) {
$template = str_replace('{' . $name . '}', $value, $template);
}
return $template;
}
}
// This will not work
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
private $vars = array();
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
}
?>
Example #2 Extendable Interfaces
Example #3 Multiple interface inheritance
Example #4 Interfaces with constants
An interface, together with type-hinting, provides a good way to make sure
that a particular object contains particular methods. See instanceof
operator and type hinting.
----------------------------------------------------------------------
----------------------------------------------------------------------
Overloading
Overloading in PHP provides means to dynamically "create" properties and
methods. These dynamic entities are processed via magic methods one can
establish in a class for various action types.
The overloading methods are invoked when interacting with properties or
methods that have not been declared or are not visible in the current
scope. The rest of this section will use the terms "inaccessible
properties" and "inaccessible methods" to refer to this combination of
declaration and visibility.
All overloading methods must be defined as public.
Note:
None of the arguments of these magic methods can be passed by reference.
Note:
PHP's interpretation of "overloading" is different than most object
oriented languages. Overloading traditionally provides the ability to
have multiple methods with the same name but different quantities and
types of arguments.
Changelog
Version Description
5.3.0 Added __callStatic(). Added warning to enforce public visibility
and non-static declaration.
5.1.0 Added __isset() and __unset().
Property overloading
void __set ( string $name , mixed $value )
mixed __get ( string $name )
bool __isset ( string $name )
void __unset ( string $name )
__set() is run when writing data to inaccessible properties.
__get() is utilized for reading data from inaccessible properties.
__isset() is triggered by calling isset() or empty() on inaccessible
properties.
__unset() is invoked when unset() is used on inaccessible properties.
The $name argument is the name of the property being interacted with. The
__set() method's $value argument specifies the value the $name'ed property
should be set to.
Property overloading only works in object context. These magic methods
will not be triggered in static context. Therefore these methods should
not be declared static. As of PHP 5.3.0, a warning is issued if one of the
magic overloading methods is declared static.
Note:
The return value of __set() is ignored because of the way PHP processes
the assignment operator. Similarly, __get() is never called when
chaining assignments together like this:
$a = $obj->b = 8;
Note:
It is not possible to use overloaded properties in other language
constructs than isset(). This means if empty() is called on an
overloaded property, the overloaded method is not called.
To workaround that limitation, the overloaded property must be copied
into a local variable in the scope and then be handed to empty().
Example #1 Overloading properties via the __get(), __set(), __isset() and
__unset() methods
data[$name] = $value;
}
public function __get($name) {
echo "Getting '$name'\n";
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
$trace = debug_backtrace();
trigger_error(
'Undefined property via __get(): ' . $name .
' in ' . $trace[0]['file'] .
' on line ' . $trace[0]['line'],
E_USER_NOTICE);
return null;
}
/** As of PHP 5.1.0 */
public function __isset($name) {
echo "Is '$name' set?\n";
return isset($this->data[$name]);
}
/** As of PHP 5.1.0 */
public function __unset($name) {
echo "Unsetting '$name'\n";
unset($this->data[$name]);
}
/** Not a magic method, just here for example. */
public function getHidden() {
return $this->hidden;
}
}
echo "\n";
$obj = new PropertyTest;
$obj->a = 1;
echo $obj->a . "\n\n";
var_dump(isset($obj->a));
unset($obj->a);
var_dump(isset($obj->a));
echo "\n";
echo $obj->declared . "\n\n";
echo "Let's experiment with the private property named 'hidden':\n";
echo "Privates are visible inside the class, so __get() not used...\n";
echo $obj->getHidden() . "\n";
echo "Privates not visible outside of class, so __get() is used...\n";
echo $obj->hidden . "\n";
?>
The above example will output:
Setting 'a' to '1'
Getting 'a'
1
Is 'a' set?
bool(true)
Unsetting 'a'
Is 'a' set?
bool(false)
1
Let's experiment with the private property named 'hidden':
Privates are visible inside the class, so __get() not used...
2
Privates not visible outside of class, so __get() is used...
Getting 'hidden'
Notice: Undefined property via __get(): hidden in on line 70 in on line 29
Method overloading
mixed __call ( string $name , array $arguments )
mixed __callStatic ( string $name , array $arguments )
__call() is triggered when invoking inaccessible methods in an object
context.
__callStatic() is triggered when invoking inaccessible methods in a static
context.
The $name argument is the name of the method being called. The $arguments
argument is an enumerated array containing the parameters passed to the
$name'ed method.
Example #2 Overloading methods via the __call() and __callStatic() methods
runTest('in object context');
MethodTest::runTest('in static context'); // As of PHP 5.3.0
?>
The above example will output:
Calling object method 'runTest' in object context
Calling static method 'runTest' in static context
----------------------------------------------------------------------
----------------------------------------------------------------------
Object Iteration
PHP 5 provides a way for objects to be defined so it is possible to
iterate through a list of items, with, for example a foreach statement. By
default, all visible properties will be used for the iteration.
Example #1 Simple Object Iteration
$value) {
print "$key => $value\n";
}
}
}
$class = new MyClass();
foreach($class as $key => $value) {
print "$key => $value\n";
}
echo "\n";
$class->iterateVisible();
?>
The above example will output:
var1 => value 1
var2 => value 2
var3 => value 3
MyClass::iterateVisible:
var1 => value 1
var2 => value 2
var3 => value 3
protected => protected var
private => private var
As the output shows, the foreach iterated through all visible variables
that can be accessed. To take it a step further you can implement one of
PHP 5's internal interface named Iterator. This allows the object to
decide what and how the object will be iterated.
Example #2 Object Iteration implementing Iterator
var = $array;
}
}
public function rewind()
{
echo "rewinding\n";
reset($this->var);
}
public function current()
{
$var = current($this->var);
echo "current: $var\n";
return $var;
}
public function key()
{
$var = key($this->var);
echo "key: $var\n";
return $var;
}
public function next()
{
$var = next($this->var);
echo "next: $var\n";
return $var;
}
public function valid()
{
$key = key($this->var);
$var = ($key !== NULL && $key !== FALSE);
echo "valid: $var\n";
return $var;
}
}
$values = array(1,2,3);
$it = new MyIterator($values);
foreach ($it as $a => $b) {
print "$a: $b\n";
}
?>
The above example will output:
rewinding
valid: 1
current: 1
key: 0
0: 1
next: 2
valid: 1
current: 2
key: 1
1: 2
next: 3
valid: 1
current: 3
key: 2
2: 3
next:
valid:
You can also define your class so that it doesn't have to define all the
Iterator functions by simply implementing the PHP 5 IteratorAggregate
interface.
Example #3 Object Iteration implementing IteratorAggregate
items);
}
public function add($value) {
$this->items[$this->count++] = $value;
}
}
$coll = new MyCollection();
$coll->add('value 1');
$coll->add('value 2');
$coll->add('value 3');
foreach ($coll as $key => $val) {
echo "key/value: [$key -> $val]\n\n";
}
?>
The above example will output:
rewinding
current: value 1
valid: 1
current: value 1
key: 0
key/value: [0 -> value 1]
next: value 2
current: value 2
valid: 1
current: value 2
key: 1
key/value: [1 -> value 2]
next: value 3
current: value 3
valid: 1
current: value 3
key: 2
key/value: [2 -> value 3]
next:
current:
valid:
Note:
For more examples of iterators, see the SPL Extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Patterns
Patterns are ways to describe best practices and good designs. They show a
flexible solution to common programming problems.
Factory
The Factory pattern allows for the instantiation of objects at runtime. It
is called a Factory Pattern since it is responsible for "manufacturing" an
object. A Parameterized Factory receives the name of the class to
instantiate as argument.
Example #1 Parameterized Factory Method
Defining this method in a class allows drivers to be loaded on the fly. If
the Example class was a database abstraction class, loading a MySQL and
SQLite driver could be done as follows:
Singleton
The Singleton ensures that there can be only one instance of a Class and
provides a global access point to that instance. Singleton is a "Gang of
Four" Creational Pattern.
The Singleton pattern is often implemented in Database Classes, Loggers,
Front Controllers or Request and Response objects.
Example #2 Singleton example
count++;
}
public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
public function __wakeup()
{
trigger_error('Unserializing is not allowed.', E_USER_ERROR);
}
}
?>
Illustrated below is how the Singleton behaves
increment(); // 0
echo $singleton->increment(); // 1
$singleton = Example::singleton(); // reuses existing instance now
echo $singleton->increment(); // 2
echo $singleton->increment(); // 3
// all of these will raise a Fatal Error
$singleton2 = new Example;
$singleton3 = clone $singleton;
$singleton4 = unserialize(serialize($singleton));
?>
Warning
The Singleton pattern is one of the more controversial patterns. Critics
argue that Singletons introduce Global State into an application and
tightly couple the Singleton and its consuming classes. This leads to
hidden dependencies and unexpected side-effects, which in turn leads to
code that is harder to test and maintain.
Critics further argue that it is pointless to use a Singleton in a Shared
Nothing Architecture like PHP where objects are unique within the Request
only anyways. It is easier and cleaner to create collaborator object
graphs by using Builders and Factory patterns once at the beginning of the
Request.
Singletons also violate several of the "SOLID" OOP design principles and
the Law of Demeter. Singletons cannot be serialized. They cannot be
subtyped (before PHP 5.3) and won't be Garbage Collected because of the
instance being stored as a static attribute of the Singleton.
----------------------------------------------------------------------
----------------------------------------------------------------------
Magic Methods
The function names __construct, __destruct, __call, __callStatic, __get,
__set, __isset, __unset, __sleep, __wakeup, __toString, __invoke,
__set_state and __clone are magical in PHP classes. You cannot have
functions with these names in any of your classes unless you want the
magic functionality associated with them.
Caution
PHP reserves all function names starting with __ as magical. It is
recommended that you do not use function names with __ in PHP unless you
want some documented magic functionality.
__sleep and __wakeup
serialize() checks if your class has a function with the magic name
__sleep. If so, that function is executed prior to any serialization. It
can clean up the object and is supposed to return an array with the names
of all variables of that object that should be serialized. If the method
doesn't return anything then NULL is serialized and E_NOTICE is issued.
Note:
It is not possible for __sleep to return names of private properties in
parent classes. Doing this will result in an E_NOTICE level error.
Instead you may use the Serializable interface.
The intended use of __sleep is to commit pending data or perform similar
cleanup tasks. Also, the function is useful if you have very large objects
which do not need to be saved completely.
Conversely, unserialize() checks for the presence of a function with the
magic name __wakeup. If present, this function can reconstruct any
resources that the object may have.
The intended use of __wakeup is to reestablish any database connections
that may have been lost during serialization and perform other
reinitialization tasks.
Example #1 Sleep and wakeup
server = $server;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$this->connect();
}
private function connect()
{
$this->link = mysql_connect($this->server, $this->username, $this->password);
mysql_select_db($this->db, $this->link);
}
public function __sleep()
{
return array('server', 'username', 'password', 'db');
}
public function __wakeup()
{
$this->connect();
}
}
?>
__toString
The __toString method allows a class to decide how it will react when it
is treated like a string. For example, what echo $obj; will print. This
method must return a string, as otherwise a fatal E_RECOVERABLE_ERROR
level error is emitted.
Example #2 Simple example
foo = $foo;
}
public function __toString()
{
return $this->foo;
}
}
$class = new TestClass('Hello');
echo $class;
?>
The above example will output:
Hello
It is worth noting that before PHP 5.2.0 the __toString method was only
called when it was directly combined with echo() or print(). Since PHP
5.2.0, it is called in any string context (e.g. in printf() with %s
modifier) but not in other types contexts (e.g. with %d modifier). Since
PHP 5.2.0, converting objects without __toString method to string would
cause E_RECOVERABLE_ERROR.
__invoke
The __invoke method is called when a script tries to call an object as a
function.
Note:
This feature is available since PHP 5.3.0.
Example #3 Using __invoke
The above example will output:
int(5)
bool(true)
__set_state
This static method is called for classes exported by var_export() since
PHP 5.1.0.
The only parameter of this method is an array containing exported
properties in the form array('property' => value, ...).
Example #4 Using __set_state (since PHP 5.1.0)
var1 = $an_array['var1'];
$obj->var2 = $an_array['var2'];
return $obj;
}
}
$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';
eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
// 'var1' => 5,
// 'var2' => 'foo',
// ));
var_dump($b);
?>
The above example will output:
object(A)#2 (2) {
["var1"]=>
int(5)
["var2"]=>
string(3) "foo"
}
----------------------------------------------------------------------
----------------------------------------------------------------------
Final Keyword
PHP 5 introduces the final keyword, which prevents child classes from
overriding a method by prefixing the definition with final. If the class
itself is being defined final then it cannot be extended.
Example #1 Final methods example
Example #2 Final class example
Note: Properties cannot be declared final, only classes and methods may
be declared as final.
----------------------------------------------------------------------
----------------------------------------------------------------------
Object Cloning
Creating a copy of an object with fully replicated properties is not
always the wanted behavior. A good example of the need for copy
constructors, is if you have an object which represents a GTK window and
the object holds the resource of this GTK window, when you create a
duplicate you might want to create a new window with the same properties
and have the new object hold the resource of the new window. Another
example is if your object holds a reference to another object which it
uses and when you replicate the parent object you want to create a new
instance of this other object so that the replica has its own separate
copy.
An object copy is created by using the clone keyword (which calls the
object's __clone() method if possible). An object's __clone() method
cannot be called directly.
$copy_of_object = clone $object;
When an object is cloned, PHP 5 will perform a shallow copy of all of the
object's properties. Any properties that are references to other
variables, will remain references.
Once the cloning is complete, if a __clone() method is defined, then the
newly created object's __clone() method will be called, to allow any
necessary properties that need to be changed.
Example #1 Cloning an object
instance = ++self::$instances;
}
public function __clone() {
$this->instance = ++self::$instances;
}
}
class MyCloneable
{
public $object1;
public $object2;
function __clone()
{
// Force a copy of this->object, otherwise
// it will point to same object.
$this->object1 = clone $this->object1;
}
}
$obj = new MyCloneable();
$obj->object1 = new SubObject();
$obj->object2 = new SubObject();
$obj2 = clone $obj;
print("Original Object:\n");
print_r($obj);
print("Cloned Object:\n");
print_r($obj2);
?>
The above example will output:
Original Object:
MyCloneable Object
(
[object1] => SubObject Object
(
[instance] => 1
)
[object2] => SubObject Object
(
[instance] => 2
)
)
Cloned Object:
MyCloneable Object
(
[object1] => SubObject Object
(
[instance] => 3
)
[object2] => SubObject Object
(
[instance] => 2
)
)
----------------------------------------------------------------------
----------------------------------------------------------------------
Comparing Objects
In PHP 5, object comparison is more complicated than in PHP 4 and more in
accordance to what one will expect from an Object Oriented Language (not
that PHP 5 is such a language).
When using the comparison operator (==), object variables are compared in
a simple manner, namely: Two object instances are equal if they have the
same attributes and values, and are instances of the same class.
On the other hand, when using the identity operator (===), object
variables are identical if and only if they refer to the same instance of
the same class.
An example will clarify these rules.
Example #1 Example of object comparison in PHP 5
flag = $flag;
}
}
class OtherFlag
{
public $flag;
function OtherFlag($flag = true) {
$this->flag = $flag;
}
}
$o = new Flag();
$p = new Flag();
$q = $o;
$r = new OtherFlag();
echo "Two instances of the same class\n";
compareObjects($o, $p);
echo "\nTwo references to the same instance\n";
compareObjects($o, $q);
echo "\nInstances of two different classes\n";
compareObjects($o, $r);
?>
The above example will output:
Two instances of the same class
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : FALSE
o1 !== o2 : TRUE
Two references to the same instance
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE
Instances of two different classes
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE
Note:
Extensions can define own rules for their objects comparison.
----------------------------------------------------------------------
----------------------------------------------------------------------
Type Hinting
PHP 5 introduces Type Hinting. Functions are now able to force parameters
to be objects (by specifying the name of the class in the function
prototype) or arrays (since PHP 5.1). However, if NULL is used as the
default parameter value, it will be allowed as an argument for any later
call.
Example #1 Type Hinting examples
var;
}
/**
* Another test function
*
* First parameter must be an array
*/
public function test_array(array $input_array) {
print_r($input_array);
}
}
// Another example class
class OtherClass {
public $var = 'Hello World';
}
?>
Failing to satisfy the type hint results in a catchable fatal error.
test('hello');
// Fatal Error: Argument 1 must be an instance of OtherClass
$foo = new stdClass;
$myclass->test($foo);
// Fatal Error: Argument 1 must not be null
$myclass->test(null);
// Works: Prints Hello World
$myclass->test($otherclass);
// Fatal Error: Argument 1 must be an array
$myclass->test_array('a string');
// Works: Prints the array
$myclass->test_array(array('a', 'b', 'c'));
?>
Type hinting also works with functions:
var;
}
// Works
$myclass = new MyClass;
MyFunction($myclass);
?>
Type hinting allowing NULL value:
Type Hints can only be of the object and array (since PHP 5.1) type.
Traditional type hinting with int and string isn't supported.
----------------------------------------------------------------------
----------------------------------------------------------------------
Late Static Bindings
As of PHP 5.3.0, PHP implements a feature called late static bindings
which can be used to reference the called class in a context of static
inheritance.
More precisely, late static bindings work by storing the class named in
the last "non-forwarding call". In case of static method calls, this is
the class explicitly named (usually the one on the left of the ::
operator); in case of non static method calls, it is the class of the
object. A "forwarding call" is a static one that is introduced by self::,
parent::, static::, or, if going up in the class hierarchy,
forward_static_call(). The function get_called_class() can be used to
retrieve a string with the name of the called class and static::
introduces its scope.
This feature was named "late static bindings" with an internal perspective
in mind. "Late binding" comes from the fact that static:: will not be
resolved using the class where the method is defined but it will rather be
computed using runtime information. It was also called a "static binding"
as it can be used for (but is not limited to) static method calls.
Limitations of self::
Static references to the current class like self:: or __CLASS__ are
resolved using the class in which the function belongs, as in where it was
defined:
Example #1 self:: usage
The above example will output:
A
Late Static Bindings' usage
Late static bindings tries to solve that limitation by introducing a
keyword that references the class that was initially called at runtime.
Basically, a keyword that would allow you to reference B from test() in
the previous example. It was decided not to introduce a new keyword but
rather use static that was already reserved.
Example #2 static:: simple usage
The above example will output:
B
Note:
In non-static contexts, the called class will be the class of the object
instance. Since $this-> will try to call private methods from the same
scope, using static:: may give different results. Another difference is
that static:: can only refer to static properties.
Example #3 static:: usage in a non-static context
foo();
static::foo();
}
}
class B extends A {
/* foo() will be copied to B, hence its scope will still be A and
* the call be successful */
}
class C extends A {
private function foo() {
/* original method is replaced; the scope of the new one is C */
}
}
$b = new B();
$b->test();
$c = new C();
$c->test(); //fails
?>
The above example will output:
success!
success!
success!
Fatal error: Call to private method C::foo() from context 'A' in /tmp/test.php on line 9
Note:
Late static bindings' resolution will stop at a fully resolved static
call with no fallback. On the other hand, static calls using keywords
like parent:: or self:: will forward the calling information.
Example #4 Forwarding and non-forwarding calls
The above example will output:
A
C
C
----------------------------------------------------------------------
----------------------------------------------------------------------
Objects and references
One of the key-points of PHP5 OOP that is often mentioned is that "objects
are passed by references by default". This is not completely true. This
section rectifies that general thought using some examples.
A PHP reference is an alias, which allows two different variables to write
to the same value. As of PHP5, an object variable doesn't contain the
object itself as value anymore. It only contains an object identifier
which allows object accessors to find the actual object. When an object is
sent by argument, returned or assigned to another variable, the different
variables are not aliases: they hold a copy of the identifier, which
points to the same object.
Example #1 References and Objects
$b->foo = 2;
echo $a->foo."\n";
$c = new A;
$d = &$c; // $c and $d are references
// ($c,$d) =
$d->foo = 2;
echo $c->foo."\n";
$e = new A;
function foo($obj) {
// ($obj) = ($e) =
$obj->foo = 2;
}
foo($e);
echo $e->foo."\n";
?>
The above example will output:
2
2
2
----------------------------------------------------------------------
----------------------------------------------------------------------
Object Serialization
Serializing objects - objects in sessions
serialize() returns a string containing a byte-stream representation of
any value that can be stored in PHP. unserialize() can use this string to
recreate the original variable values. Using serialize to save an object
will save all variables in an object. The methods in an object will not be
saved, only the name of the class.
In order to be able to unserialize() an object, the class of that object
needs to be defined. That is, if you have an object of class A and
serialize this, you'll get a string that refers to class A and contains
all values of variables contained in it. If you want to be able to
unserialize this in another file, an object of class A, the definition of
class A must be present in that file first. This can be done for example
by storing the class definition of class A in an include file and
including this file or making use of the spl_autoload_register() function.
one;
}
}
// page1.php:
include("classa.inc");
$a = new A;
$s = serialize($a);
// store $s somewhere where page2.php can find it.
file_put_contents('store', $s);
// page2.php:
// this is needed for the unserialize to work properly.
include("classa.inc");
$s = file_get_contents('store');
$a = unserialize($s);
// now use the function show_one() of the $a object.
$a->show_one();
?>
If an application is using sessions and uses session_register() to
register objects, these objects are serialized automatically at the end of
each PHP page, and are unserialized automatically on each of the following
pages. This means that these objects can show up on any of the
application's pages once they become part of the session. However, the
session_register() is removed since PHP 5.4.0.
It is strongly recommended that if an application serializes objects, for
use later in the application, that the application include the class
definition for that object throughout the application. Not doing so might
result in an object being unserialized without a class definition, which
will result in PHP giving the object a class of
__PHP_Incomplete_Class_Name, which has no methods and would render the
object useless.
So if in the example above $a became part of a session by running
session_register("a"), you should include the file classa.inc on all of
your pages, not only page1.php and page2.php.
----------------------------------------------------------------------
----------------------------------------------------------------------
OOP Changelog
Changes to the PHP 5 OOP model are logged here. Descriptions and other
notes regarding these features are documented within the OOP 5
documentation.
Version Description
Changed: Methods with the same name as the last element of a
5.3.3 namespaced class name will no longer be treated as constructor.
This change doesn't affect non-namespaced classes.
Changed: Classes that implement interfaces with methods that have
5.3.0 default values in the prototype are no longer required to match
the interface's default value.
Changed: It's now possible to reference the class using a variable
5.3.0 (e.g., echo $classname::constant;). The variable's value can not
be a keyword (e.g., self, parent or static).
Changed: An E_WARNING level error is issued if the magic
5.3.0 overloading methods are declared static. It also enforces the
public visibility requirement.
Changed: Prior to 5.3.0, exceptions thrown in the __autoload
function could not be caught in the catch block, and would result
in a fatal error. Exceptions now thrown in the __autoload function
5.3.0 can be caught in the catch block, with one proviso. If throwing a
custom exception, then the custom exception class must be
available. The __autoload function may be used recursively to
autoload the custom exception class.
5.3.0 Added: The __callStatic method.
Added: heredoc and nowdoc support for class const and property
5.3.0 definitions. Note: heredoc values must follow the same rules as
double-quoted strings, (e.g., no variables within).
5.3.0 Added: Late Static Bindings.
5.3.0 Added: The __invoke method.
Changed: The __toString method was only called when it was
directly combined with echo() or print(). But now, it is called in
5.2.0 any string context (e.g. in printf() with %s modifier) but not in
other types contexts (e.g. with %d modifier). Since PHP 5.2.0,
converting objects without a __toString method to string emits a
E_RECOVERABLE_ERROR level error.
Changed: In previous versions of PHP 5, the use of var was
5.1.3 considered deprecated and would issue an E_STRICT level error.
It's no longer deprecated, therefore does not emit the error.
5.1.0 Changed: The __set_state static method is now called for classes
exported by var_export().
5.1.0 Added: The __isset and __unset methods.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Namespaces
Table of Contents
* Namespaces overview
* Defining namespaces
* Declaring sub-namespaces
* Defining multiple namespaces in the same file
* Using namespaces: Basics
* Namespaces and dynamic language features
* namespace keyword and __NAMESPACE__ constant
* Using namespaces: Aliasing/Importing
* Global space
* Using namespaces: fallback to global function/constant
* Name resolution rules
* FAQ: things you need to know about namespaces
----------------------------------------------------------------------
Namespaces overview
What are namespaces? In the broadest definition namespaces are a way of
encapsulating items. This can be seen as an abstract concept in many
places. For example, in any operating system directories serve to group
related files, and act as a namespace for the files within them. As a
concrete example, the file foo.txt can exist in both directory /home/greg
and in /home/other, but two copies of foo.txt cannot co-exist in the same
directory. In addition, to access the foo.txt file outside of the
/home/greg directory, we must prepend the directory name to the file name
using the directory separator to get /home/greg/foo.txt. This same
principle extends to namespaces in the programming world.
In the PHP world, namespaces are designed to solve two problems that
authors of libraries and applications encounter when creating re-usable
code elements such as classes or functions:
1. Name collisions between code you create, and internal PHP
classes/functions/constants or third-party
classes/functions/constants.
2. Ability to alias (or shorten) Extra_Long_Names designed to alleviate
the first problem, improving readability of source code.
PHP Namespaces provide a way in which to group related classes, functions
and constants. Here is an example of namespace syntax in PHP:
Example #1 Namespace syntax example
----------------------------------------------------------------------
----------------------------------------------------------------------
Defining namespaces
Although any valid PHP code can be contained within a namespace, only
three type of code are affected by namespaces: classes, functions and
constants.
Namespaces are declared using the namespace keyword. A file containing a
namespace must declare the namespace at the top of the file before any
other code - with one exception: the declare keyword.
Example #1 Declaring a single namespace
The only code construct allowed before a namespace declaration is the
declare statement, for defining encoding of a source file. In addition, no
non-PHP code may precede a namespace declaration, including extra
whitespace:
Example #2 Declaring a single namespace
In addition, unlike any other PHP construct, the same namespace may be
defined in multiple files, allowing splitting up of a namespace's contents
across the filesystem.
----------------------------------------------------------------------
----------------------------------------------------------------------
Declaring sub-namespaces
Much like directories and files, PHP namespaces also contain the ability
to specify a hierarchy of namespace names. Thus, a namespace name can be
defined with sub-levels:
Example #1 Declaring a single namespace with hierarchy
The above example creates constant MyProject\Sub\Level\CONNECT_OK, class
MyProject\Sub\Level\Connection and function MyProject\Sub\Level\connect.
----------------------------------------------------------------------
----------------------------------------------------------------------
Defining multiple namespaces in the same file
Multiple namespaces may also be declared in the same file. There are two
allowed syntaxes.
Example #1 Declaring multiple namespaces, simple combination syntax
This syntax is not recommended for combining namespaces into a single
file. Instead it is recommended to use the alternate bracketed syntax.
Example #2 Declaring multiple namespaces, bracketed syntax
It is strongly discouraged as a coding practice to combine multiple
namespaces into the same file. The primary use case is to combine multiple
PHP scripts into the same file.
To combine global non-namespaced code with namespaced code, only bracketed
syntax is supported. Global code should be encased in a namespace
statement with no namespace name as in:
Example #3 Declaring multiple namespaces and unnamespaced code
No PHP code may exist outside of the namespace brackets except for an
opening declare statement.
Example #4 Declaring multiple namespaces and unnamespaced code
----------------------------------------------------------------------
----------------------------------------------------------------------
Using namespaces: Basics
Before discussing the use of namespaces, it is important to understand how
PHP knows which namespaced element your code is requesting. A simple
analogy can be made between PHP namespaces and a filesystem. There are
three ways to access a file in a file system:
1. Relative file name like foo.txt. This resolves to
currentdirectory/foo.txt where currentdirectory is the directory
currently occupied. So if the current directory is /home/foo, the name
resolves to /home/foo/foo.txt.
2. Relative path name like subdirectory/foo.txt. This resolves to
currentdirectory/subdirectory/foo.txt.
3. Absolute path name like /main/foo.txt. This resolves to /main/foo.txt.
The same principle can be applied to namespaced elements in PHP. For
example, a class name can be referred to in three ways:
1. Unqualified name, or an unprefixed class name like $a = new foo(); or
foo::staticmethod();. If the current namespace is currentnamespace,
this resolves to currentnamespace\foo. If the code is global,
non-namespaced code, this resolves to foo. One caveat: unqualified
names for functions and constants will resolve to global functions and
constants if the namespaced function or constant is not defined. See
Using namespaces: fallback to global function/constant for details.
2. Qualified name, or a prefixed class name like $a = new
subnamespace\foo(); or subnamespace\foo::staticmethod();. If the
current namespace is currentnamespace, this resolves to
currentnamespace\subnamespace\foo. If the code is global,
non-namespaced code, this resolves to subnamespace\foo.
3. Fully qualified name, or a prefixed name with global prefix operator
like $a = new \currentnamespace\foo(); or
\currentnamespace\foo::staticmethod();. This always resolves to the
literal name specified in the code, currentnamespace\foo.
Here is an example of the three kinds of syntax in actual code:
file1.php
file2.php
Note that to access any global class, function or constant, a fully
qualified name can be used, such as \strlen() or \Exception or \INI_ALL.
Example #1 Accessing global classes, functions and constants from within a
namespace
----------------------------------------------------------------------
----------------------------------------------------------------------
Namespaces and dynamic language features
PHP's implementation of namespaces is influenced by its dynamic nature as
a programming language. Thus, to convert code like the following example
into namespaced code:
Example #1 Dynamically accessing elements
example1.php:
One must use the fully qualified name (class name with namespace prefix).
Note that because there is no difference between a qualified and a fully
qualified Name inside a dynamic class name, function name, or constant
name, the leading backslash is not necessary.
Example #2 Dynamically accessing namespaced elements
Be sure to read the note about escaping namespace names in strings.
----------------------------------------------------------------------
----------------------------------------------------------------------
namespace keyword and __NAMESPACE__ constant
PHP supports two ways of abstractly accessing elements within the current
namespace, the __NAMESPACE__ magic constant, and the namespace keyword.
The value of __NAMESPACE__ is a string that contains the current namespace
name. In global, un-namespaced code, it contains an empty string.
Example #1 __NAMESPACE__ example, namespaced code
Example #2 __NAMESPACE__ example, global code
The __NAMESPACE__ constant is useful for dynamically constructing names,
for instance:
Example #3 using __NAMESPACE__ for dynamic name construction
The namespace keyword can be used to explicitly request an element from
the current namespace or a sub-namespace. It is the namespace equivalent
of the self operator for classes.
Example #4 the namespace operator, inside a namespace
Example #5 the namespace operator, in global code
----------------------------------------------------------------------
----------------------------------------------------------------------
Using namespaces: Aliasing/Importing
The ability to refer to an external fully qualified name with an alias, or
importing, is an important feature of namespaces. This is similar to the
ability of unix-based filesystems to create symbolic links to a file or to
a directory.
PHP namespaces support three kinds of aliasing or importing: aliasing a
class name, aliasing an interface name, and aliasing a namespace name.
Note that importing a function or constant is not supported.
In PHP, aliasing is accomplished with the use operator. Here is an example
showing all 3 kinds of importing:
Example #1 importing/aliasing with the use operator
Note that for namespaced names (fully qualified namespace names containing
namespace separator, such as Foo\Bar as opposed to global names that do
not, such as FooBar), the leading backslash is unnecessary and not
recommended, as import names must be fully qualified, and are not
processed relative to the current namespace.
PHP additionally supports a convenience shortcut to place multiple use
statements on the same line
Example #2 importing/aliasing with the use operator, multiple use
statements combined
Importing is performed at compile-time, and so does not affect dynamic
class, function or constant names.
Example #3 Importing and dynamic names
In addition, importing only affects unqualified and qualified names. Fully
qualified names are absolute, and unaffected by imports.
Example #4 Importing and fully qualified names
Scoping rules for importing
The use keyword must be declared in the outermost scope of a file (the
global scope) or inside namespace declarations. This is because the
importing is done at compile time and not runtime, so it cannot be block
scoped. The following example will show an illegal use of the use keyword:
Example #5 Illegal importing rule
Note:
Importing rules are per file basis, meaning included files will NOT
inherit the parent file's importing rules.
----------------------------------------------------------------------
----------------------------------------------------------------------
Global space
Without any namespace definition, all class and function definitions are
placed into the global space - as it was in PHP before namespaces were
supported. Prefixing a name with \ will specify that the name is required
from the global space even in the context of the namespace.
Example #1 Using global space specification
----------------------------------------------------------------------
----------------------------------------------------------------------
Using namespaces: fallback to global function/constant
Inside a namespace, when PHP encounters a unqualified Name in a class
name, function or constant context, it resolves these with different
priorities. Class names always resolve to the current namespace name. Thus
to access internal or non-namespaced user classes, One must refer to them
with their fully qualified Name as in:
Example #1 Accessing global classes inside a namespace
For functions and constants, PHP will fall back to global functions or
constants if a namespaced function or constant does not exist.
Example #2 global functions/constants fallback inside a namespace
----------------------------------------------------------------------
----------------------------------------------------------------------
Name resolution rules
For the purposes of these resolution rules, here are some important
definitions:
Namespace name definitions
Unqualified name
This is an identifier without a namespace separator, such as Foo
Qualified name
This is an identifier with a namespace separator, such as Foo\Bar
Fully qualified name
This is an identifier with a namespace separator that begins with
a namespace separator, such as \Foo\Bar. namespace\Foo is also a
fully qualified name.
Names are resolved following these resolution rules:
1. Calls to fully qualified functions, classes or constants are resolved
at compile-time. For instance new \A\B resolves to class A\B.
2. All unqualified and qualified names (not fully qualified names) are
translated during compilation according to current import rules. For
example, if the namespace A\B\C is imported as C, a call to C\D\e() is
translated to A\B\C\D\e().
3. Inside a namespace, all qualified names not translated according to
import rules have the current namespace prepended. For example, if a
call to C\D\e() is performed within namespace A\B, it is translated to
A\B\C\D\e().
4. Unqualified class names are translated during compilation according to
current import rules (full name substituted for short imported name).
In example, if the namespace A\B\C is imported as C, new C() is
translated to new A\B\C().
5. Inside namespace (say A\B), calls to unqualified functions are
resolved at run-time. Here is how a call to function foo() is
resolved:
1. It looks for a function from the current namespace: A\B\foo().
2. It tries to find and call the global function foo().
6. Inside namespace (say A\B), calls to unqualified or qualified class
names (not fully qualified class names) are resolved at run-time. Here
is how a call to new C() or new D\E() is resolved. For new C():
1. It looks for a class from the current namespace: A\B\C.
2. It attempts to autoload A\B\C.
For new D\E():
1. It looks for a class by prepending the current namespace:
A\B\D\E.
2. It attempts to autoload A\B\D\E.
To reference any global class in the global namespace, its fully
qualified name new \C() must be used.
Example #1 Name resolutions illustrated
----------------------------------------------------------------------
----------------------------------------------------------------------
FAQ: things you need to know about namespaces
This FAQ is split into two sections: common questions, and some specifics
of implementation that are helpful to understand fully.
First, the common questions.
1. If I don't use namespaces, should I care about any of this?
2. How do I use internal or global classes in a namespace?
3. How do I use namespaces classes functions, or constants in their own
namespace?
4. How does a name like \my\name or \name resolve?
5. How does a name like my\name resolve?
6. How does an unqualified class name like name resolve?
7. How does an unqualified function name or unqualified constant name
like name resolve?
There are a few implementation details of the namespace implementations
that are helpful to understand.
1. Import names cannot conflict with classes defined in the same file.
2. Nested namespaces are not allowed.
3. Neither functions nor constants can be imported via the use statement.
4. Dynamic namespace names (quoted identifiers) should escape backslash.
5. Undefined Constants referenced using any backslash die with fatal
error
6. Cannot override special constants NULL, TRUE, FALSE, ZEND_THREAD_SAFE
or ZEND_DEBUG_BUILD
If I don't use namespaces, should I care about any of this?
No. Namespaces do not affect any existing code in any way, or any
as-yet-to-be-written code that does not contain namespaces. You can write
this code if you wish:
Example #1 Accessing global classes outside a namespace
This is functionally equivalent to:
Example #2 Accessing global classes outside a namespace
How do I use internal or global classes in a namespace?
Example #3 Accessing internal classes in namespaces
How do I use namespaces classes, functions, or constants in their own
namespace?
Example #4 Accessing internal classes, functions or constants in
namespaces
How does a name like \my\name or \name resolve?
Names that begin with a \ always resolve to what they look like, so
\my\name is in fact my\name, and \Exception is Exception.
Example #5 Fully Qualified names
How does a name like my\name resolve?
Names that contain a backslash but do not begin with a backslash like
my\name can be resolved in 2 different ways.
If there is an import statement that aliases another name to my, then the
import alias is applied to the my in my\name.
Otherwise, the current namespace name is prepended to my\name.
Example #6 Qualified names
How does an unqualified class name like name resolve?
Class names that do not contain a backslash like name can be resolved in 2
different ways.
If there is an import statement that aliases another name to name, then
the import alias is applied.
Otherwise, the current namespace name is prepended to name.
Example #7 Unqualified class names
How does an unqualified function name or unqualified constant name like name
resolve?
Function or constant names that do not contain a backslash like name can
be resolved in 2 different ways.
First, the current namespace name is prepended to name.
Finally, if the constant or function name does not exist in the current
namespace, a global constant or function name is used if it exists.
Example #8 Unqualified function or constant names
Import names cannot conflict with classes defined in the same file.
The following script combinations are legal:
file1.php
another.php
file2.php
There is no name conflict, even though the class MyClass exists within the
my\stuff namespace, because the MyClass definition is in a separate file.
However, the next example causes a fatal error on name conflict because
MyClass is defined in the same file as the use statement.
Nested namespaces are not allowed.
PHP does not allow nesting namespaces
However, it is easy to simulate nested namespaces like so:
Neither functions nor constants can be imported via the use statement.
The only elements that are affected by use statements are namespaces and
class names. In order to shorten a long constant or function, import its
containing namespace
Dynamic namespace names (quoted identifiers) should escape backslash
It is very important to realize that because the backslash is used as an
escape character within strings, it should always be doubled when used
inside a string. Otherwise there is a risk of unintended consequences:
Example #9 Dangers of using namespaced names inside a double-quoted string
Inside a single-quoted string, the backslash escape sequence is much safer
to use, but it is still recommended practice to escape backslashes in all
strings as a best practice.
Undefined Constants referenced using any backslash die with fatal error
Any undefined constant that is unqualified like FOO will produce a notice
explaining that PHP assumed FOO was the value of the constant. Any
constant, qualified or fully qualified, that contains a backslash will
produce a fatal error if not found.
Example #10 Undefined constants
Cannot override special constants NULL, TRUE, FALSE, ZEND_THREAD_SAFE or
ZEND_DEBUG_BUILD
Any attempt to define a namespaced constant that is a special, built-in
constant results in a fatal error
Example #11 Undefined constants
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Exceptions
Table of Contents
* Extending Exceptions
PHP 5 has an exception model similar to that of other programming
languages. An exception can be thrown, and caught ("catched") within PHP.
Code may be surrounded in a try block, to facilitate the catching of
potential exceptions. Each try must have at least one corresponding catch
block. Multiple catch blocks can be used to catch different classes of
exeptions. Normal execution (when no exception is thrown within the try
block, or when a catch matching the thrown exception's class is not
present) will continue after that last catch block defined in sequence.
Exceptions can be thrown (or re-thrown) within a catch block.
When an exception is thrown, code following the statement will not be
executed, and PHP will attempt to find the first matching catch block. If
an exception is not caught, a PHP Fatal Error will be issued with an
"Uncaught Exception ..." message, unless a handler has been defined with
set_exception_handler().
The thrown object must be an instance of the Exception class or a subclass
of Exception. Trying to throw an object that is not will result in a PHP
Fatal Error.
Note:
Internal PHP functions mainly use Error reporting, only modern Object
oriented extensions use exceptions. However, errors can be simply
translated to exceptions with ErrorException.
Tip
The Standard PHP Library (SPL) provides a good number of built-in
exceptions.
Example #1 Throwing an Exception
getMessage(), "\n";
}
// Continue execution
echo 'Hello World';
?>
The above example will output:
0.2
Caught exception: Division by zero.
Hello World
Example #2 Nested Exception
getMessage());
}
}
}
$foo = new Test;
$foo->testing();
?>
The above example will output:
string(4) "foo!"
----------------------------------------------------------------------
Extending Exceptions
A User defined Exception class can be defined by extending the built-in
Exception class. The members and properties below, show what is accessible
within the child class that derives from the built-in Exception class.
Example #1 The Built in Exception class
If a class extends the built-in Exception class and re-defines the
constructor, it is highly recommended that it also call
parent::__construct() to ensure all available data has been properly
assigned. The __toString() method can be overridden to provide a custom
output when the object is presented as a string.
Note:
Exceptions cannot be cloned. Attempting to clone an Exception will
result in a fatal E_ERROR error.
Example #2 Extending the Exception class (PHP 5.3.0+)
code}]: {$this->message}\n";
}
public function customFunction() {
echo "A custom function for this type of exception\n";
}
}
/**
* Create a class to test the exception
*/
class TestException
{
public $var;
const THROW_NONE = 0;
const THROW_CUSTOM = 1;
const THROW_DEFAULT = 2;
function __construct($avalue = self::THROW_NONE) {
switch ($avalue) {
case self::THROW_CUSTOM:
// throw custom exception
throw new MyException('1 is an invalid parameter', 5);
break;
case self::THROW_DEFAULT:
// throw default one.
throw new Exception('2 is not allowed as a parameter', 6);
break;
default:
// No exception, object will be created.
$this->var = $avalue;
break;
}
}
}
// Example 1
try {
$o = new TestException(TestException::THROW_CUSTOM);
} catch (MyException $e) { // Will be caught
echo "Caught my exception\n", $e;
$e->customFunction();
} catch (Exception $e) { // Skipped
echo "Caught Default Exception\n", $e;
}
// Continue execution
var_dump($o); // Null
echo "\n\n";
// Example 2
try {
$o = new TestException(TestException::THROW_DEFAULT);
} catch (MyException $e) { // Doesn't match this type
echo "Caught my exception\n", $e;
$e->customFunction();
} catch (Exception $e) { // Will be caught
echo "Caught Default Exception\n", $e;
}
// Continue execution
var_dump($o); // Null
echo "\n\n";
// Example 3
try {
$o = new TestException(TestException::THROW_CUSTOM);
} catch (Exception $e) { // Will be caught
echo "Default Exception caught\n", $e;
}
// Continue execution
var_dump($o); // Null
echo "\n\n";
// Example 4
try {
$o = new TestException();
} catch (Exception $e) { // Skipped, no exception
echo "Default Exception caught\n", $e;
}
// Continue execution
var_dump($o); // TestException
echo "\n\n";
?>
Note:
Versions of PHP 5, prior to PHP 5.3.0 do not support nesting of
exceptions. The following code fragment can be used as a replacement
MyException class if you wish to run this example.
code}]: {$this->message}\n";
}
public function customFunction() {
echo "A custom function for this type of exception\n";
}
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
References Explained
Table of Contents
* What References Are
* What References Do
* What References Are Not
* Passing by Reference
* Returning References
* Unsetting References
* Spotting References
----------------------------------------------------------------------
What References Are
References in PHP are a means to access the same variable content by
different names. They are not like C pointers; for instance, you cannot
perform pointer arithmetic using them, they are not actual memory
addresses, and so on. See What References Are Not for more information.
Instead, they are symbol table aliases. Note that in PHP, variable name
and variable content are different, so the same content can have different
names. The closest analogy is with Unix filenames and files - variable
names are directory entries, while variable content is the file itself.
References can be likened to hardlinking in Unix filesystem.
----------------------------------------------------------------------
----------------------------------------------------------------------
What References Do
There are three basic operations performed using references: assigning by
reference, passing by reference, and returning by reference. This section
will give an introduction to these operations, with links to further
reading.
Assign By Reference
In the first of these, PHP references allow you to make two variables
refer to the same content. Meaning, when you do:
it means that $a and $b point to the same content.
Note:
$a and $b are completely equal here. $a is not pointing to $b or vice
versa. $a and $b are pointing to the same place.
Note:
If you assign, pass, or return an undefined variable by reference, it
will get created.
Example #1 Using references with undefined variables
d);
var_dump(property_exists($c, 'd')); // bool(true)
?>
The same syntax can be used with functions that return references, and
with the new operator (since PHP 4.0.4 and before PHP 5.0.0):
Since PHP 5, new returns a reference automatically, so using =& in this
context is deprecated and produces an E_DEPRECATED message in PHP 5.3 and
later, and an E_STRICT message in earlier versions. (Technically, the
difference is that, in PHP 5, object variables, much like resources, are a
mere pointer to the actual object data, so these object references are not
"references" in the same sense used before (aliases). For more
information, see Objects and references.)
Warning
If you assign a reference to a variable declared global inside a function,
the reference will be visible only inside the function. You can avoid this
by using the $GLOBALS array.
Example #2 Referencing global variables inside functions
Think about global $var; as a shortcut to $var =& $GLOBALS['var'];. Thus
assigning another reference to $var only changes the local variable's
reference.
Note:
If you assign a value to a variable with references in a foreach
statement, the references are modified too.
Example #3 References and foreach statement
While not being strictly an assignment by reference, expressions created
with the language construct array() can also behave as such by prefixing &
to the array element to add. Example:
Note, however, that references inside arrays are potentially dangerous.
Doing a normal (not by reference) assignment with a reference on the right
side does not turn the left side into a reference, but references inside
arrays are preserved in these normal assignments. This also applies to
function calls where the array is passed by value. Example:
In other words, the reference behavior of arrays is defined in an
element-by-element basis; the reference behavior of individual elements is
dissociated from the reference status of the array container.
Pass By Reference
The second thing references do is to pass variables by reference. This is
done by making a local variable in a function and a variable in the
calling scope referencing the same content. Example:
will make $a to be 6. This happens because in the function foo the
variable $var refers to the same content as $a. For more information on
this, read the passing by reference section.
Return By Reference
The third thing references can do is return by reference.
----------------------------------------------------------------------
----------------------------------------------------------------------
What References Are Not
As said before, references are not pointers. That means, the following
construct won't do what you expect:
What happens is that $var in foo will be bound with $bar in the caller,
but then re-bound with $GLOBALS["baz"]. There's no way to bind $bar in the
calling scope to something else using the reference mechanism, since $bar
is not available in the function foo (it is represented by $var, but $var
has only variable contents and not name-to-value binding in the calling
symbol table). You can use returning references to reference variables
selected by the function.
----------------------------------------------------------------------
----------------------------------------------------------------------
Passing by Reference
You can pass a variable by reference to a function so the function can
modify the variable. The syntax is as follows:
Note: There is no reference sign on a function call - only on function
definitions. Function definitions alone are enough to correctly pass the
argument by reference. As of PHP 5.3.0, you will get a warning saying
that "call-time pass-by-reference" is deprecated when you use & in
foo(&$a);.
The following things can be passed by reference:
* Variables, i.e. foo($a)
* New statements, i.e. foo(new foobar())
* References returned from functions, i.e.:
See more about returning by reference.
No other expressions should be passed by reference, as the result is
undefined. For example, the following examples of passing by reference are
invalid:
These requirements are for PHP 4.0.4 and later.
----------------------------------------------------------------------
----------------------------------------------------------------------
Returning References
Returning by reference is useful when you want to use a function to find
to which variable a reference should be bound. Do not use
return-by-reference to increase performance. The engine will automatically
optimize this on its own. Only return references when you have a valid
technical reason to do so. To return references, use this syntax:
value;
}
}
$obj = new foo;
$myValue = &$obj->getValue(); // $myValue is a reference to $obj->value, which is 42.
$obj->value = 2;
echo $myValue; // prints the new value of $obj->value, i.e. 2.
?>
In this example, the property of the object returned by the getValue
function would be set, not the copy, as it would be without using
reference syntax.
Note: Unlike parameter passing, here you have to use & in both places -
to indicate that you want to return by reference, not a copy, and to
indicate that reference binding, rather than usual assignment, should be
done for $myValue.
Note: If you try to return a reference from a function with the syntax:
return ($this->value); this will not work as you are attempting to
return the result of an expression, and not a variable, by reference.
You can only return variables by reference from a function - nothing
else. Since PHP 4.4.0 in the PHP4 branch, and PHP 5.1.0 in the PHP5
branch, an E_NOTICE error is issued if the code tries to return a
dynamic expression or a result of the new operator.
To use the returned reference, you must use reference assigment:
To pass the returned reference to another function expecting a reference
you can use this syntax:
Note: Note that array_push(&collector(), 'foo'); will not work, it
results in a fatal error.
----------------------------------------------------------------------
----------------------------------------------------------------------
Unsetting References
When you unset the reference, you just break the binding between variable
name and variable content. This does not mean that variable content will
be destroyed. For example:
won't unset $b, just $a.
Again, it might be useful to think about this as analogous to the Unix
unlink call.
----------------------------------------------------------------------
----------------------------------------------------------------------
Spotting References
Many syntax constructs in PHP are implemented via referencing mechanisms,
so everything mentioned herein about reference binding also applies to
these constructs. Some constructs, like passing and returning by
reference, are mentioned above. Other constructs that use references are:
global References
When you declare a variable as global $var you are in fact creating
reference to a global variable. That means, this is the same as:
This also means that unsetting $var won't unset the global variable.
$this
In an object method, $this is always a reference to the caller object.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Variables
PHP provides a large number of predefined variables to all scripts. The
variables represent everything from external variables to built-in
environment variables, last error messages to last retrieved headers.
See also the FAQ titled "How does register_globals affect me?"
----------------------------------------------------------------------
Superglobals
Superglobals - Superglobals are built-in variables that are always
available in all scopes
Description
Several predefined variables in PHP are "superglobals", which means they
are available in all scopes throughout a script. There is no need to do
global $variable; to access them within functions or methods.
These superglobal variables are:
* $GLOBALS
* $_SERVER
* $_GET
* $_POST
* $_FILES
* $_COOKIE
* $_SESSION
* $_REQUEST
* $_ENV
Changelog
Version Description
4.1.0 Superglobals were introduced to PHP.
Notes
Note: Variable availability
By default, all of the superglobals are available but there are
directives that affect this availability. For further information, refer
to the documentation for variables_order.
Note: Dealing with register_globals
If the deprecated register_globals directive is set to on then the
variables within will also be made available in the global scope of the
script. For example, $_POST['foo'] would also exist as $foo.
For related information, see the FAQ titled "How does register_globals
affect me?"
Note: Variable variables
Superglobals cannot be used as variable variables inside functions or
class methods.
See Also
* variable scope
* The variables_order directive
* The filter extension
----------------------------------------------------------------------
----------------------------------------------------------------------
$GLOBALS
(PHP 4, PHP 5)
$GLOBALS - References all variables available in global scope
Description
An associative array containing references to all variables which are
currently defined in the global scope of the script. The variable names
are the keys of the array.
Examples
Example #1 $GLOBALS example
The above example will output something similar to:
$foo in global scope: Example content
$foo in current scope: local variable
Notes
Note:
This is a 'superglobal', or automatic global, variable. This simply
means that it is available in all scopes throughout a script. There is
no need to do global $variable; to access it within functions or
methods.
Note: Variable availability
Unlike all of the other superglobals, $GLOBALS has essentially always
been available in PHP.
----------------------------------------------------------------------
----------------------------------------------------------------------
$_SERVER
$HTTP_SERVER_VARS [deprecated]
(PHP 4 >= 4.1.0, PHP 5)
$_SERVER -- $HTTP_SERVER_VARS [deprecated] - Server and execution
environment information
Description
$_SERVER is an array containing information such as headers, paths, and
script locations. The entries in this array are created by the web server.
There is no guarantee that every web server will provide any of these;
servers may omit some, or provide others not listed here. That said, a
large number of these variables are accounted for in the >> CGI/1.1
specification, so you should be able to expect those.
$HTTP_SERVER_VARS contains the same initial information, but is not a
superglobal. (Note that $HTTP_SERVER_VARS and $_SERVER are different
variables and that PHP handles them as such)
Indices
You may or may not find any of the following elements in $_SERVER. Note
that few, if any, of these will be available (or indeed have any meaning)
if running PHP on the command line.
'PHP_SELF'
The filename of the currently executing script, relative to the
document root. For instance, $_SERVER['PHP_SELF'] in a script at
the address http://example.com/test.php/foo.bar would be
/test.php/foo.bar. The __FILE__ constant contains the full path
and filename of the current (i.e. included) file. If PHP is
running as a command-line processor this variable contains the
script name since PHP 4.3.0. Previously it was not available.
'argv'
Array of arguments passed to the script. When the script is run on
the command line, this gives C-style access to the command line
parameters. When called via the GET method, this will contain the
query string.
'argc'
Contains the number of command line parameters passed to the
script (if run on the command line).
'GATEWAY_INTERFACE'
What revision of the CGI specification the server is using; i.e.
'CGI/1.1'.
'SERVER_ADDR'
The IP address of the server under which the current script is
executing.
'SERVER_NAME'
The name of the server host under which the current script is
executing. If the script is running on a virtual host, this will
be the value defined for that virtual host.
'SERVER_SOFTWARE'
Server identification string, given in the headers when responding
to requests.
'SERVER_PROTOCOL'
Name and revision of the information protocol via which the page
was requested; i.e. 'HTTP/1.0';
'REQUEST_METHOD'
Which request method was used to access the page; i.e. 'GET',
'HEAD', 'POST', 'PUT'.
Note:
PHP script is terminated after sending headers (it means after
producing any output without output buffering) if the request
method was HEAD.
'REQUEST_TIME'
The timestamp of the start of the request. Available since PHP
5.1.0. It is float with microseconds since PHP 5.4.0.
'QUERY_STRING'
The query string, if any, via which the page was accessed.
'DOCUMENT_ROOT'
The document root directory under which the current script is
executing, as defined in the server's configuration file.
'HTTP_ACCEPT'
Contents of the Accept: header from the current request, if there
is one.
'HTTP_ACCEPT_CHARSET'
Contents of the Accept-Charset: header from the current request,
if there is one. Example: 'iso-8859-1,*,utf-8'.
'HTTP_ACCEPT_ENCODING'
Contents of the Accept-Encoding: header from the current request,
if there is one. Example: 'gzip'.
'HTTP_ACCEPT_LANGUAGE'
Contents of the Accept-Language: header from the current request,
if there is one. Example: 'en'.
'HTTP_CONNECTION'
Contents of the Connection: header from the current request, if
there is one. Example: 'Keep-Alive'.
'HTTP_HOST'
Contents of the Host: header from the current request, if there is
one.
'HTTP_REFERER'
The address of the page (if any) which referred the user agent to
the current page. This is set by the user agent. Not all user
agents will set this, and some provide the ability to modify
HTTP_REFERER as a feature. In short, it cannot really be trusted.
'HTTP_USER_AGENT'
Contents of the User-Agent: header from the current request, if
there is one. This is a string denoting the user agent being which
is accessing the page. A typical example is: Mozilla/4.5 [en]
(X11; U; Linux 2.2.9 i586). Among other things, you can use this
value with get_browser() to tailor your page's output to the
capabilities of the user agent.
'HTTPS'
Set to a non-empty value if the script was queried through the
HTTPS protocol.
Note: Note that when using ISAPI with IIS, the value will be off
if the request was not made through the HTTPS protocol.
'REMOTE_ADDR'
The IP address from which the user is viewing the current page.
'REMOTE_HOST'
The Host name from which the user is viewing the current page. The
reverse dns lookup is based off the REMOTE_ADDR of the user.
Note: Your web server must be configured to create this
variable. For example in Apache you'll need HostnameLookups On
inside httpd.conf for it to exist. See also gethostbyaddr().
'REMOTE_PORT'
The port being used on the user's machine to communicate with the
web server.
'SCRIPT_FILENAME'
The absolute pathname of the currently executing script.
Note:
If a script is executed with the CLI, as a relative path, such
as file.php or ../file.php, $_SERVER['SCRIPT_FILENAME'] will
contain the relative path specified by the user.
'SERVER_ADMIN'
The value given to the SERVER_ADMIN (for Apache) directive in the
web server configuration file. If the script is running on a
virtual host, this will be the value defined for that virtual
host.
'SERVER_PORT'
The port on the server machine being used by the web server for
communication. For default setups, this will be '80'; using SSL,
for instance, will change this to whatever your defined secure
HTTP port is.
'SERVER_SIGNATURE'
String containing the server version and virtual host name which
are added to server-generated pages, if enabled.
'PATH_TRANSLATED'
Filesystem- (not document root-) based path to the current script,
after the server has done any virtual-to-real mapping.
Note: As of PHP 4.3.2, PATH_TRANSLATED is no longer set
implicitly under the Apache 2 SAPI in contrast to the situation
in Apache 1, where it's set to the same value as the
SCRIPT_FILENAME server variable when it's not populated by
Apache. This change was made to comply with the CGI
specification that PATH_TRANSLATED should only exist if
PATH_INFO is defined. Apache 2 users may use AcceptPathInfo = On
inside httpd.conf to define PATH_INFO.
'SCRIPT_NAME'
Contains the current script's path. This is useful for pages which
need to point to themselves. The __FILE__ constant contains the
full path and filename of the current (i.e. included) file.
'REQUEST_URI'
The URI which was given in order to access this page; for
instance, '/index.html'.
'PHP_AUTH_DIGEST'
When doing Digest HTTP authentication this variable is set to the
'Authorization' header sent by the client (which you should then
use to make the appropriate validation).
'PHP_AUTH_USER'
When doing HTTP authentication this variable is set to the
username provided by the user.
'PHP_AUTH_PW'
When doing HTTP authentication this variable is set to the
password provided by the user.
'AUTH_TYPE'
When doing HTTP authenticated this variable is set to the
authentication type.
'PATH_INFO'
Contains any client-provided pathname information trailing the
actual script filename but preceding the query string, if
available. For instance, if the current script was accessed via
the URL
http://www.example.com/php/path_info.php/some/stuff?foo=bar, then
$_SERVER['PATH_INFO'] would contain /some/stuff.
'ORIG_PATH_INFO'
Original version of 'PATH_INFO' before processed by PHP.
Changelog
Version Description
4.1.0 Introduced $_SERVER that deprecated $HTTP_SERVER_VARS.
Examples
Example #1 $_SERVER example
The above example will output something similar to:
www.example.com
Notes
Note:
This is a 'superglobal', or automatic global, variable. This simply
means that it is available in all scopes throughout a script. There is
no need to do global $variable; to access it within functions or
methods.
See Also
* The filter extension
----------------------------------------------------------------------
----------------------------------------------------------------------
$_GET
$HTTP_GET_VARS [deprecated]
(PHP 4 >= 4.1.0, PHP 5)
$_GET -- $HTTP_GET_VARS [deprecated] - HTTP GET variables
Description
An associative array of variables passed to the current script via the URL
parameters.
$HTTP_GET_VARS contains the same initial information, but is not a
superglobal. (Note that $HTTP_GET_VARS and $_GET are different variables
and that PHP handles them as such)
Changelog
Version Description
4.1.0 Introduced $_GET that deprecated $HTTP_GET_VARS.
Examples
Example #1 $_GET example
Assuming the user entered http://example.com/?name=Hannes
The above example will output something similar to:
Hello Hannes!
Notes
Note:
This is a 'superglobal', or automatic global, variable. This simply
means that it is available in all scopes throughout a script. There is
no need to do global $variable; to access it within functions or
methods.
Note:
The GET variables are passed through urldecode().
See Also
* Handling external variables
* The filter extension
----------------------------------------------------------------------
----------------------------------------------------------------------
$_POST
$HTTP_POST_VARS [deprecated]
(PHP 4 >= 4.1.0, PHP 5)
$_POST -- $HTTP_POST_VARS [deprecated] - HTTP POST variables
Description
An associative array of variables passed to the current script via the
HTTP POST method.
$HTTP_POST_VARS contains the same initial information, but is not a
superglobal. (Note that $HTTP_POST_VARS and $_POST are different variables
and that PHP handles them as such)
Changelog
Version Description
4.1.0 Introduced $_POST that deprecated $HTTP_POST_VARS.
Examples
Example #1 $_POST example
Assuming the user POSTed name=Hannes
The above example will output something similar to:
Hello Hannes!
Notes
Note:
This is a 'superglobal', or automatic global, variable. This simply
means that it is available in all scopes throughout a script. There is
no need to do global $variable; to access it within functions or
methods.
See Also
* Handling external variables
* The filter extension
----------------------------------------------------------------------
----------------------------------------------------------------------
$_FILES
$HTTP_POST_FILES [deprecated]
(PHP 4 >= 4.1.0, PHP 5)
$_FILES -- $HTTP_POST_FILES [deprecated] - HTTP File Upload variables
Description
An associative array of items uploaded to the current script via the HTTP
POST method.
$HTTP_POST_FILES contains the same initial information, but is not a
superglobal. (Note that $HTTP_POST_FILES and $_FILES are different
variables and that PHP handles them as such)
Changelog
Version Description
4.1.0 Introduced $_FILES that deprecated $HTTP_POST_FILES.
Notes
Note:
This is a 'superglobal', or automatic global, variable. This simply
means that it is available in all scopes throughout a script. There is
no need to do global $variable; to access it within functions or
methods.
See Also
* move_uploaded_file() - Moves an uploaded file to a new location
* Handling File Uploads
----------------------------------------------------------------------
----------------------------------------------------------------------
$_REQUEST
(PHP 4 >= 4.1.0, PHP 5)
$_REQUEST - HTTP Request variables
Description
An associative array that by default contains the contents of $_GET,
$_POST and $_COOKIE.
Changelog
Version Description
5.3.0 Introduced request_order. This directive affects the contents of
$_REQUEST.
4.3.0 $_FILES information was removed from $_REQUEST.
4.1.0 Introduced $_REQUEST.
Notes
Note:
This is a 'superglobal', or automatic global, variable. This simply
means that it is available in all scopes throughout a script. There is
no need to do global $variable; to access it within functions or
methods.
Note:
When running on the command line , this will not include the argv and
argc entries; these are present in the $_SERVER array.
Note:
The variables in $_REQUEST are provided to the script via the GET, POST,
and COOKIE input mechanisms and therefore could be modified by the
remote user and cannot be trusted. The presence and order of variables
listed in this array is defined according to the PHP variables_order
configuration directive.
See Also
* import_request_variables() - Import GET/POST/Cookie variables into the
global scope
* Handling external variables
* The filter extension
----------------------------------------------------------------------
----------------------------------------------------------------------
$_SESSION
$HTTP_SESSION_VARS [deprecated]
(PHP 4 >= 4.1.0, PHP 5)
$_SESSION -- $HTTP_SESSION_VARS [deprecated] - Session variables
Description
An associative array containing session variables available to the current
script. See the Session functions documentation for more information on
how this is used.
$HTTP_SESSION_VARS contains the same initial information, but is not a
superglobal. (Note that $HTTP_SESSION_VARS and $_SESSION are different
variables and that PHP handles them as such)
Changelog
Version Description
4.1.0 Introduced $_SESSION that deprecated $HTTP_SESSION_VARS.
Notes
Note:
This is a 'superglobal', or automatic global, variable. This simply
means that it is available in all scopes throughout a script. There is
no need to do global $variable; to access it within functions or
methods.
See Also
* session_start() - Initialize session data
----------------------------------------------------------------------
----------------------------------------------------------------------
$_ENV
$HTTP_ENV_VARS [deprecated]
(PHP 4 >= 4.1.0, PHP 5)
$_ENV -- $HTTP_ENV_VARS [deprecated] - Environment variables
Description
An associative array of variables passed to the current script via the
environment method.
These variables are imported into PHP's global namespace from the
environment under which the PHP parser is running. Many are provided by
the shell under which PHP is running and different systems are likely
running different kinds of shells, a definitive list is impossible. Please
see your shell's documentation for a list of defined environment
variables.
Other environment variables include the CGI variables, placed there
regardless of whether PHP is running as a server module or CGI processor.
$HTTP_ENV_VARS contains the same initial information, but is not a
superglobal. (Note that $HTTP_ENV_VARS and $_ENV are different variables
and that PHP handles them as such)
Changelog
Version Description
4.1.0 Introduced $_ENV that deprecated $HTTP_ENV_VARS.
Examples
Example #1 $_ENV example
Assuming "bjori" executes this script
The above example will output something similar to:
My username is bjori!
Notes
Note:
This is a 'superglobal', or automatic global, variable. This simply
means that it is available in all scopes throughout a script. There is
no need to do global $variable; to access it within functions or
methods.
See Also
* getenv() - Gets the value of an environment variable
* The filter extension
----------------------------------------------------------------------
----------------------------------------------------------------------
$_COOKIE
$HTTP_COOKIE_VARS [deprecated]
(PHP 4 >= 4.1.0, PHP 5)
$_COOKIE -- $HTTP_COOKIE_VARS [deprecated] - HTTP Cookies
Description
An associative array of variables passed to the current script via HTTP
Cookies.
$HTTP_COOKIE_VARS contains the same initial information, but is not a
superglobal. (Note that $HTTP_COOKIE_VARS and $_COOKIE are different
variables and that PHP handles them as such)
Changelog
Version Description
4.1.0 Introduced $_COOKIE that deprecated $HTTP_COOKIE_VARS.
Examples
Example #1 $_COOKIE example
Assuming the "name" cookie has been set earlier
The above example will output something similar to:
Hello Hannes!
Notes
Note:
This is a 'superglobal', or automatic global, variable. This simply
means that it is available in all scopes throughout a script. There is
no need to do global $variable; to access it within functions or
methods.
See Also
* setcookie() - Send a cookie
* Handling external variables
* The filter extension
----------------------------------------------------------------------
----------------------------------------------------------------------
$php_errormsg
(PHP 4, PHP 5)
$php_errormsg - The previous error message
Description
$php_errormsg is a variable containing the text of the last error message
generated by PHP. This variable will only be available within the scope in
which the error occurred, and only if the track_errors configuration
option is turned on (it defaults to off).
Note: This variable is only available when track_errors is enabled in
php.ini.
Warning
If a user defined error handler (set_error_handler()) is set $php_errormsg
is only set if the error handler returns FALSE
Examples
Example #1 $php_errormsg example
The above example will output something similar to:
Wrong parameter count for strpos()
----------------------------------------------------------------------
----------------------------------------------------------------------
$HTTP_RAW_POST_DATA
(PHP 4, PHP 5)
$HTTP_RAW_POST_DATA - Raw POST data
Description
$HTTP_RAW_POST_DATA contains the raw POST data. See
always_populate_raw_post_data
----------------------------------------------------------------------
----------------------------------------------------------------------
$http_response_header
(PHP 4 >= 4.0.4, PHP 5)
$http_response_header - HTTP response headers
Description
The $http_response_header array is similar to the get_headers() function.
When using the HTTP wrapper, $http_response_header will be populated with
the HTTP response headers. $http_response_header will be created in the
local scope.
Examples
Example #1 $http_response_header example
The above example will output something similar to:
array(9) {
[0]=>
string(15) "HTTP/1.1 200 OK"
[1]=>
string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT"
[2]=>
string(29) "Server: Apache/2.2.3 (CentOS)"
[3]=>
string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT"
[4]=>
string(27) "ETag: "280100-1b6-80bfd280""
[5]=>
string(20) "Accept-Ranges: bytes"
[6]=>
string(19) "Content-Length: 438"
[7]=>
string(17) "Connection: close"
[8]=>
string(38) "Content-Type: text/html; charset=UTF-8"
}
NULL
----------------------------------------------------------------------
----------------------------------------------------------------------
$argc
(PHP 4, PHP 5)
$argc - The number of arguments passed to script
Description
Contains the number of arguments passed to the current script when running
from the command line.
Note: The script's filename is always passed as an argument to the
script, therefore the minimum value of $argc is 1.
Note: This variable is not available when register_argc_argv is
disabled.
Examples
Example #1 $argc example
When executing the example with: php script.php arg1 arg2 arg3
The above example will output something similar to:
int(4)
----------------------------------------------------------------------
----------------------------------------------------------------------
$argv
(PHP 4, PHP 5)
$argv - Array of arguments passed to script
Description
Contains an array of all the arguments passed to the script when running
from the command line.
Note: The first argument $argv[0] is always the name that was used to
run the script.
Note: This variable is not available when register_argc_argv is
disabled.
Examples
Example #1 $argv example
When executing the example with: php script.php arg1 arg2 arg3
The above example will output something similar to:
array(4) {
[0]=>
string(10) "script.php"
[1]=>
string(4) "arg1"
[2]=>
string(4) "arg2"
[3]=>
string(4) "arg3"
}
See Also
* getopt() - Gets options from the command line argument list
----------------------------------------------------------------------
Table of Contents
* Superglobals - Superglobals are built-in variables that are always
available in all scopes
* $GLOBALS - References all variables available in global scope
* $_SERVER - Server and execution environment information
* $_GET - HTTP GET variables
* $_POST - HTTP POST variables
* $_FILES - HTTP File Upload variables
* $_REQUEST - HTTP Request variables
* $_SESSION - Session variables
* $_ENV - Environment variables
* $_COOKIE - HTTP Cookies
* $php_errormsg - The previous error message
* $HTTP_RAW_POST_DATA - Raw POST data
* $http_response_header - HTTP response headers
* $argc - The number of arguments passed to script
* $argv - Array of arguments passed to script
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Exceptions
Table of Contents
* Exception
* ErrorException
See also the SPL Exceptions
----------------------------------------------------------------------
Exception
Introduction
Exception is the base class for all Exceptions.
Class synopsis
Exception {
/* Properties */
protected string $Exception->message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
public Exception::__construct ([ string $message = "" [, int $code = 0 [,
Exception $previous = NULL ]]] )
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}
Properties
message
The exception message
code
The Exception code
file
The filename where the exception was thrown
line
The line where the exception was thrown
----------------------------------------------------------------------
Exception::__construct
(PHP 5 >= 5.1.0)
Exception::__construct - Construct the exception
Description
public Exception::__construct() ([ string $message = "" [, int $code = 0
[, Exception $previous = NULL ]]] )
Constructs the Exception.
Parameters
message
The Exception message to throw.
code
The Exception code.
previous
The previous exception used for the exception chaining.
Changelog
Version Description
5.3.0 The previous parameter was added.
Notes
Note:
The message is NOT binary safe.
----------------------------------------------------------------------
----------------------------------------------------------------------
Exception::getMessage
(PHP 5 >= 5.1.0)
Exception::getMessage - Gets the Exception message
Description
final public string Exception::getMessage ( void )
Returns the Exception message.
Parameters
This function has no parameters.
Return Values
Returns the Exception message as a string.
Examples
Example #1 Exception::getMessage() example
getMessage();
}
?>
The above example will output something similar to:
Some error message
----------------------------------------------------------------------
----------------------------------------------------------------------
Exception::getPrevious
(PHP 5 >= 5.3.0)
Exception::getPrevious - Returns previous Exception
Description
final public Exception Exception::getPrevious ( void )
Returns previous Exception (the third parameter of
Exception::__construct()).
Parameters
This function has no parameters.
Return Values
Returns the previous Exception if available or NULL otherwise.
Examples
Example #1 Exception::getPrevious() example
Looping over, and printing out, exception trace.
getFile(), $e->getLine(), $e->getMessage(), $e->getCode(), get_class($e));
} while($e = $e->getPrevious());
}
?>
The above example will output something similar to:
/home/bjori/ex.php:8 Something happend (911) [MyCustomException]
/home/bjori/ex.php:6 You are doing it wrong! (112) [InvalidArgumentException]
----------------------------------------------------------------------
----------------------------------------------------------------------
Exception::getCode
(PHP 5 >= 5.1.0)
Exception::getCode - Gets the Exception code
Description
final public mixed Exception::getCode ( void )
Returns the Exception code.
Parameters
This function has no parameters.
Return Values
Returns the exception code as integer in Exception but possibly as other
type in Exception descendants (for example as string in PDOException).
Examples
Example #1 Exception::getCode() example
getCode();
}
?>
The above example will output something similar to:
The exception code is: 30
----------------------------------------------------------------------
----------------------------------------------------------------------
Exception::getFile
(PHP 5 >= 5.1.0)
Exception::getFile - Gets the file in which the exception occurred
Description
final public string Exception::getFile ( void )
Get the name of the file the exception was created.
Parameters
This function has no parameters.
Return Values
Returns the filename in which the exception was created.
Examples
Example #1 Exception::getFile() example
getFile();
}
?>
The above example will output something similar to:
/home/bjori/tmp/ex.php
----------------------------------------------------------------------
----------------------------------------------------------------------
Exception::getLine
(PHP 5 >= 5.1.0)
Exception::getLine - Gets the line in which the exception occurred
Description
final public int Exception::getLine ( void )
Get line number where the exception was created.
Parameters
This function has no parameters.
Return Values
Returns the line number where the exception was created.
Examples
Example #1 Exception::getLine() example
getLine();
}
?>
The above example will output something similar to:
The exception was created on line: 3
----------------------------------------------------------------------
----------------------------------------------------------------------
Exception::getTrace
(PHP 5 >= 5.1.0)
Exception::getTrace - Gets the stack trace
Description
final public array Exception::getTrace ( void )
Returns the Exception stack trace.
Parameters
This function has no parameters.
Return Values
Returns the Exception stack trace as an array.
Examples
Example #1 Exception::getTrace() example
getTrace());
}
?>
The above example will output something similar to:
array(1) {
[0]=>
array(4) {
["file"]=>
string(22) "/home/bjori/tmp/ex.php"
["line"]=>
int(7)
["function"]=>
string(4) "test"
["args"]=>
array(0) {
}
}
}
----------------------------------------------------------------------
----------------------------------------------------------------------
Exception::getTraceAsString
(PHP 5 >= 5.1.0)
Exception::getTraceAsString - Gets the stack trace as a string
Description
final public string Exception::getTraceAsString ( void )
Returns the Exception stack trace as a string.
Parameters
This function has no parameters.
Return Values
Returns the Exception stack trace as a string.
Examples
Example #1 Exception::getTraceAsString() example
getTraceAsString();
}
?>
The above example will output something similar to:
#0 /home/bjori/tmp/ex.php(7): test()
#1 {main}
----------------------------------------------------------------------
----------------------------------------------------------------------
Exception::__toString
(PHP 5 >= 5.1.0)
Exception::__toString - String representation of the exception
Description
public string Exception::__toString ( void )
Returns the string representation of the exception.
Parameters
This function has no parameters.
Return Values
Returns the string representation of the exception.
Examples
Example #1 Exception::__toString() example
The above example will output something similar to:
exception 'Exception' with message 'Some error message' in /home/bjori/tmp/ex.php:3
Stack trace:
#0 {main}
----------------------------------------------------------------------
----------------------------------------------------------------------
Exception::__clone
(PHP 5 >= 5.1.0)
Exception::__clone - Clone the exception
Description
final private void Exception::__clone ( void )
Tries to clone the Exception, which results in Fatal error.
Parameters
This function has no parameters.
Return Values
No value is returned.
Errors/Exceptions
Exceptions are not clonable.
----------------------------------------------------------------------
Table of Contents
* Exception::__construct - Construct the exception
* Exception::getMessage - Gets the Exception message
* Exception::getPrevious - Returns previous Exception
* Exception::getCode - Gets the Exception code
* Exception::getFile - Gets the file in which the exception occurred
* Exception::getLine - Gets the line in which the exception occurred
* Exception::getTrace - Gets the stack trace
* Exception::getTraceAsString - Gets the stack trace as a string
* Exception::__toString - String representation of the exception
* Exception::__clone - Clone the exception
----------------------------------------------------------------------
----------------------------------------------------------------------
ErrorException
Introduction
An Error Exception.
Class synopsis
ErrorException extends Exception {
/* Properties */
protected int $ErrorException->severity ;
/* Methods */
public ErrorException::__construct ([ string $message [, int $code [, int
$severity [, string $filename [, int $lineno ]]]]] )
final public int ErrorException::getSeverity ( void )
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}
Properties
severity
The severity of the exception
Examples
Example #1 Use set_error_handler() to change error messages into
ErrorException.
The above example will output something similar to:
Fatal error: Uncaught exception 'ErrorException' with message 'Wrong parameter count for strpos()' in /home/bjori/tmp/ex.php:8
Stack trace:
#0 [internal function]: exception_error_handler(2, 'Wrong parameter...', '/home/bjori/php...', 8, Array)
#1 /home/bjori/php/cleandocs/test.php(8): strpos()
#2 {main}
thrown in /home/bjori/tmp/ex.php on line 8
----------------------------------------------------------------------
ErrorException::__construct
(PHP 5 >= 5.1.0)
ErrorException::__construct - Construct the exception
Description
public ErrorException::__construct() ([ string $message [, int $code [,
int $severity [, string $filename [, int $lineno ]]]]] )
Constructs the Exception.
Parameters
message
The Exception message to throw.
code
The Exception code.
severity
The severity level of the exception.
filename
The filename where the exception is thrown.
lineno
The line number where the exception is thrown.
----------------------------------------------------------------------
----------------------------------------------------------------------
ErrorException::getSeverity
(PHP 5 >= 5.1.0)
ErrorException::getSeverity - Gets the exception severity
Description
final public int ErrorException::getSeverity ( void )
Returns the severity of the exception.
Parameters
This function has no parameters.
Return Values
Returns the severity level of the exception.
Examples
Example #1 ErrorException::getSeverity() example
getSeverity();
}
?>
The above example will output something similar to:
This exception severity is: 75
----------------------------------------------------------------------
Table of Contents
* ErrorException::__construct - Construct the exception
* ErrorException::getSeverity - Gets the exception severity
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Interfaces
Table of Contents
* Traversable
* Iterator
* IteratorAggregate
* ArrayAccess
* Serializable
See also the SPL Interfaces
----------------------------------------------------------------------
The Traversable interface
Introduction
Interface to detect if a class is traversable using foreach.
Abstract base interface that cannot be implemented alone. Instead it must
be implemented by either IteratorAggregate or Iterator.
Note:
Internal (built-in) classes that implement this interface can be used in
a foreach construct and do not need to implement IteratorAggregate or
Iterator.
Note:
This is an internal engine interface which cannot be implemented in PHP
scripts. Either IteratorAggregate or Iterator must be used instead.
Interface synopsis
Traversable {
}
This interface has no methods, its only purpose is to be the base
interface for all traversable classes.
----------------------------------------------------------------------
----------------------------------------------------------------------
The Iterator interface
Introduction
Interface for external iterators or objects that can be iterated
themselves internally.
Interface synopsis
Iterator extends Traversable {
/* Methods */
abstract public mixed current ( void )
abstract public scalar key ( void )
abstract public void next ( void )
abstract public void rewind ( void )
abstract public boolean valid ( void )
}
Example #1 Basic usage
This example demonstrates in which order methods are called when using
foreach with an iterator.
position = 0;
}
function rewind() {
var_dump(__METHOD__);
$this->position = 0;
}
function current() {
var_dump(__METHOD__);
return $this->array[$this->position];
}
function key() {
var_dump(__METHOD__);
return $this->position;
}
function next() {
var_dump(__METHOD__);
++$this->position;
}
function valid() {
var_dump(__METHOD__);
return isset($this->array[$this->position]);
}
}
$it = new myIterator;
foreach($it as $key => $value) {
var_dump($key, $value);
echo "\n";
}
?>
The above example will output something similar to:
string(18) "myIterator::rewind"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(0)
string(12) "firstelement"
string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(1)
string(13) "secondelement"
string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(2)
string(11) "lastelement"
string(16) "myIterator::next"
string(17) "myIterator::valid"
----------------------------------------------------------------------
Iterator::current
(PHP 5 >= 5.0.0)
Iterator::current - Return the current element
Description
abstract public mixed Iterator::current ( void )
Returns the current element.
Parameters
This function has no parameters.
Return Values
Can return any type.
----------------------------------------------------------------------
----------------------------------------------------------------------
Iterator::key
(PHP 5 >= 5.0.0)
Iterator::key - Return the key of the current element
Description
abstract public scalar Iterator::key ( void )
Returns the key of the current element.
Parameters
This function has no parameters.
Return Values
Returns scalar on success, or NULL on failure.
Errors/Exceptions
Issues E_NOTICE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
Iterator::next
(PHP 5 >= 5.0.0)
Iterator::next - Move forward to next element
Description
abstract public void Iterator::next ( void )
Moves the current position to the next element.
Note:
This method is called after each foreach loop.
Parameters
This function has no parameters.
Return Values
Any returned value is ignored.
----------------------------------------------------------------------
----------------------------------------------------------------------
Iterator::rewind
(PHP 5 >= 5.0.0)
Iterator::rewind - Rewind the Iterator to the first element
Description
abstract public void Iterator::rewind ( void )
Rewinds back to the first element of the Iterator.
Note:
This is the first method called when starting a foreach loop. It will
not be executed after foreach loops.
Parameters
This function has no parameters.
Return Values
Any returned value is ignored.
----------------------------------------------------------------------
----------------------------------------------------------------------
Iterator::valid
(PHP 5 >= 5.0.0)
Iterator::valid - Checks if current position is valid
Description
abstract public boolean Iterator::valid ( void )
This method is called after Iterator::rewind() and Iterator::next() to
check if the current position is valid.
Parameters
This function has no parameters.
Return Values
The return value will be casted to boolean and then evaluated. Returns
TRUE on success or FALSE on failure.
----------------------------------------------------------------------
Table of Contents
* Iterator::current - Return the current element
* Iterator::key - Return the key of the current element
* Iterator::next - Move forward to next element
* Iterator::rewind - Rewind the Iterator to the first element
* Iterator::valid - Checks if current position is valid
----------------------------------------------------------------------
----------------------------------------------------------------------
The IteratorAggregate interface
Introduction
Interface to create an external Iterator.
Interface synopsis
IteratorAggregate extends Traversable {
/* Methods */
abstract public Traversable getIterator ( void )
}
Example #1 Basic usage
property4 = "last property";
}
public function getIterator() {
return new ArrayIterator($this);
}
}
$obj = new myData;
foreach($obj as $key => $value) {
var_dump($key, $value);
echo "\n";
}
?>
The above example will output something similar to:
string(9) "property1"
string(19) "Public property one"
string(9) "property2"
string(19) "Public property two"
string(9) "property3"
string(21) "Public property three"
string(9) "property4"
string(13) "last property"
----------------------------------------------------------------------
IteratorAggregate::getIterator
(PHP 5 >= 5.0.0)
IteratorAggregate::getIterator - Retrieve an external iterator
Description
abstract public Traversable IteratorAggregate::getIterator ( void )
Returns an external iterator.
Parameters
This function has no parameters.
Return Values
An instance of an object implementing Iterator or Traversable
Errors/Exceptions
Throws an Exception on failure.
----------------------------------------------------------------------
Table of Contents
* IteratorAggregate::getIterator - Retrieve an external iterator
----------------------------------------------------------------------
----------------------------------------------------------------------
The ArrayAccess interface
Introduction
Interface to provide accessing objects as arrays.
Interface synopsis
ArrayAccess {
/* Methods */
abstract public boolean offsetExists ( mixed $offset )
abstract public mixed offsetGet ( mixed $offset )
abstract public void offsetSet ( mixed $offset , mixed $value )
abstract public void offsetUnset ( mixed $offset )
}
Example #1 Basic usage
container = array(
"one" => 1,
"two" => 2,
"three" => 3,
);
}
public function offsetSet($offset, $value) {
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
public function offsetExists($offset) {
return isset($this->container[$offset]);
}
public function offsetUnset($offset) {
unset($this->container[$offset]);
}
public function offsetGet($offset) {
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
}
$obj = new obj;
var_dump(isset($obj["two"]));
var_dump($obj["two"]);
unset($obj["two"]);
var_dump(isset($obj["two"]));
$obj["two"] = "A value";
var_dump($obj["two"]);
$obj[] = 'Append 1';
$obj[] = 'Append 2';
$obj[] = 'Append 3';
print_r($obj);
?>
The above example will output something similar to:
bool(true)
int(2)
bool(false)
string(7) "A value"
obj Object
(
[container:obj:private] => Array
(
[one] => 1
[three] => 3
[two] => A value
[0] => Append 1
[1] => Append 2
[2] => Append 3
)
)
----------------------------------------------------------------------
ArrayAccess::offsetExists
(PHP 5 >= 5.0.0)
ArrayAccess::offsetExists - Whether a offset exists
Description
abstract public boolean ArrayAccess::offsetExists ( mixed $offset )
Whether or not an offset exists.
This method is executed when using isset() or empty() on objects
implementing ArrayAccess.
Note:
When using empty() ArrayAccess::offsetGet() will be called and checked
if empty only if ArrayAccess::offsetExists() returns TRUE.
Parameters
offset
An offset to check for.
Return Values
Returns TRUE on success or FALSE on failure.
Note:
The return value will be casted to boolean if non-boolean was returned.
Examples
Example #1 ArrayAccess::offsetExists() example
The above example will output something similar to:
Runs obj::offsetExists()
string(17) "obj::offsetExists"
bool(true)
Runs obj::offsetExists() and obj::offsetGet()
string(17) "obj::offsetExists"
string(14) "obj::offsetGet"
bool(false)
Runs obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get
string(17) "obj::offsetExists"
bool(true)
----------------------------------------------------------------------
----------------------------------------------------------------------
ArrayAccess::offsetGet
(PHP 5 >= 5.0.0)
ArrayAccess::offsetGet - Offset to retrieve
Description
abstract public mixed ArrayAccess::offsetGet ( mixed $offset )
Returns the value at specified offset.
This method is executed when checking if offset is empty().
Parameters
offset
The offset to retrieve.
Notes
Note:
Starting with PHP 5.3.4, the prototype checks were relaxed and it's
possible for implementations of this method to return by reference. This
makes indirect modifications to the overloaded array dimensions of
ArrayAccess objects possible.
A direct modification is one that replaces completely the value of the
array dimension, as in $obj[6] = 7. An indirect modification, on the
other hand, only changes part of the dimension, or attempts to assign
the dimension by reference to another variable, as in $obj[6][7] = 7 or
$var =& $obj[6]. Increments with ++ and decrements with -- are also
implemented in a way that requires indirect modification.
While direct modification triggers a call to ArrayAccess::offsetSet(),
indirect modification triggers a call to ArrayAccess::offsetGet(). In
that case, the implementation of ArrayAccess::offsetGet() must be able
to return by reference, otherwise an E_NOTICE message is raised.
Return Values
Can return all value types.
See Also
* ArrayAccess::offsetExists() - Whether a offset exists
----------------------------------------------------------------------
----------------------------------------------------------------------
ArrayAccess::offsetSet
(PHP 5 >= 5.0.0)
ArrayAccess::offsetSet - Offset to set
Description
abstract public void ArrayAccess::offsetSet ( mixed $offset , mixed $value
)
Assigns a value to the specified offset.
Parameters
offset
The offset to assign the value to.
value
The value to set.
Return Values
No value is returned.
Notes
Note:
The offset parameter will be set to NULL if another value is not
available, like in the following example.
The above example will output:
Array
(
[0] => first value
[1] => second value
)
Note:
This function is not called in assignments by reference and otherwise
indirect changes to array dimensions overloaded with ArrayAccess
(indirect in the sense they are made not by changing the dimension
directly, but by changing a sub-dimension or sub-property or assigning
the array dimension by reference to another variable). Instead,
ArrayAccess::offsetGet() is called. The operation will only be
successful if that method returns by reference, which is only possible
since PHP 5.3.4.
----------------------------------------------------------------------
----------------------------------------------------------------------
ArrayAccess::offsetUnset
(PHP 5 >= 5.0.0)
ArrayAccess::offsetUnset - Offset to unset
Description
abstract public void ArrayAccess::offsetUnset ( mixed $offset )
Unsets an offset.
Note:
This method will not be called when type-casting to (unset)
Parameters
offset
The offset to unset.
Return Values
No value is returned.
----------------------------------------------------------------------
Table of Contents
* ArrayAccess::offsetExists - Whether a offset exists
* ArrayAccess::offsetGet - Offset to retrieve
* ArrayAccess::offsetSet - Offset to set
* ArrayAccess::offsetUnset - Offset to unset
----------------------------------------------------------------------
----------------------------------------------------------------------
The Serializable interface
Introduction
Interface for customized serializing.
Classes that implement this interface no longer support __sleep() and
__wakeup(). The method serialize is called whenever an instance needs to
be serialized. This does not invoke __destruct() or has any other side
effect unless programmed inside the method. When the data is unserialized
the class is known and the appropriate unserialize() method is called as a
constructor instead of calling __construct(). If you need to execute the
standard constructor you may do so in the method.
Interface synopsis
Serializable {
/* Methods */
abstract public string serialize ( void )
abstract public mixed unserialize ( string $serialized )
}
Example #1 Basic usage
data = "My private data";
}
public function serialize() {
return serialize($this->data);
}
public function unserialize($data) {
$this->data = unserialize($data);
}
public function getData() {
return $this->data;
}
}
$obj = new obj;
$ser = serialize($obj);
var_dump($ser);
$newobj = unserialize($ser);
var_dump($newobj->getData());
?>
The above example will output something similar to:
string(38) "C:3:"obj":23:{s:15:"My private data";}"
string(15) "My private data"
----------------------------------------------------------------------
Serializable::serialize
(PHP 5 >= 5.1.0)
Serializable::serialize - String representation of object
Description
abstract public string Serializable::serialize ( void )
Should return the string representation of the object.
Note:
This method acts as the destructor of the object. The __destruct()
method will not be called after this method.
Parameters
This function has no parameters.
Return Values
Returns the string representation of the object or NULL
Errors/Exceptions
Throws Exception when returning other types then strings and NULL
See Also
* __sleep()
----------------------------------------------------------------------
----------------------------------------------------------------------
Serializable::unserialize
(PHP 5 >= 5.1.0)
Serializable::unserialize - Constructs the object
Description
abstract public mixed Serializable::unserialize ( string $serialized )
Called during unserialization of the object.
Note:
This method acts as the constructor of the object. The __construct()
method will not be called after this method.
Parameters
serialized
The string representation of the object.
Return Values
Returns the original value unserialized.
See Also
* __wakeup()
----------------------------------------------------------------------
Table of Contents
* Serializable::serialize - String representation of object
* Serializable::unserialize - Constructs the object
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Context options and parameters
PHP offers various context options and parameters which can be used with
all filesystem and stream wrappers. The context is created with
stream_context_create(). Options are set with stream_context_set_option()
and parameters with stream_context_set_params().
----------------------------------------------------------------------
Socket context options
Socket context options - Socket context option listing
Description
Socket context options are available for all wrappers that work over
sockets, like tcp, http and ftp.
Options
bindto
Used to specify the IP address (either IPv4 or IPv6) and/or the
port number that PHP will use to access the network. The syntax is
ip:port. Setting the IP or the port to 0 will let the system
choose the IP and/or port.
Note:
As FTP creates two socket connections during normal operation,
the port number cannot be specified using this option.
backlog
Used to limit the number of outstanding connections in the
socket's listen queue.
Note:
This is only applicable to stream_socket_server().
Changelog
Version Description
5.1.0 Added bindto.
5.3.3 Added backlog.
Examples
Example #1 Basic bindto usage example
array(
'bindto' => '192.168.0.100:0',
),
);
// connect to the internet using the '192.168.0.100' IP and port '7000'
$opts = array(
'socket' => array(
'bindto' => '192.168.0.100:7000',
),
);
// connect to the internet using port '7000'
$opts = array(
'socket' => array(
'bindto' => '0:7000',
),
);
// create the context...
$context = stream_context_create($opts);
// ...and use it to fetch the data
echo file_get_contents('http://www.example.com', false, $context);
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
HTTP context options
HTTP context options - HTTP context option listing
Description
Context options for http:// and https:// transports.
Options
method string
GET, POST, or any other HTTP method supported by the remote
server.
Defaults to GET.
header string
Additional headers to be sent during request. Values in this
option will override other values (such as User-agent:, Host:, and
Authentication:).
user_agent string
Value to send with User-Agent: header. This value will only be
used if user-agent is not specified in the header context option
above.
By default the user_agent php.ini setting is used.
content string
Additional data to be sent after the headers. Typically used with
POST or PUT requests.
proxy string
URI specifying address of proxy server. (e.g.
tcp://proxy.example.com:5100).
request_fulluri boolean
When set to TRUE, the entire URI will be used when constructing
the request. (i.e. GET http://www.example.com/path/to/file.html
HTTP/1.0). While this is a non-standard request format, some proxy
servers require it.
Defaults to FALSE.
follow_location integer
Follow Location: .. redirects.
Defaults to TRUE.
max_redirects integer
The max number of redirects to follow. Value 1 or less means that
no redirects are followed.
Defaults to 20.
protocol_version float
HTTP protocol version.
Defaults to 1.0.
Note:
PHP prior to 5.3.0 does not implement chunked transfer decoding.
If this value is set to 1.1 it is your responsibility to be 1.1
compliant.
timeout float
Read timeout in seconds, specified by a float (e.g. 10.5).
By default the default_socket_timeout php.ini setting is used.
ignore_errors boolean
Fetch the content even on failure status codes.
Defaults to FALSE
Changelog
Version Description
5.3.4 Added follow_location.
5.3.0 The protocol_version supports chunked transfer decoding when set
to 1.1.
5.2.10 Added ignore_errors.
5.2.10 The header can now be an numerically indexed array.
5.2.1 Added timeout.
5.1.0 Added HTTPS proxying through HTTP proxies.
5.1.0 Added max_redirects.
5.1.0 Added protocol_version.
Examples
Example #1 Fetch a page and send POST data
'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
?>
Example #2 Ignore redirects but fetch headers and content
array('method' => 'GET',
'max_redirects' => '0',
'ignore_errors' => '1')
);
$context = stream_context_create($opts);
$stream = fopen($url, 'r', false, $context);
// header information as well as meta data
// about the stream
var_dump(stream_get_meta_data($stream));
// actual data at $url
var_dump(stream_get_contents($stream));
fclose($stream);
?>
Notes
Note: Underlying socket stream context options
Additional context options may be supported by the underlying transport
For http:// streams, refer to context options for the tcp:// transport.
For https:// streams, refer to context options for the ssl:// transport.
Note: HTTP status line
When this stream wrapper follows a redirect, the wrapper_data returned
by stream_get_meta_data() might not necessarily contain the HTTP status
line that actually applies to the content data at index 0.
array (
'wrapper_data' =>
array (
0 => 'HTTP/1.0 301 Moved Permantenly',
1 => 'Cache-Control: no-cache',
2 => 'Connection: close',
3 => 'Location: http://example.com/foo.jpg',
4 => 'HTTP/1.1 200 OK',
...
The first request returned a 301 (permanent redirect), so the stream
wrapper automatically followed the redirect to get a 200 response (index
= 4).
See Also
* http://
* Socket context options
* SSL context options
----------------------------------------------------------------------
----------------------------------------------------------------------
FTP context options
FTP context options - FTP context option listing
Description
Context options for ftp:// and ftps:// transports.
Options
overwrite boolean
Allow overwriting of already existing files on remote server.
Applies to write mode (uploading) only.
Defaults to FALSE.
resume_pos integer
File offset at which to begin transfer. Applies to read mode
(downloading) only.
Defaults to 0 (Beginning of File).
proxy string
Proxy FTP request via http proxy server. Applies to file read
operations only. Ex: tcp://squid.example.com:8000.
Changelog
Version Description
5.1.0 Added proxy.
5.0.0 Added overwrite and resume_pos.
Notes
Note: Underlying socket stream context options
Additional context options may be supported by the underlying transport
For ftp:// streams, refer to context options for the tcp:// transport.
For ftps:// streams, refer to context options for the ssl:// transport.
See Also
* ftp://
* Socket context options
* SSL context options
----------------------------------------------------------------------
----------------------------------------------------------------------
SSL context options
SSL context options - SSL context option listing
Description
Context options for ssl:// and tls:// transports.
Options
verify_peer boolean
Require verification of SSL certificate used.
Defaults to FALSE.
allow_self_signed boolean
Allow self-signed certificates.
Defaults to FALSE
cafile string
Location of Certificate Authority file on local filesystem which
should be used with the verify_peer context option to authenticate
the identity of the remote peer.
capath string
If cafile is not specified or if the certificate is not found
there, the directory pointed to by capath is searched for a
suitable certificate. capath must be a correctly hashed
certificate directory.
local_cert string
Path to local certificate file on filesystem. It must be a PEM
encoded file which contains your certificate and private key. It
can optionally contain the certificate chain of issuers.
passphrase string
Passphrase with which your local_cert file was encoded.
CN_match string
Common Name we are expecting. PHP will perform limited wildcard
matching. If the Common Name does not match this, the connection
attempt will fail.
verify_depth integer
Abort if the certificate chain is too deep.
Defaults to no verification.
ciphers string
Sets the list of available ciphers. The format of the string is
described in >> ciphers(1).
Defaults to DEFAULT.
capture_peer_cert boolean
If set to TRUE a peer_certificate context option will be created
containing the peer certificate.
capture_peer_cert_chain boolean
If set to TRUE a peer_certificate_chain context option will be
created containing the certificate chain.
SNI_enabled boolean
If set to TRUE server name indication will be enabled. Enabling
SNI allows multiple certificates on the same IP address.
SNI_server_name string
If set, then this value will be used as server name for server
name indication. If this value is not set, then the server name is
guessed based on the hostname used when opening the stream.
Changelog
Version Description
5.3.2 Added SNI_enabled and SNI_server_name.
5.0.0 Added capture_peer_cert, capture_peer_chain and ciphers.
Notes
Note: Because ssl:// is the underlying transport for the https:// and
ftps:// wrappers, any context options which apply to ssl:// also apply
to https:// and ftps://.
Note: For SNI (Server Name Indication) to be available, then PHP must be
compiled with OpenSSL 0.9.8j or greater. Use the
OPENSSL_TLSEXT_SERVER_NAME to determine whether SNI is supported.
See Also
* Socket context options
----------------------------------------------------------------------
----------------------------------------------------------------------
CURL context options
CURL context options - CURL context option listing
Description
CURL context options are available when the CURL extension was compiled
using the --with-curlwrappers configure option.
Options
method string
GET, POST, or any other HTTP method supported by the remote
server.
Defaults to GET.
header string
Additional headers to be sent during request. Values in this
option will override other values (such as User-agent:, Host:, and
Authentication:).
user_agent string
Value to send with User-Agent: header.
By default the user_agent php.ini setting is used.
content string
Additional data to be sent after the headers. This option is not
used for GET or HEAD requests.
proxy string
URI specifying address of proxy server. (e.g.
tcp://proxy.example.com:5100).
max_redirects integer
The max number of redirects to follow. Value 1 or less means that
no redirects are followed.
Defaults to 20.
curl_verify_ssl_host boolean
Verify the host.
Defaults to FALSE
Note:
This option is available for both the http and ftp protocol
wrappers.
curl_verify_ssl_peer boolean
Require verification of SSL certificate used.
Defaults to FALSE
Note:
This option is available for both the http and ftp protocol
wrappers.
Examples
Example #1 Fetch a page and send POST data
'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
?>
See Also
* Socket context options
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar context options
Phar context options - Phar context option listing
Description
Context options for phar:// wrapper.
Options
compress int
One of Phar compression constants.
metadata mixed
Phar metadata. See Phar::setMetadata().
See Also
* phar://
* Phar stream wrapper
----------------------------------------------------------------------
----------------------------------------------------------------------
Context parameters
Context parameters - Context parameter listing
Description
These parameters can be set on a context using the
stream_context_set_params() function.
Parameters
notification callback
A callback to be called when an event occurs on a stream.
See stream_notification_callback() for more details.
----------------------------------------------------------------------
Table of Contents
* Socket context options - Socket context option listing
* HTTP context options - HTTP context option listing
* FTP context options - FTP context option listing
* SSL context options - SSL context option listing
* CURL context options - CURL context option listing
* Phar context options - Phar context option listing
* Context parameters - Context parameter listing
----------------------------------------------------------------------
----------------------------------------------------------------------
Supported Protocols and Wrappers
PHP comes with many built-in wrappers for various URL-style protocols for
use with the filesystem functions such as fopen(), copy(), file_exists()
and filesize(). In addition to these wrappers, it is possible to register
custom wrappers using the stream_wrapper_register() function.
Note: The URL syntax used to describe a wrapper only supports the
scheme://... syntax. The scheme:/ and scheme: syntaxes are not
supported.
----------------------------------------------------------------------
file://
file:// - Accessing local filesystem
Description
Filesystem is the default wrapper used with PHP and represents the local
filesystem. When a relative path is specified (a path which does not begin
with /, \, \\, or a Windows drive letter) the path provided will be
applied against the current working directory. In many cases this is the
directory in which the script resides unless it has been changed. Using
the CLI sapi, this defaults to the directory from which the script was
called.
With some functions, such as fopen() and file_get_contents(), include_path
may be optionally searched for relative paths as well.
Options
* /path/to/file.ext
* relative/path/to/file.ext
* fileInCwd.ext
* C:/path/to/winfile.ext
* C:\path\to\winfile.ext
* \\smbserver\share\path\to\winfile.ext
* file:///path/to/file.ext
Options
Wrapper Summary
Attribute Supported
Restricted by allow_url_fopen No
Allows Reading Yes
Allows Writing Yes
Allows Appending Yes
Allows Simultaneous Reading and Writing Yes
Supports stat() Yes
Supports unlink() Yes
Supports rename() Yes
Supports mkdir() Yes
Supports rmdir() Yes
Changelog
Version Description
5.0.0 Added file://.
----------------------------------------------------------------------
----------------------------------------------------------------------
http://
https://
http:// -- https:// - Accessing HTTP(s) URLs
Description
Allows read-only access to files/resources via HTTP 1.0, using the HTTP
GET method. A Host: header is sent with the request to handle name-based
virtual hosts. If you have configured a user_agent string using your
php.ini file or the stream context, it will also be included in the
request.
The stream allows access to the body of the resource; the headers are
stored in the $http_response_header variable.
If it's important to know the URL of the resource where your document came
from (after all redirects have been processed), you'll need to process the
series of response headers returned by the stream.
The from directive will be used for the From: header if set and not
overwritten by the Context options and parameters.
Options
* http://example.com
* http://example.com/file.php?var1=val1&var2=val2
* http://user:password@example.com
* https://example.com
* https://example.com/file.php?var1=val1&var2=val2
* https://user:password@example.com
Options
Wrapper Summary
Attribute Supported
Restricted by allow_url_fopen Yes
Allows Reading Yes
Allows Writing No
Allows Appending No
Allows Simultaneous Reading and Writing N/A
Supports stat() No
Supports unlink() No
Supports rename() No
Supports mkdir() No
Supports rmdir() No
Changelog
Version Description
4.3.7 Detect buggy IIS servers to avoid "SSL: Fatal Protocol Error"
errors.
4.3.0 Added https://.
4.0.5 Added support for redirects.
Examples
Example #1 Detecting which URL we ended up on after redirects
Example #2 Sending custom headers with an HTTP request
Custom headers may be sent with an HTTP request by taking advantage of a
side-effect in the handling of the user_agent INI setting. Set user_agent
to any valid string (such as the default PHP/version setting) followed by
a carriage-return/line-feed pair and any additional headers. This method
works in PHP 4 and all later versions.
Results in the following request being sent:
GET /index.php HTTP/1.0
Host: www.example.com
User-Agent: PHP
X-MyCustomHeader: Foo
Notes
Note: HTTPS is only supported when the openssl extension is enabled.
HTTP connections are read-only; writing data or copying files to an HTTP
resource is not supported.
Sending POST and PUT requests, for example, can be done with the help of
HTTP Contexts.
See Also
* HTTP context options
* $http_response_header
* stream_get_meta_data() - Retrieves header/meta data from streams/file
pointers
----------------------------------------------------------------------
----------------------------------------------------------------------
ftp://
ftps://
ftp:// -- ftps:// - Accessing FTP(s) URLs
Description
Allows read access to existing files and creation of new files via FTP. If
the server does not support passive mode ftp, the connection will fail.
You can open files for either reading or writing, but not both
simultaneously. If the remote file already exists on the ftp server and
you attempt to open it for writing but have not specified the context
option overwrite, the connection will fail. If you need to overwrite
existing files over ftp, specify the overwrite option in the context and
open the file for writing. Alternatively, you can use the FTP extension.
If you have set the from directive in php.ini, then this value will be
sent as the anonymous FTP password.
Options
* ftp://example.com/pub/file.txt
* ftp://user:password@example.com/pub/file.txt
* ftps://example.com/pub/file.txt
* ftps://user:password@example.com/pub/file.txt
Options
Wrapper Summary
Attribute PHP 4 PHP 5
Restricted by Yes Yes
allow_url_fopen
Allows Reading Yes Yes
Allows Writing Yes (new Yes (new files/existing files with
files only) overwrite)
Allows Appending No Yes
Allows Simultaneous No No
Reading and Writing
As of PHP 5.0.0: filesize(), filetype(),
Supports stat() No file_exists(), is_file(), and is_dir()
elements only. As of PHP 5.1.0:
filemtime().
Supports unlink() No Yes
Supports rename() No Yes
Supports mkdir() No Yes
Supports rmdir() No Yes
Changelog
Version Description
4.3.0 Added ftps://.
Notes
Note:
FTPS is only supported when the openssl extension is enabled.
If the server does not support SSL, then the connection falls back to
regular unencrypted ftp.
Note: Appending
As of PHP 5.0.0 files may be appended via the ftp:// URL wrapper. In
prior versions, attempting to append to a file via ftp:// will result in
failure.
See Also
* FTP context options
----------------------------------------------------------------------
----------------------------------------------------------------------
php://
php:// - Accessing various I/O streams
Description
PHP provides a number of miscellaneous I/O streams that allow access to
PHP's own input and output streams, the standard input, output and error
file descriptors, in-memory and disk-backed temporary file streams, and
filters that can manipulate other file resources as they are read from and
written to.
php://stdin, php://stdout and php://stderr
php://stdin, php://stdout and php://stderr allow direct access to the
corresponding input or output stream of the PHP process. The stream
references a duplicate file descriptor, so if you open php://stdin and
later close it, you close only your copy of the descriptor-the actual
stream referenced by STDIN is unaffected. Note that PHP exhibited buggy
behavior in this regard until PHP 5.2.1. It is recommended that you simply
use the constants STDIN, STDOUT and STDERR instead of manually opening
streams using these wrappers.
php://stdin is read-only, whereas php://stdout and php://stderr are
write-only.
php://input
php://input is a read-only stream that allows you to read raw data from
the request body. In the case of POST requests, it is preferable to
$HTTP_RAW_POST_DATA as it does not depend on special php.ini directives.
Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by
default, it is a potentially less memory intensive alternative to
activating always_populate_raw_post_data. php://input is not available
with enctype="multipart/form-data".
Note: A stream opened with php://input can only be read once; the stream
does not support seek operations. However, depending on the SAPI
implementation, it may be possible to open another php://input stream
and restart reading. This is only possible if the request body data has
been saved. Typically, this is the case for POST requests, but not other
request methods, such as PUT or PROPFIND.
php://output
php://output is a write-only stream that allows you to write to the output
buffer mechanism in the same way as print() and echo().
php://fd
php://fd allows direct access to the given file descriptor. For example,
php://fd/3 refers to file descriptor 3.
php://memory and php://temp
php://memory and php://temp are read-write streams that allow temporary
data to be stored in a file-like wrapper. The only difference between the
two is that php://memory will always store its data in memory, whereas
php://temp will use a temporary file once the amount of data stored hits a
predefined limit (the default is 2 MB).
The memory limit of php://temp can be controlled by appending
/maxmemory:NN, where NN is the maximum amount of data to keep in memory
before using a temporary file, in bytes.
php://filter
php://filter is a kind of meta-wrapper designed to permit the application
of filters to a stream at the time of opening. This is useful with
all-in-one file functions such as readfile(), file(), and
file_get_contents() where there is otherwise no opportunity to apply a
filter to the stream prior the contents being read.
The php://filter target takes the following parameters as part of its
path. Please refer to the examples for specifics on using these
parameters.
php://filter parameters
Name Description
resource= This parameter is required. It specifies
the stream that you would like to filter.
read= filter names can be provided here,
separated by the pipe character (|).
write= filter names can be provided here,
separated by the pipe character (|).
Any filter lists which are not prefixed
both the read and write chains as
appropriate.
Options
Wrapper Summary (for php://filter, refer to the summary of the wrapper
being filtered)
Attribute Supported
Restricted by allow_url_fopen No
Restricted by allow_url_include php://input, php://stdin, php://memory and
php://temp only.
Allows Reading php://stdin, php://input, php://fd,
php://memory and php://temp only.
php://stdout, php://stderr, php://output,
Allows Writing php://fd, php://memory and php://temp
only.
php://stdout, php://stderr, php://output,
Allows Appending php://fd, php://memory and php://temp
only. (Equivalent to writing)
Allows Simultaneous Reading and php://fd, php://memory and php://temp
Writing only.
Supports stat() php://memory and php://temp only.
Supports unlink() No
Supports rename() No
Supports mkdir() No
Supports rmdir() No
Supports stream_select() php://stdin, php://stdout, php://stderr,
php://fd and php://temp only.
Changelog
Version Description
5.3.6 php://fd was added.
5.1.0 php://memory and php://temp were added.
5.0.0 php://filter was added.
Examples
Example #1 php://temp/maxmemory
This optional parameter allows setting the memory limit before php://temp
starts using a temporary file.
Example #2 php://filter/resource=
This parameter must be located at the end of your php://filter
specification and should point to the stream which you want filtered.
Example #3 php://filter/read=
This parameter takes one or more filternames separated by the pipe
character |.
Example #4 php://filter/write=
This parameter takes one or more filternames separated by the pipe
character |.
----------------------------------------------------------------------
----------------------------------------------------------------------
zlib://
bzip2://
zip://
zlib:// -- bzip2:// -- zip:// - Compression Streams
Description
zlib: PHP 4.0.4 - PHP 4.2.3 (systems with fopencookie only)
compress.zlib:// and compress.bzip2:// PHP 4.3.0 and up
zlib: works like gzopen(), except that the stream can be used with fread()
and the other filesystem functions. This is deprecated as of PHP 4.3.0 due
to ambiguities with filenames containing ':' characters; use
compress.zlib:// instead.
compress.zlib:// and compress.bzip2:// are equivalent to gzopen() and
bzopen() respectively, and operate even on systems that do not support
fopencookie.
ZIP extension registers zip: wrapper.
Options
* zlib:
* compress.zlib://
* compress.bzip2://
Options
Wrapper Summary
Attribute Supported
Restricted by allow_url_fopen No
Allows Reading Yes
Allows Writing Yes (except zip://)
Allows Appending Yes (except zip://)
Allows Simultaneous Reading and No
Writing
Supports stat() No, use the normal file:// wrapper to stat
compressed files.
Supports unlink() No, use the normal file:// wrapper to
unlink compressed files.
Supports rename() No
Supports mkdir() No
Supports rmdir() No
----------------------------------------------------------------------
----------------------------------------------------------------------
data://
data:// - Data (RFC 2397)
Description
The data: (>> RFC 2397) stream wrapper is available since PHP 5.2.0.
Options
* data://text/plain;base64,
Options
Wrapper Summary
Attribute Supported
Restricted by allow_url_fopen No
Restricted by allow_url_include Yes
Allows Reading Yes
Allows Writing No
Allows Appending No
Allows Simultaneous Reading and Writing No
Supports stat() No
Supports unlink() No
Supports rename() No
Supports mkdir() No
Supports rmdir() No
Examples
Example #1 Print data:// contents
Example #2 Fetch the media type
----------------------------------------------------------------------
----------------------------------------------------------------------
glob://
glob:// - Find pathnames matching pattern
Description
The glob: stream wrapper is available since PHP 5.3.0.
Options
* glob://
Options
Wrapper Summary
Attribute Supported
Restricted by allow_url_fopen No
Restricted by allow_url_include No
Allows Reading No
Allows Writing No
Allows Appending No
Allows Simultaneous Reading and Writing No
Supports stat() No
Supports unlink() No
Supports rename() No
Supports mkdir() No
Supports rmdir() No
Examples
Example #1 Basic usage
getFilename(), $f->getSize()/1024);
}
?>
tree.php: 1.0K
findregex.php: 0.6K
findfile.php: 0.7K
dba_dump.php: 0.9K
nocvsdir.php: 1.1K
phar_from_dir.php: 1.0K
ini_groups.php: 0.9K
directorytree.php: 0.9K
dba_array.php: 1.1K
class_tree.php: 1.8K
----------------------------------------------------------------------
----------------------------------------------------------------------
phar://
phar:// - PHP Archive
Description
The phar:// stream wrapper is available since PHP 5.3.0. See Phar stream
wrapper for detailed description.
Options
* phar://
Options
Wrapper Summary
Attribute Supported
Restricted by allow_url_fopen No
Restricted by allow_url_include No
Allows Reading Yes
Allows Writing Yes
Allows Appending No
Allows Simultaneous Reading and Writing Yes
Supports stat() Yes
Supports unlink() Yes
Supports rename() Yes
Supports mkdir() Yes
Supports rmdir() Yes
See Also
* Phar context options
----------------------------------------------------------------------
----------------------------------------------------------------------
ssh2://
ssh2:// - Secure Shell 2
Description
ssh2.shell:// ssh2.exec:// ssh2.tunnel:// ssh2.sftp:// ssh2.scp:// PHP
4.3.0 and up (PECL)
Note: This wrapper is not enabled by default
In order to use the ssh2.*:// wrappers you must install the >> SSH2
extension available from >> PECL.
In addition to accepting traditional URI login details, the ssh2 wrappers
will also reuse open connections by passing the connection resource in the
host portion of the URL.
Options
* ssh2.shell://user:pass@example.com:22/xterm
* ssh2.exec://user:pass@example.com:22/usr/local/bin/somecmd
* ssh2.tunnel://user:pass@example.com:22/192.168.0.1:14
* ssh2.sftp://user:pass@example.com:22/path/to/filename
Options
Wrapper Summary
Attribute ssh2.shell ssh2.exec ssh2.tunnel ssh2.sftp ssh2.scp
Restricted by Yes Yes Yes Yes Yes
allow_url_fopen
Allows Reading Yes Yes Yes Yes Yes
Allows Writing Yes Yes Yes Yes No
Yes (When
Allows Appending No No No supported by No
server)
Allows Simultaneous Yes Yes Yes Yes No
Reading and Writing
Supports stat() No No No Yes No
Supports unlink() No No No Yes No
Supports rename() No No No Yes No
Supports mkdir() No No No Yes No
Supports rmdir() No No No Yes No
Context options
Name Usage Default
session Preconnected ssh2 resource to be reused
sftp Preallocated sftp resource to be reused
methods Key exchange, hostkey, cipher,
compression, and MAC methods to use
callbacks
username Username to connect as
password Password to use with password
authentication
pubkey_file Name of public key file to use for
authentication
privkey_file Name of private key file to use for
authentication
env Associate array of environment variables
to set
term Terminal emulation type to request when
allocating a pty
term_width Width of terminal requested when
allocating a pty
term_height Height of terminal requested when
allocating a pty
term_units Units to use with term_width and SSH2_TERM_UNIT_CHARS
term_height
Examples
Example #1 Opening a stream from an active connection
----------------------------------------------------------------------
----------------------------------------------------------------------
rar://
rar:// - RAR
Description
The wrapper takes the url encoded path to the RAR archive (relative or
absolute), an optional asterik (*), an optional number sign (#) and an
optional url encoded entry name, as stored in the archive. Specifying an
entry name requires the number sign; a leading forward slash in the entry
name is optional.
This wrapper can open both files and directories. When opening
directories, the asterisk sign forces the directory entries names to be
returned unencoded. If it's not specified, they will be returned url
encoded - the reason for this is to allow the wrapper to be correctly used
with built-in functionality like the RecursiveDirectoryIterator in the
presence of file names that seem like url encoded data.
If the pound sign and the entry name part are not included, the root of
the archive will be displayed. This differs from regular directories in
that the resulting stream will not contain information such as the
modification time, as the root directory is not stored in an inidivual
entry in the archive. The usage of the wrapper with
RecursiveDirectoryIterator requires the number sign to be included in the
URL when accessing the root, so that the URLs of the children may be
constructed correctly.
Note: This wrapper is not enabled by default
In order to use the rar:// wrapper, you must install the >> rar
extension available from >> PECL.
rar:// Available since PECL rar 3.0.0
Options
* rar://[*][#[]]
Options
Wrapper Summary
Attribute Supported
Restricted by allow_url_fopen No
Restricted by allow_url_include No
Allows Reading Yes
Allows Writing No
Allows Appending No
Allows Simultaneous Reading and Writing No
Supports stat() Yes
Supports unlink() No
Supports rename() No
Supports mkdir() No
Supports rmdir() No
Context options
Name Usage Default
The password used to encrypt the headers of the
archive, if any. WinRAR will encrypt all the files
open_password with the same password as the headers password
when the later is present, so for archives with
encrypted headers, file_password will be ignored.
The password used to encrypt a file, if any. If
the headers are also encrypted, this option will
be ignored in favor of open_password. The reason
there are two options is to cover the possibility
file_password of supporting archives with different headers and
file passwords, should those archives arise. Note
that if the archive does not have its headers
encrypted, open_password will be ignored and this
option must be used instead.
A callback to determine the path of missing
volume_callback volumes. See RarArchive::open() for more
information.
Examples
Example #1 Traversing a RAR archive
getSubPathName()) .
(is_dir(parent::current())?" [DIR]":"");
}
}
$f = "rar://" . rawurlencode(dirname(__FILE__)) .
DIRECTORY_SEPARATOR . 'dirs_and_extra_headers.rar#';
$it = new RecursiveTreeIterator(new MyRecDirIt($f));
foreach ($it as $s) {
echo $s, "\n";
}
?>
The above example will output something similar to:
|-allow_everyone_ni [DIR]
|-file1.txt
|-file2_*.txt
|-with_streams.txt
\-* [DIR]
|-*\%2Fempty%2E [DIR]
| \-*\%2Fempty%2E\file7.txt
|-*\empty [DIR]
|-*\file3.txt
|-*\file4_*.txt
\-*\*_2 [DIR]
|-*\*_2\file5.txt
\-*\*_2\file6_*.txt
Example #2 Opening an encrypted file (header encryption)
array(
'open_password' => 'samplepassword'
)
)
)
);
var_dump(stream_get_contents($stream));
/* creation and last access date is opt-in in WinRAR, hence most
* files don't have them */
var_dump(fstat($stream));
?>
The above example will output something similar to:
string(26) "Encrypted file 1 contents."
Array
(
[0] => 0
[1] => 0
[2] => 33206
[3] => 1
[4] => 0
[5] => 0
[6] => 0
[7] => 26
[8] => 0
[9] => 1259550052
[10] => 0
[11] => -1
[12] => -1
[dev] => 0
[ino] => 0
[mode] => 33206
[nlink] => 1
[uid] => 0
[gid] => 0
[rdev] => 0
[size] => 26
[atime] => 0
[mtime] => 1259550052
[ctime] => 0
[blksize] => -1
[blocks] => -1
)
----------------------------------------------------------------------
----------------------------------------------------------------------
ogg://
ogg:// - Audio streams
Description
Files opened for reading via the ogg:// wrapper are treated as compressed
audio encoded using the OGG/Vorbis codec. Similarly, files opened for
writing or appending via the ogg:// wrapper are writen as compressed audio
data. stream_get_meta_data(), when used on an OGG/Vorbis file opened for
reading will return various details about the stream including the vendor
tag, any included comments, the number of channels, the sampling rate, and
the encoding rate range described by: bitrate_lower, bitrate_upper,
bitrate_nominal, and bitrate_window.
ogg:// PHP 4.3.0 and up (PECL)
Note: This wrapper is not enabled by default
In order to use the ogg:// wrapper you must install the >> OGG/Vorbis
extension available from >> PECL.
Options
* ogg://soundfile.ogg
* ogg:///path/to/soundfile.ogg
* ogg://http://www.example.com/path/to/soundstream.ogg
Options
Wrapper Summary
Attribute Supported
Restricted by allow_url_fopen No
Allows Reading Yes
Allows Writing Yes
Allows Appending Yes
Allows Simultaneous Reading and Writing No
Supports stat() No
Supports unlink() No
Supports rename() No
Supports mkdir() No
Supports rmdir() No
Context options
Name Usage Default Mode
PCM encoding to apply while
reading, one of:
OGGVORBIS_PCM_U8,
OGGVORBIS_PCM_S8,
pcm_mode OGGVORBIS_PCM_U16_BE, OGGVORBIS_PCM_S16_LE Read
OGGVORBIS_PCM_S16_BE,
OGGVORBIS_PCM_U16_LE, and
OGGVORBIS_PCM_S16_LE. (8 vs 16
bit, signed or unsigned, big or
little endian)
rate Sampling rate of input data, 44100 Write/Append
expressed in Hz
When given as an integer, the
fixed bitrate at which to
bitrate encode. (16000 to 131072) When 128000 Write/Append
given as a float, the variable
bitrate quality to use. (-1.0
to 1.0)
The number of audio channels to
channels encode, typically 1 (Mono), or 2 Write/Append
2 (Stero). May range as high as
16.
comments An array of string values to Write/Append
encode into the track header.
Examples
----------------------------------------------------------------------
----------------------------------------------------------------------
expect://
expect:// - Process Interaction Streams
Description
Streams opened via the expect:// wrapper provide access to process'es
stdio, stdout and stderr via PTY.
Note: This wrapper is not enabled by default
In order to use the expect:// wrapper you must install the >> Expect
extension available from >> PECL.
expect:// PHP 4.3.0 and up (PECL)
Options
* expect://command
Options
Wrapper Summary
Attribute Supported
Restricted by allow_url_fopen No
Allows Reading Yes
Allows Writing Yes
Allows Appending Yes
Allows Simultaneous Reading and Writing No
Supports stat() No
Supports unlink() No
Supports rename() No
Supports mkdir() No
Supports rmdir() No
Examples
----------------------------------------------------------------------
Table of Contents
* file:// - Accessing local filesystem
* http:// - Accessing HTTP(s) URLs
* ftp:// - Accessing FTP(s) URLs
* php:// - Accessing various I/O streams
* zlib:// - Compression Streams
* data:// - Data (RFC 2397)
* glob:// - Find pathnames matching pattern
* phar:// - PHP Archive
* ssh2:// - Secure Shell 2
* rar:// - RAR
* ogg:// - Audio streams
* expect:// - Process Interaction Streams
----------------------------------------------------------------------
* Basic syntax
* Escaping from HTML
* Instruction separation
* Comments
* Types
* Introduction
* Booleans
* Integers
* Floating point numbers
* Strings
* Arrays
* Objects
* Resources
* NULL
* Pseudo-types and variables used in this documentation
* Type Juggling
* Variables
* Basics
* Predefined Variables
* Variable scope
* Variable variables
* Variables From External Sources
* Constants
* Syntax
* Magic constants
* Expressions
* Operators
* Operator Precedence
* Arithmetic Operators
* Assignment Operators
* Bitwise Operators
* Comparison Operators
* Error Control Operators
* Execution Operators
* Incrementing/Decrementing Operators
* Logical Operators
* String Operators
* Array Operators
* Type Operators
* Control Structures
* Introduction
* if
* else
* elseif/else if
* Alternative syntax for control structures
* while
* do-while
* for
* foreach
* break
* continue
* switch
* declare
* return
* require
* include
* require_once
* include_once
* goto
* Functions
* User-defined functions
* Function arguments
* Returning values
* Variable functions
* Internal (built-in) functions
* Anonymous functions
* Classes and Objects
* Introduction
* The Basics
* Properties
* Class Constants
* Autoloading Classes
* Constructors and Destructors
* Visibility
* Object Inheritance
* Scope Resolution Operator (::)
* Static Keyword
* Class Abstraction
* Object Interfaces
* Overloading
* Object Iteration
* Patterns
* Magic Methods
* Final Keyword
* Object Cloning
* Comparing Objects
* Type Hinting
* Late Static Bindings
* Objects and references
* Object Serialization
* OOP Changelog
* Namespaces
* Namespaces overview
* Defining namespaces
* Declaring sub-namespaces
* Defining multiple namespaces in the same file
* Using namespaces: Basics
* Namespaces and dynamic language features
* namespace keyword and __NAMESPACE__ constant
* Using namespaces: Aliasing/Importing
* Global space
* Using namespaces: fallback to global function/constant
* Name resolution rules
* FAQ: things you need to know about namespaces
* Exceptions
* Extending Exceptions
* References Explained
* What References Are
* What References Do
* What References Are Not
* Passing by Reference
* Returning References
* Unsetting References
* Spotting References
* Predefined Variables
* Superglobals - Superglobals are built-in variables that are
always available in all scopes
* $GLOBALS - References all variables available in global scope
* $_SERVER - Server and execution environment information
* $_GET - HTTP GET variables
* $_POST - HTTP POST variables
* $_FILES - HTTP File Upload variables
* $_REQUEST - HTTP Request variables
* $_SESSION - Session variables
* $_ENV - Environment variables
* $_COOKIE - HTTP Cookies
* $php_errormsg - The previous error message
* $HTTP_RAW_POST_DATA - Raw POST data
* $http_response_header - HTTP response headers
* $argc - The number of arguments passed to script
* $argv - Array of arguments passed to script
* Predefined Exceptions
* Exception
* ErrorException
* Predefined Interfaces
* Traversable - The Traversable interface
* Iterator - The Iterator interface
* IteratorAggregate - The IteratorAggregate interface
* ArrayAccess - The ArrayAccess interface
* Serializable - The Serializable interface
* Context options and parameters
* Socket context options - Socket context option listing
* HTTP context options - HTTP context option listing
* FTP context options - FTP context option listing
* SSL context options - SSL context option listing
* CURL context options - CURL context option listing
* Phar context options - Phar context option listing
* Context parameters - Context parameter listing
* Supported Protocols and Wrappers
* file:// - Accessing local filesystem
* http:// - Accessing HTTP(s) URLs
* ftp:// - Accessing FTP(s) URLs
* php:// - Accessing various I/O streams
* zlib:// - Compression Streams
* data:// - Data (RFC 2397)
* glob:// - Find pathnames matching pattern
* phar:// - PHP Archive
* ssh2:// - Secure Shell 2
* rar:// - RAR
* ogg:// - Audio streams
* expect:// - Process Interaction Streams
----------------------------------------------------------------------
----------------------------------------------------------------------
Security
----------------------------------------------------------------------
Introduction
PHP is a powerful language and the interpreter, whether included in a web
server as a module or executed as a separate CGI binary, is able to access
files, execute commands and open network connections on the server. These
properties make anything run on a web server insecure by default. PHP is
designed specifically to be a more secure language for writing CGI
programs than Perl or C, and with correct selection of compile-time and
runtime configuration options, and proper coding practices, it can give
you exactly the combination of freedom and security you need.
As there are many different ways of utilizing PHP, there are many
configuration options controlling its behaviour. A large selection of
options guarantees you can use PHP for a lot of purposes, but it also
means there are combinations of these options and server configurations
that result in an insecure setup.
The configuration flexibility of PHP is equally rivalled by the code
flexibility. PHP can be used to build complete server applications, with
all the power of a shell user, or it can be used for simple server-side
includes with little risk in a tightly controlled environment. How you
build that environment, and how secure it is, is largely up to the PHP
developer.
This chapter starts with some general security advice, explains the
different configuration option combinations and the situations they can be
safely used, and describes different considerations in coding for
different levels of security.
----------------------------------------------------------------------
----------------------------------------------------------------------
General considerations
A completely secure system is a virtual impossibility, so an approach
often used in the security profession is one of balancing risk and
usability. If every variable submitted by a user required two forms of
biometric validation (such as a retinal scan and a fingerprint), you would
have an extremely high level of accountability. It would also take half an
hour to fill out a fairly complex form, which would tend to encourage
users to find ways of bypassing the security.
The best security is often unobtrusive enough to suit the requirements
without the user being prevented from accomplishing their work, or
over-burdening the code author with excessive complexity. Indeed, some
security attacks are merely exploits of this kind of overly built
security, which tends to erode over time.
A phrase worth remembering: A system is only as good as the weakest link
in a chain. If all transactions are heavily logged based on time,
location, transaction type, etc. but the user is only verified based on a
single cookie, the validity of tying the users to the transaction log is
severely weakened.
When testing, keep in mind that you will not be able to test all
possibilities for even the simplest of pages. The input you may expect
will be completely unrelated to the input given by a disgruntled employee,
a cracker with months of time on their hands, or a housecat walking across
the keyboard. This is why it's best to look at the code from a logical
perspective, to discern where unexpected data can be introduced, and then
follow how it is modified, reduced, or amplified.
The Internet is filled with people trying to make a name for themselves by
breaking your code, crashing your site, posting inappropriate content, and
otherwise making your day interesting. It doesn't matter if you have a
small or large site, you are a target by simply being online, by having a
server that can be connected to. Many cracking programs do not discern by
size, they simply trawl massive IP blocks looking for victims. Try not to
become one.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installed as CGI binary
Table of Contents
* Possible attacks
* Case 1: only public files served
* Case 2: using cgi.force_redirect
* Case 3: setting doc_root or user_dir
* Case 4: PHP parser outside of web tree
----------------------------------------------------------------------
Possible attacks
Using PHP as a CGI binary is an option for setups that for some reason do
not wish to integrate PHP as a module into server software (like Apache),
or will use PHP with different kinds of CGI wrappers to create safe chroot
and setuid environments for scripts. This setup usually involves
installing executable PHP binary to the web server cgi-bin directory. CERT
advisory >> CA-96.11 recommends against placing any interpreters into
cgi-bin. Even if the PHP binary can be used as a standalone interpreter,
PHP is designed to prevent the attacks this setup makes possible:
* Accessing system files: http://my.host/cgi-bin/php?/etc/passwd The
query information in a URL after the question mark (?) is passed as
command line arguments to the interpreter by the CGI interface.
Usually interpreters open and execute the file specified as the first
argument on the command line. When invoked as a CGI binary, PHP
refuses to interpret the command line arguments.
* Accessing any web document on server:
http://my.host/cgi-bin/php/secret/doc.html The path information part
of the URL after the PHP binary name, /secret/doc.html is
conventionally used to specify the name of the file to be opened and
interpreted by the CGI program. Usually some web server configuration
directives (Apache: Action) are used to redirect requests to documents
like http://my.host/secret/script.php to the PHP interpreter. With
this setup, the web server first checks the access permissions to the
directory /secret, and after that creates the redirected request
http://my.host/cgi-bin/php/secret/script.php. Unfortunately, if the
request is originally given in this form, no access checks are made by
web server for file /secret/script.php, but only for the /cgi-bin/php
file. This way any user able to access /cgi-bin/php is able to access
any protected document on the web server. In PHP, runtime
configuration directives cgi.force_redirect, doc_root and user_dir can
be used to prevent this attack, if the server document tree has any
directories with access restrictions. See below for full the
explanation of the different combinations.
----------------------------------------------------------------------
----------------------------------------------------------------------
Case 1: only public files served
If your server does not have any content that is not restricted by
password or ip based access control, there is no need for these
configuration options. If your web server does not allow you to do
redirects, or the server does not have a way to communicate to the PHP
binary that the request is a safely redirected request, you can specify
the option --enable-force-cgi-redirect to the configure script. You still
have to make sure your PHP scripts do not rely on one or another way of
calling the script, neither by directly
http://my.host/cgi-bin/php/dir/script.php nor by redirection
http://my.host/dir/script.php.
Redirection can be configured in Apache by using AddHandler and Action
directives (see below).
----------------------------------------------------------------------
----------------------------------------------------------------------
Case 2: using cgi.force_redirect
The configuration directive cgi.force_redirect prevents anyone from
calling PHP directly with a URL like
http://my.host/cgi-bin/php/secretdir/script.php. Instead, PHP will only
parse in this mode if it has gone through a web server redirect rule. PHP
older than 4.2.0 used --enable-force-cgi-redirect compile time option for
this.
Usually the redirection in the Apache configuration is done with the
following directives:
Action php-script /cgi-bin/php
AddHandler php-script .php
This option has only been tested with the Apache web server, and relies on
Apache to set the non-standard CGI environment variable REDIRECT_STATUS on
redirected requests. If your web server does not support any way of
telling if the request is direct or redirected, you cannot use this option
and you must use one of the other ways of running the CGI version
documented here.
----------------------------------------------------------------------
----------------------------------------------------------------------
Case 3: setting doc_root or user_dir
To include active content, like scripts and executables, in the web server
document directories is sometimes considered an insecure practice. If,
because of some configuration mistake, the scripts are not executed but
displayed as regular HTML documents, this may result in leakage of
intellectual property or security information like passwords. Therefore
many sysadmins will prefer setting up another directory structure for
scripts that are accessible only through the PHP CGI, and therefore always
interpreted and not displayed as such.
Also if the method for making sure the requests are not redirected, as
described in the previous section, is not available, it is necessary to
set up a script doc_root that is different from web document root.
You can set the PHP script document root by the configuration directive
doc_root in the configuration file, or you can set the environment
variable PHP_DOCUMENT_ROOT. If it is set, the CGI version of PHP will
always construct the file name to open with this doc_root and the path
information in the request, so you can be sure no script is executed
outside this directory (except for user_dir below).
Another option usable here is user_dir. When user_dir is unset, only thing
controlling the opened file name is doc_root. Opening a URL like
http://my.host/~user/doc.php does not result in opening a file under users
home directory, but a file called ~user/doc.php under doc_root (yes, a
directory name starting with a tilde [~]).
If user_dir is set to for example public_php, a request like
http://my.host/~user/doc.php will open a file called doc.php under the
directory named public_php under the home directory of the user. If the
home of the user is /home/user, the file executed is
/home/user/public_php/doc.php.
user_dir expansion happens regardless of the doc_root setting, so you can
control the document root and user directory access separately.
----------------------------------------------------------------------
----------------------------------------------------------------------
Case 4: PHP parser outside of web tree
A very secure option is to put the PHP parser binary somewhere outside of
the web tree of files. In /usr/local/bin, for example. The only real
downside to this option is that you will now have to put a line similar
to:
#!/usr/local/bin/php
as the first line of any file containing PHP tags. You will also need to
make the file executable. That is, treat it exactly as you would treat any
other CGI script written in Perl or sh or any other common scripting
language which uses the #! shell-escape mechanism for launching itself.
To get PHP to handle PATH_INFO and PATH_TRANSLATED information correctly
with this setup, the PHP parser should be compiled with the
--enable-discard-path configure option.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Installed as an Apache module
When PHP is used as an Apache module it inherits Apache's user permissions
(typically those of the "nobody" user). This has several impacts on
security and authorization. For example, if you are using PHP to access a
database, unless that database has built-in access control, you will have
to make the database accessible to the "nobody" user. This means a
malicious script could access and modify the database, even without a
username and password. It's entirely possible that a web spider could
stumble across a database administrator's web page, and drop all of your
databases. You can protect against this with Apache authorization, or you
can design your own access model using LDAP, .htaccess files, etc. and
include that code as part of your PHP scripts.
Often, once security is established to the point where the PHP user (in
this case, the apache user) has very little risk attached to it, it is
discovered that PHP is now prevented from writing any files to user
directories. Or perhaps it has been prevented from accessing or changing
databases. It has equally been secured from writing good and bad files, or
entering good and bad database transactions.
A frequent security mistake made at this point is to allow apache root
permissions, or to escalate apache's abilities in some other way.
Escalating the Apache user's permissions to root is extremely dangerous
and may compromise the entire system, so sudo'ing, chroot'ing, or
otherwise running as root should not be considered by those who are not
security professionals.
There are some simpler solutions. By using open_basedir you can control
and restrict what directories are allowed to be used for PHP. You can also
set up apache-only areas, to restrict all web based activity to non-user,
or non-system, files.
----------------------------------------------------------------------
----------------------------------------------------------------------
Filesystem Security
Table of Contents
* Null bytes related issues
PHP is subject to the security built into most server systems with respect
to permissions on a file and directory basis. This allows you to control
which files in the filesystem may be read. Care should be taken with any
files which are world readable to ensure that they are safe for reading by
all users who have access to that filesystem.
Since PHP was designed to allow user level access to the filesystem, it's
entirely possible to write a PHP script that will allow you to read system
files such as /etc/passwd, modify your ethernet connections, send massive
printer jobs out, etc. This has some obvious implications, in that you
need to ensure that the files that you read from and write to are the
appropriate ones.
Consider the following script, where a user indicates that they'd like to
delete a file in their home directory. This assumes a situation where a
PHP web interface is regularly used for file management, so the Apache
user is allowed to delete files in the user home directories.
Example #1 Poor variable checking leads to....
Since the username and the filename are postable from a user form, they
can submit a username and a filename belonging to someone else, and delete
it even if they're not supposed to be allowed to do so. In this case,
you'd want to use some other form of authentication. Consider what could
happen if the variables submitted were "../etc/" and "passwd". The code
would then effectively read:
Example #2 ... A filesystem attack
There are two important measures you should take to prevent these issues.
* Only allow limited permissions to the PHP web user binary.
* Check all variables which are submitted.
Here is an improved script:
Example #3 More secure file name checking
However, even this is not without its flaws. If your authentication system
allowed users to create their own user logins, and a user chose the login
"../etc/", the system is once again exposed. For this reason, you may
prefer to write a more customized check:
Example #4 More secure file name checking
Depending on your operating system, there are a wide variety of files
which you should be concerned about, including device entries (/dev/ or
COM1), configuration files (/etc/ files and the .ini files), well known
file storage areas (/home/, My Documents), etc. For this reason, it's
usually easier to create a policy where you forbid everything except for
what you explicitly allow.
----------------------------------------------------------------------
Null bytes related issues
As PHP uses the underlying C functions for filesystem related operations,
it may handle null bytes in a quite unexpected way. As null bytes denote
the end of a string in C, strings containing them won't be considered
entirely but rather only until a null byte occurs. The following example
shows a vulnerable code that demonstrates this problem:
Example #1 Script vulnerable to null bytes
Therefore, any tainted string that is used in a filesystem operation
should always be validated properly. Here is a better version of the
previous example:
Example #2 Correctly validating the input
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Database Security
Table of Contents
* Designing Databases
* Connecting to Database
* Encrypted Storage Model
* SQL Injection
Nowadays, databases are cardinal components of any web based application
by enabling websites to provide varying dynamic content. Since very
sensitive or secret information can be stored in a database, you should
strongly consider protecting your databases.
To retrieve or to store any information you need to connect to the
database, send a legitimate query, fetch the result, and close the
connection. Nowadays, the commonly used query language in this interaction
is the Structured Query Language (SQL). See how an attacker can tamper
with an SQL query.
As you can surmise, PHP cannot protect your database by itself. The
following sections aim to be an introduction into the very basics of how
to access and manipulate databases within PHP scripts.
Keep in mind this simple rule: defense in depth. The more places you take
action to increase the protection of your database, the less probability
of an attacker succeeding in exposing or abusing any stored information.
Good design of the database schema and the application deals with your
greatest fears.
----------------------------------------------------------------------
Designing Databases
The first step is always to create the database, unless you want to use
one from a third party. When a database is created, it is assigned to an
owner, who executed the creation statement. Usually, only the owner (or a
superuser) can do anything with the objects in that database, and in order
to allow other users to use it, privileges must be granted.
Applications should never connect to the database as its owner or a
superuser, because these users can execute any query at will, for example,
modifying the schema (e.g. dropping tables) or deleting its entire
content.
You may create different database users for every aspect of your
application with very limited rights to database objects. The most
required privileges should be granted only, and avoid that the same user
can interact with the database in different use cases. This means that if
intruders gain access to your database using your applications
credentials, they can only effect as many changes as your application can.
You are encouraged not to implement all the business logic in the web
application (i.e. your script), instead do it in the database schema using
views, triggers or rules. If the system evolves, new ports will be
intended to open to the database, and you have to re-implement the logic
in each separate database client. Over and above, triggers can be used to
transparently and automatically handle fields, which often provides
insight when debugging problems with your application or tracing back
transactions.
----------------------------------------------------------------------
----------------------------------------------------------------------
Connecting to Database
You may want to establish the connections over SSL to encrypt
client/server communications for increased security, or you can use ssh to
encrypt the network connection between clients and the database server. If
either of these is used, then monitoring your traffic and gaining
information about your database will be difficult for a would-be attacker.
----------------------------------------------------------------------
----------------------------------------------------------------------
Encrypted Storage Model
SSL/SSH protects data travelling from the client to the server, SSL/SSH
does not protect the persistent data stored in a database. SSL is an
on-the-wire protocol.
Once an attacker gains access to your database directly (bypassing the
webserver), the stored sensitive data may be exposed or misused, unless
the information is protected by the database itself. Encrypting the data
is a good way to mitigate this threat, but very few databases offer this
type of data encryption.
The easiest way to work around this problem is to first create your own
encryption package, and then use it from within your PHP scripts. PHP can
assist you in this with several extensions, such as Mcrypt and Mhash,
covering a wide variety of encryption algorithms. The script encrypts the
data before inserting it into the database, and decrypts it when
retrieving. See the references for further examples of how encryption
works.
In case of truly hidden data, if its raw representation is not needed
(i.e. not be displayed), hashing may also be taken into consideration. The
well-known example for the hashing is storing the MD5 hash of a password
in a database, instead of the password itself. See also crypt() and md5().
Example #1 Using hashed password field
0) {
echo 'Welcome, $username!';
} else {
echo 'Authentication failed for $username.';
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
SQL Injection
Many web developers are unaware of how SQL queries can be tampered with,
and assume that an SQL query is a trusted command. It means that SQL
queries are able to circumvent access controls, thereby bypassing standard
authentication and authorization checks, and sometimes SQL queries even
may allow access to host operating system level commands.
Direct SQL Command Injection is a technique where an attacker creates or
alters existing SQL commands to expose hidden data, or to override
valuable ones, or even to execute dangerous system level commands on the
database host. This is accomplished by the application taking user input
and combining it with static parameters to build an SQL query. The
following examples are based on true stories, unfortunately.
Owing to the lack of input validation and connecting to the database on
behalf of a superuser or the one who can create users, the attacker may
create a superuser in your database.
Example #1 Splitting the result set into pages ... and making superusers
(PostgreSQL)
Normal users click on the 'next', 'prev' links where the $offset is
encoded into the URL. The script expects that the incoming $offset is a
decimal number. However, what if someone tries to break in by appending a
urlencode()'d form of the following to the URL
0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
select 'crack', usesysid, 't','t','crack'
from pg_shadow where usename='postgres';
--
If it happened, then the script would present a superuser access to him.
Note that 0; is to supply a valid offset to the original query and to
terminate it.
Note:
It is common technique to force the SQL parser to ignore the rest of the
query written by the developer with -- which is the comment sign in SQL.
A feasible way to gain passwords is to circumvent your search result
pages. The only thing the attacker needs to do is to see if there are any
submitted variables used in SQL statements which are not handled properly.
These filters can be set commonly in a preceding form to customize WHERE,
ORDER BY, LIMIT and OFFSET clauses in SELECT statements. If your database
supports the UNION construct, the attacker may try to append an entire
query to the original one to list passwords from an arbitrary table. Using
encrypted password fields is strongly encouraged.
Example #2 Listing out articles ... and some passwords (any database
server)
The static part of the query can be combined with another SELECT statement
which reveals all passwords:
'
union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable;
--
If this query (playing with the ' and --) were assigned to one of the
variables used in $query, the query beast awakened.
SQL UPDATE's are also susceptible to attack. These queries are also
threatened by chopping and appending an entirely new query to it. But the
attacker might fiddle with the SET clause. In this case some schema
information must be possessed to manipulate the query successfully. This
can be acquired by examining the form variable names, or just simply brute
forcing. There are not so many naming conventions for fields storing
passwords or usernames.
Example #3 From resetting a password ... to gaining more privileges (any
database server)
But a malicious user sumbits the value ' or uid like'%admin%'; -- to $uid
to change the admin's password, or simply sets $pwd to "hehehe',
admin='yes', trusted=100 " (with a trailing space) to gain more
privileges. Then, the query will be twisted:
A frightening example how operating system level commands can be accessed
on some database hosts.
Example #4 Attacking the database hosts operating system (MSSQL Server)
If attacker submits the value a%' exec master..xp_cmdshell 'net user test
testpass /ADD' -- to $prod, then the $query will be:
MSSQL Server executes the SQL statements in the batch including a command
to add a new user to the local accounts database. If this application were
running as sa and the MSSQLSERVER service is running with sufficient
privileges, the attacker would now have an account with which to access
this machine.
Note:
Some of the examples above is tied to a specific database server. This
does not mean that a similar attack is impossible against other
products. Your database server may be similarly vulnerable in another
manner.
A worked example of the issues regarding SQL Injection
Image courtesy of >> xkcd
Avoidance Techniques
While it remains obvious that an attacker must possess at least some
knowledge of the database architecture in order to conduct a successful
attack, obtaining this information is often very simple. For example, if
the database is part of an open source or other publicly-available
software package with a default installation, this information is
completely open and available. This information may also be divulged by
closed-source code - even if it's encoded, obfuscated, or compiled - and
even by your very own code through the display of error messages. Other
methods include the user of common table and column names. For example, a
login form that uses a 'users' table with column names 'id', 'username',
and 'password'.
These attacks are mainly based on exploiting the code not being written
with security in mind. Never trust any kind of input, especially that
which comes from the client side, even though it comes from a select box,
a hidden input field or a cookie. The first example shows that such a
blameless query can cause disasters.
* Never connect to the database as a superuser or as the database owner.
Use always customized users with very limited privileges.
* Check if the given input has the expected data type. PHP has a wide
range of input validating functions, from the simplest ones found in
Variable Functions and in Character Type Functions (e.g. is_numeric(),
ctype_digit() respectively) and onwards to the Perl compatible Regular
Expressions support.
* If the application waits for numerical input, consider verifying data
with is_numeric(), or silently change its type using settype(), or use
its numeric representation by sprintf().
Example #5 A more secure way to compose a query for paging
* Quote each non numeric user supplied value that is passed to the
database with the database-specific string escape function (e.g.
mysql_real_escape_string(), sqlite_escape_string(), etc.). If a
database-specific string escape mechanism is not available, the
addslashes() and str_replace() functions may be useful (depending on
database type). See the first example. As the example shows, adding
quotes to the static part of the query is not enough, making this
query easily crackable.
* Do not print out any database specific information, especially about
the schema, by fair means or foul. See also Error Reporting and Error
Handling and Logging Functions.
* You may use stored procedures and previously defined cursors to
abstract data access so that users do not directly access tables or
views, but this solution has another impacts.
Besides these, you benefit from logging queries either within your script
or by the database itself, if it supports logging. Obviously, the logging
is unable to prevent any harmful attempt, but it can be helpful to trace
back which application has been circumvented. The log is not useful by
itself, but through the information it contains. More detail is generally
better than less.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Error Reporting
With PHP security, there are two sides to error reporting. One is
beneficial to increasing security, the other is detrimental.
A standard attack tactic involves profiling a system by feeding it
improper data, and checking for the kinds, and contexts, of the errors
which are returned. This allows the system cracker to probe for
information about the server, to determine possible weaknesses. For
example, if an attacker had gleaned information about a page based on a
prior form submission, they may attempt to override variables, or modify
them:
Example #1 Attacking Variables with a custom HTML page
The PHP errors which are normally returned can be quite helpful to a
developer who is trying to debug a script, indicating such things as the
function or file that failed, the PHP file it failed in, and the line
number which the failure occurred in. This is all information that can be
exploited. It is not uncommon for a php developer to use show_source(),
highlight_string(), or highlight_file() as a debugging measure, but in a
live site, this can expose hidden variables, unchecked syntax, and other
dangerous information. Especially dangerous is running code from known
sources with built-in debugging handlers, or using common debugging
techniques. If the attacker can determine what general technique you are
using, they may try to brute-force a page, by sending various common
debugging strings:
Example #2 Exploiting common debugging variables
Regardless of the method of error handling, the ability to probe a system
for errors leads to providing an attacker with more information.
For example, the very style of a generic PHP error indicates a system is
running PHP. If the attacker was looking at an .html page, and wanted to
probe for the back-end (to look for known weaknesses in the system), by
feeding it the wrong data they may be able to determine that a system was
built with PHP.
A function error can indicate whether a system may be running a specific
database engine, or give clues as to how a web page or programmed or
designed. This allows for deeper investigation into open database ports,
or to look for specific bugs or weaknesses in a web page. By feeding
different pieces of bad data, for example, an attacker can determine the
order of authentication in a script, (from the line number errors) as well
as probe for exploits that may be exploited in different locations in the
script.
A filesystem or general PHP error can indicate what permissions the web
server has, as well as the structure and organization of files on the web
server. Developer written error code can aggravate this problem, leading
to easy exploitation of formerly "hidden" information.
There are three major solutions to this issue. The first is to scrutinize
all functions, and attempt to compensate for the bulk of the errors. The
second is to disable error reporting entirely on the running code. The
third is to use PHP's custom error handling functions to create your own
error handler. Depending on your security policy, you may find all three
to be applicable to your situation.
One way of catching this issue ahead of time is to make use of PHP's own
error_reporting(), to help you secure your code and find variable usage
that may be dangerous. By testing your code, prior to deployment, with
E_ALL, you can quickly find areas where your variables may be open to
poisoning or modification in other ways. Once you are ready for
deployment, you should either disable error reporting completely by
setting error_reporting() to 0, or turn off the error display using the
php.ini option display_errors, to insulate your code from probing. If you
choose to do the latter, you should also define the path to your log file
using the error_log ini directive, and turn log_errors on.
Example #3 Finding dangerous variables with E_ALL
----------------------------------------------------------------------
----------------------------------------------------------------------
Using Register Globals
Warning
This feature has been DEPRECATED as of PHP 5.3.0. Relying on this feature
is highly discouraged.
Perhaps the most controversial change in PHP is when the default value for
the PHP directive register_globals went from ON to OFF in PHP >> 4.2.0.
Reliance on this directive was quite common and many people didn't even
know it existed and assumed it's just how PHP works. This page will
explain how one can write insecure code with this directive but keep in
mind that the directive itself isn't insecure but rather it's the misuse
of it.
When on, register_globals will inject your scripts with all sorts of
variables, like request variables from HTML forms. This coupled with the
fact that PHP doesn't require variable initialization means writing
insecure code is that much easier. It was a difficult decision, but the
PHP community decided to disable this directive by default. When on,
people use variables yet really don't know for sure where they come from
and can only assume. Internal variables that are defined in the script
itself get mixed up with request data sent by users and disabling
register_globals changes this. Let's demonstrate with an example misuse of
register_globals:
Example #1 Example misuse with register_globals = on
When register_globals = on, our logic above may be compromised. When off,
$authorized can't be set via request so it'll be fine, although it really
is generally a good programming practice to initialize variables first.
For example, in our example above we might have first done $authorized =
false. Doing this first means our above code would work with
register_globals on or off as users by default would be unauthorized.
Another example is that of sessions. When register_globals = on, we could
also use $username in our example below but again you must realize that
$username could also come from other means, such as GET (through the URL).
Example #2 Example use of sessions with register_globals on or off
{$_SESSION['username']}";
} else {
echo "Hello Guest ";
echo "Would you like to login?";
}
?>
It's even possible to take preventative measures to warn when forging is
being attempted. If you know ahead of time exactly where a variable should
be coming from, you can check to see if the submitted data is coming from
an inappropriate kind of submission. While it doesn't guarantee that data
has not been forged, it does require an attacker to guess the right kind
of forging. If you don't care where the request data comes from, you can
use $_REQUEST as it contains a mix of GET, POST and COOKIE data. See also
the manual section on using variables from external sources.
Example #3 Detecting simple variable poisoning
Of course, simply turning off register_globals does not mean your code is
secure. For every piece of data that is submitted, it should also be
checked in other ways. Always validate your user data and initialize your
variables! To check for uninitialized variables you may turn up
error_reporting() to show E_NOTICE level errors.
For information about emulating register_globals being On or Off, see this
FAQ.
Note: Superglobals: availability note
Superglobal arrays such as $_GET, $_POST, and $_SERVER, etc. are
available as of PHP 4.1.0. For more information, read the manual section
on superglobals
----------------------------------------------------------------------
----------------------------------------------------------------------
User Submitted Data
The greatest weakness in many PHP programs is not inherent in the language
itself, but merely an issue of code not being written with security in
mind. For this reason, you should always take the time to consider the
implications of a given piece of code, to ascertain the possible damage if
an unexpected variable is submitted to it.
Example #1 Dangerous Variable Usage
You should always carefully examine your code to make sure that any
variables being submitted from a web browser are being properly checked,
and ask yourself the following questions:
* Will this script only affect the intended files?
* Can unusual or undesirable data be acted upon?
* Can this script be used in unintended ways?
* Can this be used in conjunction with other scripts in a negative
manner?
* Will any transactions be adequately logged?
By adequately asking these questions while writing the script, rather than
later, you prevent an unfortunate re-write when you need to increase your
security. By starting out with this mindset, you won't guarantee the
security of your system, but you can help improve it.
You may also want to consider turning off register_globals, magic_quotes,
or other convenience settings which may confuse you as to the validity,
source, or value of a given variable. Working with PHP in
error_reporting(E_ALL) mode can also help warn you about variables being
used before they are checked or initialized (so you can prevent unusual
data from being operated upon).
----------------------------------------------------------------------
----------------------------------------------------------------------
Magic Quotes
Table of Contents
* What are Magic Quotes
* Why did we use Magic Quotes
* Why not to use Magic Quotes
* Disabling Magic Quotes
Warning
This feature has been DEPRECATED as of PHP 5.3.0. Relying on this feature
is highly discouraged.
Magic Quotes is a process that automagically escapes incoming data to the
PHP script. It's preferred to code with magic quotes off and to instead
escape the data at runtime, as needed.
----------------------------------------------------------------------
What are Magic Quotes
Warning
This feature has been DEPRECATED as of PHP 5.3.0. Relying on this feature
is highly discouraged.
When on, all ' (single-quote), " (double quote), \ (backslash) and NULL
characters are escaped with a backslash automatically. This is identical
to what addslashes() does.
There are three magic quote directives:
* magic_quotes_gpc Affects HTTP Request data (GET, POST, and COOKIE).
Cannot be set at runtime, and defaults to on in PHP. See also
get_magic_quotes_gpc().
* magic_quotes_runtime If enabled, most functions that return data from
an external source, including databases and text files, will have
quotes escaped with a backslash. Can be set at runtime, and defaults
to off in PHP. See also set_magic_quotes_runtime() and
get_magic_quotes_runtime().
* magic_quotes_sybase If enabled, a single-quote is escaped with a
single-quote instead of a backslash. If on, it completely overrides
magic_quotes_gpc. Having both directives enabled means only single
quotes are escaped as ''. Double quotes, backslashes and NULL's will
remain untouched and unescaped. See also ini_get() for retrieving its
value.
----------------------------------------------------------------------
----------------------------------------------------------------------
Why did we use Magic Quotes
Warning
This feature has been DEPRECATED as of PHP 5.3.0. Relying on this feature
is highly discouraged.
* There is no reason to use magic quotes because they are no longer a
supported part of PHP. However, they did exist and did help a few
beginners blissfully and unknowingly write better (more secure) code.
But, when dealing with code that relies upon this behavior it's better
to update the code instead of turning magic quotes on. So why did this
feature exist? Simple, to help prevent SQL Injection. Today developers
are better aware of security and end up using database specific
escaping mechanisms and/or prepared statements instead of relying upon
features like magical quotes.
----------------------------------------------------------------------
----------------------------------------------------------------------
Why not to use Magic Quotes
Warning
This feature has been DEPRECATED as of PHP 5.3.0. Relying on this feature
is highly discouraged.
* Portability Assuming it to be on, or off, affects portability. Use
get_magic_quotes_gpc() to check for this, and code accordingly.
* Performance Because not every piece of escaped data is inserted into a
database, there is a performance loss for escaping all this data.
Simply calling on the escaping functions (like addslashes()) at
runtime is more efficient. Although php.ini-development enables these
directives by default, php.ini-production disables it. This
recommendation is mainly due to performance reasons.
* Inconvenience Because not all data needs escaping, it's often annoying
to see escaped data where it shouldn't be. For example, emailing from
a form, and seeing a bunch of \' within the email. To fix, this may
require excessive use of stripslashes().
----------------------------------------------------------------------
----------------------------------------------------------------------
Disabling Magic Quotes
The magic_quotes_gpc directive may only be disabled at the system level,
and not at runtime. In otherwords, use of ini_set() is not an option.
Example #1 Disabling magic quotes server side
An example that sets the value of these directives to Off in php.ini. For
additional details, read the manual section titled How to change
configuration settings.
; Magic quotes
;
; Magic quotes for incoming GET/POST/Cookie data.
magic_quotes_gpc = Off
; Magic quotes for runtime-generated data, e.g. data from SQL, from exec(), etc.
magic_quotes_runtime = Off
; Use Sybase-style magic quotes (escape ' with '' instead of \').
magic_quotes_sybase = Off
If access to the server configuration is unavailable, use of .htaccess is
also an option. For example:
php_flag magic_quotes_gpc Off
In the interest of writing portable code (code that works in any
environment), like if setting at the server level is not possible, here's
an example to disable magic_quotes_gpc at runtime. This method is
inefficient so it's preferred to instead set the appropriate directives
elsewhere.
Example #2 Disabling magic quotes at runtime
$v) {
unset($process[$key][$k]);
if (is_array($v)) {
$process[$key][stripslashes($k)] = $v;
$process[] = &$process[$key][stripslashes($k)];
} else {
$process[$key][stripslashes($k)] = stripslashes($v);
}
}
}
unset($process);
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Hiding PHP
In general, security by obscurity is one of the weakest forms of security.
But in some cases, every little bit of extra security is desirable.
A few simple techniques can help to hide PHP, possibly slowing down an
attacker who is attempting to discover weaknesses in your system. By
setting expose_php to off in your php.ini file, you reduce the amount of
information available to them.
Another tactic is to configure web servers such as apache to parse
different filetypes through PHP, either with an .htaccess directive, or in
the apache configuration file itself. You can then use misleading file
extensions:
Example #1 Hiding PHP as another language
# Make PHP code look like other code types
AddType application/x-httpd-php .asp .py .pl
Or obscure it completely:
Example #2 Using unknown types for PHP extensions
# Make PHP code look like unknown types
AddType application/x-httpd-php .bop .foo .133t
Or hide it as HTML code, which has a slight performance hit because all
HTML will be parsed through the PHP engine:
Example #3 Using HTML types for PHP extensions
# Make all PHP code look like HTML
AddType application/x-httpd-php .htm .html
For this to work effectively, you must rename your PHP files with the
above extensions. While it is a form of security through obscurity, it's a
minor preventative measure with few drawbacks.
----------------------------------------------------------------------
----------------------------------------------------------------------
Keeping Current
PHP, like any other large system, is under constant scrutiny and
improvement. Each new version will often include both major and minor
changes to enhance security and repair any flaws, configuration mishaps,
and other issues that will affect the overall security and stability of
your system.
Like other system-level scripting languages and programs, the best
approach is to update often, and maintain awareness of the latest versions
and their changes.
----------------------------------------------------------------------
* Introduction
* General considerations
* Installed as CGI binary
* Possible attacks
* Case 1: only public files served
* Case 2: using cgi.force_redirect
* Case 3: setting doc_root or user_dir
* Case 4: PHP parser outside of web tree
* Installed as an Apache module
* Filesystem Security
* Null bytes related issues
* Database Security
* Designing Databases
* Connecting to Database
* Encrypted Storage Model
* SQL Injection
* Error Reporting
* Using Register Globals
* User Submitted Data
* Magic Quotes
* What are Magic Quotes
* Why did we use Magic Quotes
* Why not to use Magic Quotes
* Disabling Magic Quotes
* Hiding PHP
* Keeping Current
----------------------------------------------------------------------
----------------------------------------------------------------------
Features
----------------------------------------------------------------------
HTTP authentication with PHP
It is possible to use the header() function to send an "Authentication
Required" message to the client browser causing it to pop up a
Username/Password input window. Once the user has filled in a username and
a password, the URL containing the PHP script will be called again with
the predefined variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE set to
the user name, password and authentication type respectively. These
predefined variables are found in the $_SERVER and $HTTP_SERVER_VARS
arrays. Both "Basic" and "Digest" (since PHP 5.1.0) authentication methods
are supported. See the header() function for more information.
Note: PHP Version Note
Superglobals, such as $_SERVER, became available in PHP >> 4.1.0.
An example script fragment which would force client authentication on a
page is as follows:
Example #1 Basic HTTP Authentication example
Hello {$_SERVER['PHP_AUTH_USER']}.";
echo "You entered {$_SERVER['PHP_AUTH_PW']} as your password.
";
}
?>
Example #2 Digest HTTP Authentication example
This example shows you how to implement a simple Digest HTTP
authentication script. For more information read the >> RFC 2617.
password
$users = array('admin' => 'mypass', 'guest' => 'guest');
if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
die('Text to send if user hits Cancel button');
}
// analyze the PHP_AUTH_DIGEST variable
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
!isset($users[$data['username']]))
die('Wrong Credentials!');
// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);
if ($data['response'] != $valid_response)
die('Wrong Credentials!');
// ok, valid username & password
echo 'Your are logged in as: ' . $data['username'];
// function to parse the http auth header
function http_digest_parse($txt)
{
// protect against missing data
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
$data = array();
$keys = implode('|', array_keys($needed_parts));
preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$data[$m[1]] = $m[3] ? $m[3] : $m[4];
unset($needed_parts[$m[1]]);
}
return $needed_parts ? false : $data;
}
?>
Note: Compatibility Note
Please be careful when coding the HTTP header lines. In order to
guarantee maximum compatibility with all clients, the keyword "Basic"
should be written with an uppercase "B", the realm string must be
enclosed in double (not single) quotes, and exactly one space should
precede the 401 code in the HTTP/1.0 401 header line. Authentication
parameters have to be comma-separated as seen in the digest example
above.
Instead of simply printing out PHP_AUTH_USER and PHP_AUTH_PW, as done in
the above example, you may want to check the username and password for
validity. Perhaps by sending a query to a database, or by looking up the
user in a dbm file.
Watch out for buggy Internet Explorer browsers out there. They seem very
picky about the order of the headers. Sending the WWW-Authenticate header
before the HTTP/1.0 401 header seems to do the trick for now.
As of PHP 4.3.0, in order to prevent someone from writing a script which
reveals the password for a page that was authenticated through a
traditional external mechanism, the PHP_AUTH variables will not be set if
external authentication is enabled for that particular page and safe mode
is enabled. Regardless, REMOTE_USER can be used to identify the
externally-authenticated user. So, you can use $_SERVER['REMOTE_USER'].
Note: Configuration Note
PHP uses the presence of an AuthType directive to determine whether
external authentication is in effect.
Note, however, that the above does not prevent someone who controls a
non-authenticated URL from stealing passwords from authenticated URLs on
the same server.
Both Netscape Navigator and Internet Explorer will clear the local browser
window's authentication cache for the realm upon receiving a server
response of 401. This can effectively "log out" a user, forcing them to
re-enter their username and password. Some people use this to "time out"
logins, or provide a "log-out" button.
Example #3 HTTP Authentication example forcing a new name/password
Welcome: " . htmlspecialchars($_SERVER['PHP_AUTH_USER']) . " ";
echo "Old: " . htmlspecialchars($_REQUEST['OldAuth']);
echo "\n";
}
?>
This behavior is not required by the HTTP Basic authentication standard,
so you should never depend on this. Testing with Lynx has shown that Lynx
does not clear the authentication credentials with a 401 server response,
so pressing back and then forward again will open the resource as long as
the credential requirements haven't changed. The user can press the '_'
key to clear their authentication information, however.
Also note that until PHP 4.3.3, HTTP Authentication did not work using
Microsoft's IIS server with the CGI version of PHP due to a limitation of
IIS. In order to get it to work in PHP 4.3.3+, you must edit your IIS
configuration "Directory Security". Click on "Edit" and only check
"Anonymous Access", all other fields should be left unchecked.
Another limitation is if you're using the IIS module (ISAPI) and PHP 4,
you may not use the PHP_AUTH_* variables but instead, the variable
HTTP_AUTHORIZATION is available. For example, consider the following code:
list($user, $pw) = explode(':',
base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
Note: IIS Note:
For HTTP Authentication to work with IIS, the PHP directive
cgi.rfc2616_headers must be set to 0 (the default value).
Note:
If safe mode is enabled, the uid of the script is added to the realm
part of the WWW-Authenticate header.
----------------------------------------------------------------------
----------------------------------------------------------------------
Cookies
PHP transparently supports HTTP cookies. Cookies are a mechanism for
storing data in the remote browser and thus tracking or identifying return
users. You can set cookies using the setcookie() or setrawcookie()
function. Cookies are part of the HTTP header, so setcookie() must be
called before any output is sent to the browser. This is the same
limitation that header() has. You can use the output buffering functions
to delay the script output until you have decided whether or not to set
any cookies or send any headers.
Any cookies sent to you from the client will automatically be included
into a $_COOKIE auto-global array if variables_order contains "C". If you
wish to assign multiple values to a single cookie, just add [] to the
cookie name.
Depending on register_globals, regular PHP variables can be created from
cookies. However it's not recommended to rely on them as this feature is
often turned off for the sake of security. $HTTP_COOKIE_VARS is also set
in earlier versions of PHP when the track_vars configuration variable is
set. (This setting is always on since PHP 4.0.3.)
For more details, including notes on browser bugs, see the setcookie() and
setrawcookie() function.
----------------------------------------------------------------------
----------------------------------------------------------------------
Sessions
Session support in PHP consists of a way to preserve certain data across
subsequent accesses. This enables you to build more customized
applications and increase the appeal of your web site. All information is
in the Session reference section.
----------------------------------------------------------------------
----------------------------------------------------------------------
Dealing with XForms
>> XForms defines a variation on traditional webforms which allows them to
be used on a wider variety of platforms and browsers or even
non-traditional media such as PDF documents.
The first key difference in XForms is how the form is sent to the client.
>> XForms for HTML Authors contains a detailed description of how to
create XForms, for the purpose of this tutorial we'll only be looking at a
simple example.
Example #1 A simple XForms search form
Search
Find
Go
The above form displays a text input box (named q), and a submit button.
When the submit button is clicked, the form will be sent to the page
referred to by action.
Here's where it starts to look different from your web application's point
of view. In a normal HTML form, the data would be sent as
application/x-www-form-urlencoded, in the XForms world however, this
information is sent as XML formatted data.
If you're choosing to work with XForms then you probably want that data as
XML, in that case, look in $HTTP_RAW_POST_DATA where you'll find the XML
document generated by the browser which you can pass into your favorite
XSLT engine or document parser.
If you're not interested in formatting and just want your data to be
loaded into the traditional $_POST variable, you can instruct the client
browser to send it as application/x-www-form-urlencoded by changing the
method attribute to urlencoded-post.
Example #2 Using an XForm to populate $_POST
Search
Find
Go
Note: As of this writing, many browsers do not support XForms. Check
your browser version if the above examples fails.
----------------------------------------------------------------------
----------------------------------------------------------------------
Handling file uploads
Table of Contents
* POST method uploads
* Error Messages Explained
* Common Pitfalls
* Uploading multiple files
* PUT method support
----------------------------------------------------------------------
POST method uploads
This feature lets people upload both text and binary files. With PHP's
authentication and file manipulation functions, you have full control over
who is allowed to upload and what is to be done with the file once it has
been uploaded.
PHP is capable of receiving file uploads from any RFC-1867 compliant
browser.
Note: Related Configurations Note
See also the file_uploads, upload_max_filesize, upload_tmp_dir,
post_max_size and max_input_time directives in php.ini
PHP also supports PUT-method file uploads as used by Netscape Composer and
W3C's Amaya clients. See the PUT Method Support for more details.
Example #1 File Upload Form
A file upload screen can be built by creating a special form which looks
something like this:
The __URL__ in the above example should be replaced, and point to a PHP
file.
The MAX_FILE_SIZE hidden field (measured in bytes) must precede the file
input field, and its value is the maximum filesize accepted by PHP. This
form element should always be used as it saves users the trouble of
waiting for a big file being transferred only to find that it was too
large and the transfer failed. Keep in mind: fooling this setting on the
browser side is quite easy, so never rely on files with a greater size
being blocked by this feature. It is merely a convenience feature for
users on the client side of the application. The PHP settings (on the
server side) for maximum-size, however, cannot be fooled.
Note:
Be sure your file upload form has attribute
enctype="multipart/form-data" otherwise the file upload will not work.
The global $_FILES exists as of PHP 4.1.0 (Use $HTTP_POST_FILES instead if
using an earlier version). These arrays will contain all the uploaded file
information.
The contents of $_FILES from the example form is as follows. Note that
this assumes the use of the file upload name userfile, as used in the
example script above. This can be any name.
$_FILES['userfile']['name']
The original name of the file on the client machine.
$_FILES['userfile']['type']
The mime type of the file, if the browser provided this
information. An example would be "image/gif". This mime type is
however not checked on the PHP side and therefore don't take its
value for granted.
$_FILES['userfile']['size']
The size, in bytes, of the uploaded file.
$_FILES['userfile']['tmp_name']
The temporary filename of the file in which the uploaded file was
stored on the server.
$_FILES['userfile']['error']
The error code associated with this file upload. This element was
added in PHP 4.2.0
Files will, by default be stored in the server's default temporary
directory, unless another location has been given with the upload_tmp_dir
directive in php.ini. The server's default directory can be changed by
setting the environment variable TMPDIR in the environment in which PHP
runs. Setting it using putenv() from within a PHP script will not work.
This environment variable can also be used to make sure that other
operations are working on uploaded files, as well.
Example #2 Validating file uploads
See also the function entries for is_uploaded_file() and
move_uploaded_file() for further information. The following example will
process the file upload that came from a form.
';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print " ";
?>
The PHP script which receives the uploaded file should implement whatever
logic is necessary for determining what should be done with the uploaded
file. You can, for example, use the $_FILES['userfile']['size'] variable
to throw away any files that are either too small or too big. You could
use the $_FILES['userfile']['type'] variable to throw away any files that
didn't match a certain type criteria, but use this only as first of a
series of checks, because this value is completely under the control of
the client and not checked on the PHP side. As of PHP 4.2.0, you could use
$_FILES['userfile']['error'] and plan your logic according to the error
codes. Whatever the logic, you should either delete the file from the
temporary directory or move it elsewhere.
If no file is selected for upload in your form, PHP will return
$_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as
none.
The file will be deleted from the temporary directory at the end of the
request if it has not been moved away or renamed.
Example #3 Uploading array of files
PHP supports HTML array feature even with files.
$error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, "data/$name");
}
}
?>
File upload progress bar can be implemented by apc.rfc1867.
----------------------------------------------------------------------
----------------------------------------------------------------------
Error Messages Explained
Since PHP 4.2.0, PHP returns an appropriate error code along with the file
array. The error code can be found in the error segment of the file array
that is created during the file upload by PHP. In other words, the error
might be found in $_FILES['userfile']['error'].
UPLOAD_ERR_OK
Value: 0; There is no error, the file uploaded with success.
UPLOAD_ERR_INI_SIZE
Value: 1; The uploaded file exceeds the upload_max_filesize
directive in php.ini.
UPLOAD_ERR_FORM_SIZE
Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive
that was specified in the HTML form.
UPLOAD_ERR_PARTIAL
Value: 3; The uploaded file was only partially uploaded.
UPLOAD_ERR_NO_FILE
Value: 4; No file was uploaded.
UPLOAD_ERR_NO_TMP_DIR
Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and
PHP 5.0.3.
UPLOAD_ERR_CANT_WRITE
Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.
UPLOAD_ERR_EXTENSION
Value: 8; A PHP extension stopped the file upload. PHP does not
provide a way to ascertain which extension caused the file upload
to stop; examining the list of loaded extensions with phpinfo()
may help. Introduced in PHP 5.2.0.
Note:
These became PHP constants in PHP 4.3.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
Common Pitfalls
The MAX_FILE_SIZE item cannot specify a file size greater than the file
size that has been set in the upload_max_filesize in the php.ini file. The
default is 2 megabytes.
If a memory limit is enabled, a larger memory_limit may be needed. Make
sure you set memory_limit large enough.
If max_execution_time is set too small, script execution may be exceeded
by the value. Make sure you set max_execution_time large enough.
Note: max_execution_time only affects the execution time of the script
itself. Any time spent on activity that happens outside the execution of
the script such as system calls using system(), the sleep() function,
database queries, time taken by the file upload process, etc. is not
included when determining the maximum time that the script has been
running.
Warning
max_input_time sets the maximum time, in seconds, the script is allowed to
receive input; this includes file uploads. For large or multiple files, or
users on slower connections, the default of 60 seconds may be exceeded.
If post_max_size is set too small, large files cannot be uploaded. Make
sure you set post_max_size large enough.
Since PHP 5.2.12, the max_file_uploads configuration setting controls the
maximum number of files that can uploaded in one request. If more files
are uploaded than the limit, then $_FILES will stop processing files once
the limit is reached. For example, if max_file_uploads is set to 10, then
$_FILES will never contain more than 10 items.
Not validating which file you operate on may mean that users can access
sensitive information in other directories.
Please note that the CERN httpd seems to strip off everything starting at
the first whitespace in the content-type mime header it gets from the
client. As long as this is the case, CERN httpd will not support the file
upload feature.
Due to the large amount of directory listing styles we cannot guarantee
that files with exotic names (like containing spaces) are handled
properly.
A developer may not mix normal input fields and file upload fields in the
same form variable (by using an input name like foo[]).
----------------------------------------------------------------------
----------------------------------------------------------------------
Uploading multiple files
Multiple files can be uploaded using different name for input.
It is also possible to upload multiple files simultaneously and have the
information organized automatically in arrays for you. To do so, you need
to use the same array submission syntax in the HTML form as you do with
multiple selects and checkboxes:
Example #1 Uploading multiple files
When the above form is submitted, the arrays $_FILES['userfile'],
$_FILES['userfile']['name'], and $_FILES['userfile']['size'] will be
initialized (as well as in $HTTP_POST_FILES for PHP versions prior to
4.1.0). When register_globals is on, globals for uploaded files are also
initialized. Each of these will be a numerically indexed array of the
appropriate values for the submitted files.
For instance, assume that the filenames /home/test/review.html and
/home/test/xwp.out are submitted. In this case,
$_FILES['userfile']['name'][0] would contain the value review.html, and
$_FILES['userfile']['name'][1] would contain the value xwp.out. Similarly,
$_FILES['userfile']['size'][0] would contain review.html's file size, and
so forth.
$_FILES['userfile']['name'][0], $_FILES['userfile']['tmp_name'][0],
$_FILES['userfile']['size'][0], and $_FILES['userfile']['type'][0] are
also set.
Warning
Since PHP 5.2.12, the max_file_uploads configuration setting acts as a
limit on the number of files that can be uploaded in one request. You will
need to ensure that your form does not try to upload more files in one
request than this limit.
----------------------------------------------------------------------
----------------------------------------------------------------------
PUT method support
PHP provides support for the HTTP PUT method used by some clients to store
files on a server. PUT requests are much simpler than a file upload using
POST requests and they look something like this:
PUT /path/filename.html HTTP/1.1
This would normally mean that the remote client would like to save the
content that follows as: /path/filename.html in your web tree. It is
obviously not a good idea for Apache or PHP to automatically let everybody
overwrite any files in your web tree. So, to handle such a request you
have to first tell your web server that you want a certain PHP script to
handle the request. In Apache you do this with the Script directive. It
can be placed almost anywhere in your Apache configuration file. A common
place is inside a block or perhaps inside a
block. A line like this would do the trick:
Script PUT /put.php
This tells Apache to send all PUT requests for URIs that match the context
in which you put this line to the put.php script. This assumes, of course,
that you have PHP enabled for the .php extension and PHP is active. The
destination resource for all PUT requests to this script has to be the
script itself, not a filename the uploaded file should have.
With PHP you would then do something like the following in your put.php.
This would copy the contents of the uploaded file to the file
myputfile.ext on the server. You would probably want to perform some
checks and/or authenticate the user before performing this file copy.
Example #1 Saving HTTP PUT files
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Using remote files
As long as allow_url_fopen is enabled in php.ini, you can use HTTP and FTP
URLs with most of the functions that take a filename as a parameter. In
addition, URLs can be used with the include(), include_once(), require()
and require_once() statements (since PHP 5.2.0, allow_url_include must be
enabled for these). See Supported Protocols and Wrappers for more
information about the protocols supported by PHP.
Note:
In PHP 4.0.3 and older, in order to use URL wrappers, you were required
to configure PHP using the configure option --enable-url-fopen-wrapper .
Note:
The Windows versions of PHP earlier than PHP 4.3 did not support remote
file accessing for the following functions: include(), include_once(),
require(), require_once(), and the imagecreatefromXXX functions in the
GD and Image Functions extension.
For example, you can use this to open a file on a remote web server, parse
the output for the data you want, and then use that data in a database
query, or simply to output it in a style matching the rest of your
website.
Example #1 Getting the title of a remote page
Unable to open remote file.\n";
exit;
}
while (!feof ($file)) {
$line = fgets ($file, 1024);
/* This only works if the title and its tags are on one line */
if (preg_match ("@\(.*)\ @i", $line, $out)) {
$title = $out[1];
break;
}
}
fclose($file);
?>
You can also write to files on an FTP server (provided that you have
connected as a user with the correct access rights). You can only create
new files using this method; if you try to overwrite a file that already
exists, the fopen() call will fail.
To connect as a user other than 'anonymous', you need to specify the
username (and possibly password) within the URL, such as
'ftp://user:password@ftp.example.com/path/to/file'. (You can use the same
sort of syntax to access files via HTTP when they require Basic
authentication.)
Example #2 Storing data on a remote server
Unable to open remote file for writing.\n";
exit;
}
/* Write the data here. */
fwrite ($file, $_SERVER['HTTP_USER_AGENT'] . "\n");
fclose ($file);
?>
Note:
You might get the idea from the example above that you can use this
technique to write to a remote log file. Unfortunately that would not
work because the fopen() call will fail if the remote file already
exists. To do distributed logging like that, you should take a look at
syslog().
----------------------------------------------------------------------
----------------------------------------------------------------------
Connection handling
Internally in PHP a connection status is maintained. There are 3 possible
states:
* 0 - NORMAL
* 1 - ABORTED
* 2 - TIMEOUT
When a PHP script is running normally the NORMAL state, is active. If the
remote client disconnects the ABORTED state flag is turned on. A remote
client disconnect is usually caused by the user hitting his STOP button.
If the PHP-imposed time limit (see set_time_limit()) is hit, the TIMEOUT
state flag is turned on.
You can decide whether or not you want a client disconnect to cause your
script to be aborted. Sometimes it is handy to always have your scripts
run to completion even if there is no remote browser receiving the output.
The default behaviour is however for your script to be aborted when the
remote client disconnects. This behaviour can be set via the
ignore_user_abort php.ini directive as well as through the corresponding
php_value ignore_user_abort Apache httpd.conf directive or with the
ignore_user_abort() function. If you do not tell PHP to ignore a user
abort and the user aborts, your script will terminate. The one exception
is if you have registered a shutdown function using
register_shutdown_function(). With a shutdown function, when the remote
user hits his STOP button, the next time your script tries to output
something PHP will detect that the connection has been aborted and the
shutdown function is called. This shutdown function will also get called
at the end of your script terminating normally, so to do something
different in case of a client disconnect you can use the
connection_aborted() function. This function will return TRUE if the
connection was aborted.
Your script can also be terminated by the built-in script timer. The
default timeout is 30 seconds. It can be changed using the
max_execution_time php.ini directive or the corresponding php_value
max_execution_time Apache httpd.conf directive as well as with the
set_time_limit() function. When the timer expires the script will be
aborted and as with the above client disconnect case, if a shutdown
function has been registered it will be called. Within this shutdown
function you can check to see if a timeout caused the shutdown function to
be called by calling the connection_status() function. This function will
return 2 if a timeout caused the shutdown function to be called.
One thing to note is that both the ABORTED and the TIMEOUT states can be
active at the same time. This is possible if you tell PHP to ignore user
aborts. PHP will still note the fact that a user may have broken the
connection, but the script will keep running. If it then hits the time
limit it will be aborted and your shutdown function, if any, will be
called. At this point you will find that connection_status() returns 3.
----------------------------------------------------------------------
----------------------------------------------------------------------
Persistent Database Connections
Persistent connections are links that do not close when the execution of
your script ends. When a persistent connection is requested, PHP checks if
there's already an identical persistent connection (that remained open
from earlier) - and if it exists, it uses it. If it does not exist, it
creates the link. An 'identical' connection is a connection that was
opened to the same host, with the same username and the same password
(where applicable).
People who aren't thoroughly familiar with the way web servers work and
distribute the load may mistake persistent connects for what they're not.
In particular, they do not give you an ability to open 'user sessions' on
the same link, they do not give you an ability to build up a transaction
efficiently, and they don't do a whole lot of other things. In fact, to be
extremely clear about the subject, persistent connections don't give you
any functionality that wasn't possible with their non-persistent brothers.
Why?
This has to do with the way web servers work. There are three ways in
which your web server can utilize PHP to generate web pages.
The first method is to use PHP as a CGI "wrapper". When run this way, an
instance of the PHP interpreter is created and destroyed for every page
request (for a PHP page) to your web server. Because it is destroyed after
every request, any resources that it acquires (such as a link to an SQL
database server) are closed when it is destroyed. In this case, you do not
gain anything from trying to use persistent connections -- they simply
don't persist.
The second, and most popular, method is to run PHP as a module in a
multiprocess web server, which currently only includes Apache. A
multiprocess server typically has one process (the parent) which
coordinates a set of processes (its children) who actually do the work of
serving up web pages. When a request comes in from a client, it is handed
off to one of the children that is not already serving another client.
This means that when the same client makes a second request to the server,
it may be served by a different child process than the first time. When
opening a persistent connection, every following page requesting SQL
services can reuse the same established connection to the SQL server.
The last method is to use PHP as a plug-in for a multithreaded web server.
Currently PHP 4 has support for ISAPI, WSAPI, and NSAPI (on Windows),
which all allow PHP to be used as a plug-in on multithreaded servers like
Netscape FastTrack (iPlanet), Microsoft's Internet Information Server
(IIS), and O'Reilly's WebSite Pro. The behavior is essentially the same as
for the multiprocess model described before.
If persistent connections don't have any added functionality, what are
they good for?
The answer here is extremely simple -- efficiency. Persistent connections
are good if the overhead to create a link to your SQL server is high.
Whether or not this overhead is really high depends on many factors. Like,
what kind of database it is, whether or not it sits on the same computer
on which your web server sits, how loaded the machine the SQL server sits
on is and so forth. The bottom line is that if that connection overhead is
high, persistent connections help you considerably. They cause the child
process to simply connect only once for its entire lifespan, instead of
every time it processes a page that requires connecting to the SQL server.
This means that for every child that opened a persistent connection will
have its own open persistent connection to the server. For example, if you
had 20 different child processes that ran a script that made a persistent
connection to your SQL server, you'd have 20 different connections to the
SQL server, one from each child.
Note, however, that this can have some drawbacks if you are using a
database with connection limits that are exceeded by persistent child
connections. If your database has a limit of 16 simultaneous connections,
and in the course of a busy server session, 17 child threads attempt to
connect, one will not be able to. If there are bugs in your scripts which
do not allow the connections to shut down (such as infinite loops), the
database with only 16 connections may be rapidly swamped. Check your
database documentation for information on handling abandoned or idle
connections.
Warning
There are a couple of additional caveats to keep in mind when using
persistent connections. One is that when using table locking on a
persistent connection, if the script for whatever reason cannot release
the lock, then subsequent scripts using the same connection will block
indefinitely and may require that you either restart the httpd server or
the database server. Another is that when using transactions, a
transaction block will also carry over to the next script which uses that
connection if script execution ends before the transaction block does. In
either case, you can use register_shutdown_function() to register a simple
cleanup function to unlock your tables or roll back your transactions.
Better yet, avoid the problem entirely by not using persistent connections
in scripts which use table locks or transactions (you can still use them
elsewhere).
An important summary. Persistent connections were designed to have
one-to-one mapping to regular connections. That means that you should
always be able to replace persistent connections with non-persistent
connections, and it won't change the way your script behaves. It may (and
probably will) change the efficiency of the script, but not its behavior!
See also fbsql_pconnect(), ibase_pconnect(), ifx_pconnect(),
ingres_pconnect(), msql_pconnect(), mssql_pconnect(), mysql_pconnect(),
ociplogon(), odbc_pconnect(), oci_pconnect(), pfsockopen(), pg_pconnect(),
and sybase_pconnect().
----------------------------------------------------------------------
----------------------------------------------------------------------
Safe Mode
Table of Contents
* Security and Safe Mode
* Functions restricted/disabled by safe mode
The PHP safe mode is an attempt to solve the shared-server security
problem. It is architecturally incorrect to try to solve this problem at
the PHP level, but since the alternatives at the web server and OS levels
aren't very realistic, many people, especially ISP's, use safe mode for
now.
Warning
This feature has been DEPRECATED as of PHP 5.3.0. Relying on this feature
is highly discouraged.
----------------------------------------------------------------------
Security and Safe Mode
Security and Safe Mode Configuration Directives
Name Default Changeable Changelog
safe_mode "0" PHP_INI_SYSTEM Removed in
PHP 5.4.0.
Available
since PHP
safe_mode_gid "0" PHP_INI_SYSTEM 4.1.0.
Removed in
PHP 5.4.0.
Available
since PHP
safe_mode_include_dir NULL PHP_INI_SYSTEM 4.1.0.
Removed in
PHP 5.4.0.
safe_mode_exec_dir "" PHP_INI_SYSTEM Removed in
PHP 5.4.0.
safe_mode_allowed_env_vars "PHP_" PHP_INI_SYSTEM Removed in
PHP 5.4.0.
safe_mode_protected_env_vars "LD_LIBRARY_PATH" PHP_INI_SYSTEM Removed in
PHP 5.4.0.
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
safe_mode boolean
Whether to enable PHP's safe mode. If PHP is compiled with
--enable-safe-mode then defaults to On, otherwise Off.
Warning
This feature has been DEPRECATED as of PHP 5.3.0. Relying on this
feature is highly discouraged.
safe_mode_gid boolean
By default, Safe Mode does a UID compare check when opening files.
If you want to relax this to a GID compare, then turn on
safe_mode_gid. Whether to use UID (FALSE) or GID (TRUE) checking
upon file access.
safe_mode_include_dir string
UID/GID checks are bypassed when including files from this
directory and its subdirectories (directory must also be in
include_path or full path must including).
As of PHP 4.2.0, this directive can take a colon (semi-colon on
Windows) separated path in a fashion similar to the include_path
directive, rather than just a single directory. The restriction
specified is actually a prefix, not a directory name. This means
that "safe_mode_include_dir = /dir/incl" also allows access to
"/dir/include" and "/dir/incls" if they exist. When you want to
restrict access to only the specified directory, end with a slash.
For example: "safe_mode_include_dir = /dir/incl/" If the value of
this directive is empty, no files with different UID/GID can be
included in PHP 4.2.3 and as of PHP 4.3.3. In earlier versions,
all files could be included.
safe_mode_exec_dir string
If PHP is used in safe mode, system() and the other functions
executing system programs refuse to start programs that are not in
this directory. You have to use / as directory separator on all
environments including Windows.
safe_mode_allowed_env_vars string
Setting certain environment variables may be a potential security
breach. This directive contains a comma-delimited list of
prefixes. In Safe Mode, the user may only alter environment
variables whose names begin with the prefixes supplied here. By
default, users will only be able to set environment variables that
begin with PHP_ (e.g. PHP_FOO=BAR).
Note:
If this directive is empty, PHP will let the user modify ANY
environment variable!
safe_mode_protected_env_vars string
This directive contains a comma-delimited list of environment
variables that the end user won't be able to change using
putenv(). These variables will be protected even if
safe_mode_allowed_env_vars is set to allow to change them.
See also: open_basedir, disable_functions, disable_classes,
register_globals, display_errors, and log_errors.
When safe_mode is on, PHP checks to see if the owner of the current script
matches the owner of the file to be operated on by a file function or its
directory. For example:
-rw-rw-r-- 1 rasmus rasmus 33 Jul 1 19:20 script.php
-rw-r--r-- 1 root root 1116 May 26 18:01 /etc/passwd
Running script.php:
results in this error when safe mode is enabled:
Warning: SAFE MODE Restriction in effect. The script whose uid is 500 is not
allowed to access /etc/passwd owned by uid 0 in /docroot/script.php on line 2
However, there may be environments where a strict UID check is not
appropriate and a relaxed GID check is sufficient. This is supported by
means of the safe_mode_gid switch. Setting it to On performs the relaxed
GID checking, setting it to Off (the default) performs UID checking.
If instead of safe_mode, you set an open_basedir directory then all file
operations will be limited to files under the specified directory. For
example (Apache httpd.conf example):
php_admin_value open_basedir /docroot
If you run the same script.php with this open_basedir setting then this is
the result:
Warning: open_basedir restriction in effect. File is in wrong directory in
/docroot/script.php on line 2
You can also disable individual functions. Note that the disable_functions
directive can not be used outside of the php.ini file which means that you
cannot disable functions on a per-virtualhost or per-directory basis in
your httpd.conf file. If we add this to our php.ini file:
disable_functions = readfile,system
Then we get this output:
Warning: readfile() has been disabled for security reasons in
/docroot/script.php on line 2
Warning
These PHP restrictions are not valid in executed binaries, of course.
----------------------------------------------------------------------
----------------------------------------------------------------------
Functions restricted/disabled by safe mode
This is a still probably incomplete and possibly incorrect listing of the
functions limited by safe mode.
Safe mode limited functions
Function Limitations
Checks whether the files or directories being
dbmopen() operated upon have the same UID (owner) as the
script that is being executed.
Checks whether the files or directories being
dbase_open() operated upon have the same UID (owner) as the
script that is being executed.
Checks whether the files or directories being
filepro() operated upon have the same UID (owner) as the
script that is being executed.
Checks whether the files or directories being
filepro_rowcount() operated upon have the same UID (owner) as the
script that is being executed.
Checks whether the files or directories being
filepro_retrieve() operated upon have the same UID (owner) as the
script that is being executed.
ifx_* sql_safe_mode restrictions, (!= safe mode)
ingres_* sql_safe_mode restrictions, (!= safe mode)
mysql_* sql_safe_mode restrictions, (!= safe mode)
Checks whether the files or directories being
pg_lo_import() operated upon have the same UID (owner) as the
script that is being executed.
Checks whether the directory in which the script
posix_mkfifo() is operating has the same UID (owner) as the
script that is being executed.
Obeys the safe_mode_protected_env_vars and
putenv() safe_mode_allowed_env_vars ini-directives. See
also the documentation on putenv()
Checks whether the files or directories being
move_uploaded_file() operated upon have the same UID (owner) as the
script that is being executed.
Checks whether the directory in which the script
chdir() is operating has the same UID (owner) as the
script that is being executed.
dl() This function is disabled when PHP is running in
safe mode.
backtick operator This function is disabled when PHP is running in
safe mode.
shell_exec() (functional This function is disabled when PHP is running in
equivalent of backticks) safe mode.
You can only execute executables within the
safe_mode_exec_dir. For practical reasons it's
exec() currently not allowed to have .. components in
the path to the executable. escapeshellcmd() is
executed on the argument of this function.
You can only execute executables within the
safe_mode_exec_dir. For practical reasons it's
system() currently not allowed to have .. components in
the path to the executable. escapeshellcmd() is
executed on the argument of this function.
You can only execute executables within the
safe_mode_exec_dir. For practical reasons it's
passthru() currently not allowed to have .. components in
the path to the executable. escapeshellcmd() is
executed on the argument of this function.
You can only execute executables within the
safe_mode_exec_dir. For practical reasons it's
popen() currently not allowed to have .. components in
the path to the executable. escapeshellcmd() is
executed on the argument of this function.
Checks whether the directory in which the script
fopen() is operating has the same UID (owner) as the
script that is being executed.
Checks whether the directory in which the script
mkdir() is operating has the same UID (owner) as the
script that is being executed.
Checks whether the directory in which the script
rmdir() is operating has the same UID (owner) as the
script that is being executed.
Checks whether the files or directories being
operated upon have the same UID (owner) as the
rename() script that is being executed. Checks whether
the directory in which the script is operating
has the same UID (owner) as the script that is
being executed.
Checks whether the files or directories being
operated upon have the same UID (owner) as the
unlink() script that is being executed. Checks whether
the directory in which the script is operating
has the same UID (owner) as the script that is
being executed.
Checks whether the files or directories being
operated upon have the same UID (owner) as the
copy() script that is being executed. Checks whether
the directory in which the script is operating
has the same UID (owner) as the script that is
being executed. (on source and target)
Checks whether the files or directories being
chgrp() operated upon have the same UID (owner) as the
script that is being executed.
Checks whether the files or directories being
chown() operated upon have the same UID (owner) as the
script that is being executed.
Checks whether the files or directories being
chmod() operated upon have the same UID (owner) as the
script that is being executed. In addition, you
cannot set the SUID, SGID and sticky bits
Checks whether the files or directories being
operated upon have the same UID (owner) as the
touch() script that is being executed. Checks whether
the directory in which the script is operating
has the same UID (owner) as the script that is
being executed.
Checks whether the files or directories being
operated upon have the same UID (owner) as the
script that is being executed. Checks whether
symlink() the directory in which the script is operating
has the same UID (owner) as the script that is
being executed. (note: only the target is
checked)
Checks whether the files or directories being
operated upon have the same UID (owner) as the
script that is being executed. Checks whether
link() the directory in which the script is operating
has the same UID (owner) as the script that is
being executed. (note: only the target is
checked)
In safe mode, headers beginning with
apache_request_headers() authorization (case-insensitive) will not be
returned.
In safe mode, the uid of the script is added to
header() the realm part of the WWW-Authenticate header if
you set this header (used for HTTP
Authentication).
In safe mode, the variables PHP_AUTH_USER,
PHP_AUTH_PW, and AUTH_TYPE are not available in
PHP_AUTH variables $_SERVER. Regardless, you can still use
REMOTE_USER for the USER. (note: only affected
since PHP 4.3.0)
Checks whether the files or directories being
operated upon have the same UID (owner) as the
highlight_file(), script that is being executed. Checks whether
show_source() the directory in which the script is operating
has the same UID (owner) as the script that is
being executed. (note: only affected since PHP
4.2.1)
Checks whether the files or directories being
operated upon have the same UID (owner) as the
script that is being executed. Checks whether
parse_ini_file() the directory in which the script is operating
has the same UID (owner) as the script that is
being executed. (note: only affected since PHP
4.2.1)
set_time_limit() Has no effect when PHP is running in safe mode.
max_execution_time Has no effect when PHP is running in safe mode.
mail() In safe mode, the fifth parameter is disabled.
(note: only affected since PHP 4.2.3)
The owner of a script must be the same as owner
session_start() of a session.save_path directory if the default
files session.save_handler is used.
Checks whether the files or directories being
operated upon have the same UID (owner) as the
All filesystem and stream script that is being executed. Checks whether
functions. the directory in which the script is operating
has the same UID (owner) as the script that is
being executed. (see the safe_mode_include_dir
php.ini option.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Using PHP from the command line
Table of Contents
* Introduction
* Differences to other SAPIs
* Options
* Usage
* I/O streams
* Interactive shell
* Built-in web server
----------------------------------------------------------------------
Introduction
PHP supports a CLI SAPI as of PHP 4.3.0. The main focus of this SAPI is
for developing shell applications with PHP. There are quite a few
differences between the CLI SAPI and other SAPIs which are explained in
this chapter. It is worth mentioning that CLI and CGI are different SAPIs
although they do share many of the same behaviors.
The CLI SAPI is enabled by default using --enable-cli , but may be
disabled using the --disable-cli option when running ./configure.
The name, location and existence of the CLI/CGI binaries will differ
depending on how PHP is installed on your system. By default when
executing make, both the CGI and CLI are built and placed as
sapi/cgi/php-cgi and sapi/cli/php respectively, in your PHP source
directory. You will note that both are named php. What happens during make
install depends on your configure line. If a module SAPI is chosen during
configure, such as apxs, or the --disable-cgi option is used, the CLI is
copied to {PREFIX}/bin/php during make install otherwise the CGI is placed
there. So, for example, if --with-apxs is in your configure line then the
CLI is copied to {PREFIX}/bin/php during make install. If you want to
override the installation of the CGI binary, use make install-cli after
make install. Alternatively you can specify --disable-cgi in your
configure line.
Note:
Because both --enable-cli and --enable-cgi are enabled by default,
simply having --enable-cli in your configure line does not necessarily
mean the CLI will be copied as {PREFIX}/bin/php during make install.
As of PHP 5, the CLI binary is distributed in the main folder as php.exe
on Windows. The CGI version is distributed as php-cgi.exe. Additionally, a
php-win.exe is distributed if PHP is configured using --enable-cli-win32 .
This does the same as the CLI version, except that it doesn't output
anything and thus provides no console.
Note: What SAPI do I have?
From a shell, typing php -v will tell you whether php is CGI or CLI. See
also the function php_sapi_name() and the constant PHP_SAPI.
Note:
A Unix manual page is available by typing man php in the shell
environment.
----------------------------------------------------------------------
----------------------------------------------------------------------
Differences to other SAPIs
Remarkable differences of the CLI SAPI compared to other SAPIs:
* Unlike the CGI SAPI, no headers are written to the output.
Though the CGI SAPI provides a way to suppress HTTP headers, there's
no equivalent switch to enable them in the CLI SAPI.
CLI is started up in quiet mode by default, though the -q and
--no-header switches are kept for compatibility so that it is possible
to use older CGI scripts.
It does not change the working directory to that of the script. (-C
and --no-chdir switches kept for compatibility)
Plain text error messages (no HTML formatting).
* There are certain php.ini directives which are overridden by the CLI
SAPI because they do not make sense in shell environments:
Overridden php.ini directives
Directive CLI SAPI default Comment
value
Defaults to FALSE, as it can be
quite hard to read error messages
html_errors FALSE in the shell enviroment when they
are cluttered up with
uninterpreted HTML tags.
In a shell environment, it is
usually desirable for output, such
as from print(), echo() and
friends, to be displayed
implicit_flush TRUE immediately, and not held in a
buffer. Nonetheless, it is still
possible to use output buffering
to defer or manipulate standard
output.
PHP in a shell environment tends
to be used for a much more diverse
range of purposes than typical
max_execution_time 0 (unlimited) Web-based scripts, and as these
can be very long-running, the
maximum execution time is set to
unlimited.
Setting this to TRUE means that
scripts executed via the CLI SAPI
always have access to argc (number
of arguments passed to the
application) and argv (array of
the actual arguments).
register_argc_argv TRUE
The PHP variables $argc and $argv
are automatically set to the
appropriate values when using the
CLI SAPI. These values can also be
found in the $_SERVER array, for
example: $_SERVER['argv'].
Although the php.ini setting is
output_buffering FALSE hardcoded to FALSE, the Output
buffering functions are available.
max_input_time FALSE The PHP CLI doesn't not support
GET, POST or file uploads.
Note:
These directives cannot be initialized with another value from the
configuration file php.ini or a custom one (if specified). This
limitation is because the values are applied after all configuration
files have been parsed. However, their values can be changed during
runtime (although this is not sensible for all of them, such as
register_argc_argv).
Note:
It is recommended to set ignore_user_abort for command line scripts.
See ignore_user_abort() for more information.
* To ease working in the shell environment, a number of constants are
defined for I/O streams .
* The CLI SAPI does not change the current directory to the directory of
the executed script.
Example #1 Example showing the difference to the CGI SAPI:
When using the CGI version, the output is:
$ pwd
/tmp
$ php -q another_directory/test.php
/tmp/another_directory
This clearly shows that PHP changes its current directory to the one
of the executed script.
Using the CLI SAPI yields:
$ pwd
/tmp
$ php -f another_directory/test.php
/tmp
This allows greater flexibility when writing shell tools in PHP.
Note:
The CGI SAPI supports this CLI SAPI behaviour by means of the -C
switch when run from the command line.
----------------------------------------------------------------------
----------------------------------------------------------------------
Command line options
The list of command line options provided by the PHP binary can be queried
at any time by running PHP with the -h switch:
Usage: php [options] [-f] [--] [args...]
php [options] -r [--] [args...]
php [options] [-B ] -R [-E ] [--] [args...]
php [options] [-B ] -F [-E ] [--] [args...]
php [options] -- [args...]
php [options] -a
-a Run interactively
-c | Look for php.ini file in this directory
-n No php.ini file will be used
-d foo[=bar] Define INI entry foo with value 'bar'
-e Generate extended information for debugger/profiler
-f Parse and execute .
-h This help
-i PHP information
-l Syntax check only (lint)
-m Show compiled in modules
-r Run PHP without using script tags ..?>
-B Run PHP before processing input lines
-R Run PHP for every input line
-F Parse and execute for every input line
-E Run PHP after processing all input lines
-H Hide any passed arguments from external tools.
-s Output HTML syntax highlighted source.
-v Version number
-w Output source with stripped comments and whitespace.
-z Load Zend extension .
args... Arguments passed to script. Use -- args when first argument
starts with - or script is read from stdin
--ini Show configuration file names
--rf Show information about function .
--rc Show information about class .
--re Show information about extension .
--rz Show information about Zend extension .
--ri Show configuration for extension .
Command line options
Option Long Option Description
-a --interactive Run PHP interactively. For more information, see the Interactive shell section.
-b --bindpath Bind Path for external FASTCGI Server mode (CGI only).
-C --no-chdir Do not chdir to the script's directory (CGI only).
-q --no-header Quiet-mode. Suppress HTTP header output (CGI only).
-T --timing Measure execution time of script repeated count times (CGI only).
Specifies either a directory in which to look for php.ini, or a custom INI file (which does
not need to be named php.ini), e.g.:
-c --php-ini $ php -c /custom/directory/ my_script.php
$ php -c /custom/directory/custom-file.ini my_script.php
If this option is not specified, php.ini is searched for in the default locations.
-n --no-php-ini Ignore php.ini completely.
Set a custom value for any of the configuration directives allowed in php.ini. The syntax is:
-d configuration_directive[=value]
# Omitting the value part will set the given configuration directive to "1"
$ php -d max_execution_time
-r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(1) "1"
# Passing an empty value part will set the configuration directive to ""
-d --define php -d max_execution_time=
-r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(0) ""
# The configuration directive will be set to anything passed after the '=' character
$ php -d max_execution_time=20
-r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(2) "20"
$ php
-d max_execution_time=doesntmakesense
-r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(15) "doesntmakesense"
-e --profile-info Activate the extended information mode, to be used by a debugger/profiler.
Parse and execute the specified file. The -f is optional and may be omitted - providing just
the filename to execute is sufficient.
-f --file Note:
To pass arguments to a script, the first argument must be --, otherwise PHP will interpret
them as PHP options.
-h and --help and --usage Output a list of command line options with one line descriptions of what they do.
-?
Calls phpinfo(), and prints out the results. If PHP is not working correctly, it is advisable
-i --info to use the command php -i and see whether any error messages are printed out before or in
place of the information tables. Beware that when using the CGI mode the output is in HTML and
therefore very large.
Provides a convenient way to perform only a syntax check on the given PHP code. On success,
the text No syntax errors detected in is written to standard output and the shell
return code is 0. On failure, the text Errors parsing in addition to the internal
parser error message is written to standard output and the shell return code is set to -1.
-l --syntax-check This option won't find fatal errors (like undefined functions). Use the -f to test for fatal
errors too.
Note:
This option does not work together with the -r option.
Example #1 Printing built in (and loaded) PHP and Zend modules
$ php -m
[PHP Modules]
xml
tokenizer
standard
-m --modules session
posix
pcre
overload
mysql
mbstring
ctype
[Zend Modules]
Allows execution of PHP included directly on the command line. The PHP start and end tags
() are not needed and will cause a parse error if present.
Note:
Care must be taken when using this form of PHP not to collide with command line variable
substitution done by the shell.
Example #2 Getting a syntax error when using double quotes
$ php -r "$foo = get_defined_constants();"
PHP Parse error: syntax error, unexpected '=' in Command line code on line 1
Parse error: syntax error, unexpected '=' in Command line code on line 1
The problem here is that sh/bash performs variable substitution even when using double
quotes ". Since the variable $foo is unlikely to be defined, it expands to nothing which
results in the code passed to PHP for execution actually reading:
$ php -r " = get_defined_constants();"
The correct way would be to use single quotes '. Variables in single-quoted strings are not
expanded by sh/bash.
Example #3 Using single quotes to prevent the shell's variable substitution
-r --run
$ php -r '$foo = get_defined_constants(); var_dump($foo);'
array(370) {
["E_ERROR"]=>
int(1)
["E_WARNING"]=>
int(2)
["E_PARSE"]=>
int(4)
["E_NOTICE"]=>
int(8)
["E_CORE_ERROR"]=>
[...]
If using a shell other than sh/bash, further issues might be experienced - if appropriate, a
bug report should be opened at >> http://bugs.php.net/. It is still easy to run into trouble
when trying to use variables (shell or PHP) in commnad-line code, or using backslashes for
escaping, so take great care when doing so. You have been warned!
Note:
-r is available in the CLI SAPI, but not in the CGI SAPI.
Note:
This option is only intended for very basic code, so some configuration directives (such as
auto_prepend_file and auto_append_file) are ignored in this mode.
-B --process-begin PHP code to execute before processing stdin. Added in PHP 5.
PHP code to execute for every input line. Added in PHP 5.
-R --process-code
There are two special variables available in this mode: $argn and $argi. $argn will contain
the line PHP is processing at that moment, while $argi will contain the line number.
-F --process-file PHP file to execute for every input line. Added in PHP 5.
PHP code to execute after processing the input. Added in PHP 5.
-E --process-end Example #4 Using the -B , -R and -E options to count the number of lines of a project.
$ find my_proj | php -B '$l=0;' -R '$l += count(@file($argn));' -E 'echo "Total Lines: $l\n";'
Total Lines: 37328
Display colour syntax highlighted source.
This option uses the internal mechanism to parse the file and writes an HTML highlighted
--syntax-highlight version of it to standard output. Note that all it does is generate a block of [...]
-s and HTML tags, no HTML headers.
--syntax-highlighting
Note:
This option does not work together with the -r option.
Example #5 Using -v to get the SAPI name and the version of PHP and Zend
-v --version $ php -v
PHP 5.3.1 (cli) (built: Dec 11 2009 19:55:07)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies
Display source with comments and whitespace stripped.
-w --strip Note:
This option does not work together with the -r option.
Load Zend extension. If only a filename is given, PHP tries to load this extension from the
current default library path on your system (usually /etc/ld.so.conf on Linux systems, for
-z --zend-extension example). Passing a filename with an absolute path will not use the system's library search
path. A relative filename including directory information will tell PHP to try loading the
extension relative to the current directory.
Show configuration file names and scanned directories. Available as of PHP 5.2.3.
Example #6 --ini example
--ini $ php --ini
Configuration File (php.ini) Path: /usr/dev/php/5.2/lib
Loaded Configuration File: /usr/dev/php/5.2/lib/php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed: (none)
Show information about the given function or class method (e.g. number and name of the
parameters). Available as of PHP 5.1.2.
This option is only available if PHP was compiled with Reflection support.
Example #7 basic --rf usage
--rf --rfunction $ php --rf var_dump
Function [ public function var_dump ] {
- Parameters [2] {
Parameter #0 [ $var ]
Parameter #1 [ $... ]
}
}
Show information about the given class (list of constants, properties and methods). Available
as of PHP 5.1.2.
This option is only available if PHP was compiled with Reflection support.
Example #8 --rc example
$ php --rc Directory
Class [ class Directory ] {
- Constants [0] {
}
- Static properties [0] {
}
--rc --rclass - Static methods [0] {
}
- Properties [0] {
}
- Methods [3] {
Method [ public method close ] {
}
Method [ public method rewind ] {
}
Method [ public method read ] {
}
}
}
Show information about the given extension (list of php.ini options, defined functions,
constants and classes). Available as of PHP 5.1.2.
This option is only available if PHP was compiled with Reflection support.
Example #9 --re example
$ php --re json
--re --rextension Extension [ extension #19 json version 1.2.1 ] {
- Functions {
Function [ function json_encode ] {
}
Function [ function json_decode ] {
}
}
}
--rz --rzendextension Show the configuration information for the given Zend extension (the same information that is
returned by phpinfo()). Available as of PHP 5.4.0.
Show the configuration information for the given extension (the same information that is
returned by phpinfo()). Available as of PHP 5.2.2. The core configuration information is
available using "main" as extension name.
Example #10 --ri example
$ php --ri date
date
--ri --rextinfo date/time support => enabled
"Olson" Timezone Database Version => 2009.20
Timezone Database => internal
Default timezone => Europe/Oslo
Directive => Local Value => Master Value
date.timezone => Europe/Oslo => Europe/Oslo
date.default_latitude => 59.930972 => 59.930972
date.default_longitude => 10.776699 => 10.776699
date.sunset_zenith => 90.583333 => 90.583333
date.sunrise_zenith => 90.583333 => 90.583333
Note:
Options -rBRFEH, --ini and --r[fcezi] are available only in CLI.
----------------------------------------------------------------------
----------------------------------------------------------------------
Executing PHP files
There are three different ways of supplying the CLI SAPI with PHP code to
be executed:
1. Tell PHP to execute a certain file.
$ php my_script.php
$ php -f my_script.php
Both ways (whether using the -f switch or not) execute the file
my_script.php. Note that there is no restriction on which files can be
executed; in particular, the filename is not required have a .php
extension.
Note:
If arguments need to be passed to the script when using -f , the
first argument must be --.
2. Pass the PHP code to execute directly on the command line.
$ php -r 'print_r(get_defined_constants());'
Special care has to be taken with regard to shell variable
substitution and usage of quotes.
Note:
Read the example carefully: there are no beginning or ending tags!
The -r switch simply does not need them, and using them will lead to
a parse error.
3. Provide the PHP code to execute via standard input (stdin).
This gives the powerful ability to create PHP code dynamically and
feed it to the binary, as shown in this (fictional) example:
$ some_application | some_filter | php | sort -u > final_output.txt
You cannot combine any of the three ways to execute code.
As with every shell application, the PHP binary accepts a number of
arguments; however, the PHP script can also receive further arguments. The
number of arguments that can be passed to your script is not limited by
PHP (and although the shell has a limit to the number of characters which
can be passed, this is not in general likely to be hit). The arguments
passed to the script are available in the global array $argv. The first
index (zero) always contains the name of the script as called from the
command line. Note that, if the code is executed in-line using the command
line switch -r , the value of $argv[0] will be just a dash (-). The same
is true if the code is executed via a pipe from STDIN.
A second global variable, $argc, contains the number of elements in the
$argv array (not the number of arguments passed to the script).
As long as the arguments to be passed to the script do not start with the
- character, there's nothing special to watch out for. Passing an argument
to the script which starts with a - will cause trouble because the PHP
interpreter thinks it has to handle it itself, even before executing the
script. To prevent this, use the argument list separator --. After this
separator has been parsed by PHP, every following argument is passed
untouched to the script.
# This will not execute the given code but will show the PHP usage
$ php -r 'var_dump($argv);' -h
Usage: php [options] [-f] [args...]
[...]
# This will pass the '-h' argument to the script and prevent PHP from showing its usage
$ php -r 'var_dump($argv);' -- -h
array(2) {
[0]=>
string(1) "-"
[1]=>
string(2) "-h"
}
However, on Unix systems there's another way of using PHP for shell
scripting: make the first line of the script start with #!/usr/bin/php (or
whatever the path to your PHP CLI binary is if different). The rest of the
file should contain normal PHP code within the usual PHP starting and end
tags. Once the execution attributes of the file are set appropriately
(e.g. chmod +x test), the script can be executed like any other shell or
perl script:
Example #1 Execute PHP script as shell script
#!/usr/bin/php
Assuming this file is named test in the current directory, it is now
possible to do the following:
$ chmod +x test
$ ./test -h -- foo
array(4) {
[0]=>
string(6) "./test"
[1]=>
string(2) "-h"
[2]=>
string(2) "--"
[3]=>
string(3) "foo"
}
As can be seen, in this case no special care needs to be taken when
passing parameters starting with -.
The PHP executable can be used to run PHP scripts absolutely independent
of the web server. On Unix systems, the special #! (or "shebang") first
line should be added to PHP scripts so that the system can automatically
tell which program should run the script. On Windows platforms, it's
possible to associate php.exe with the double click option of the .php
extension, or a batch file can be created to run scripts through PHP. The
special shebang first line for Unix does no harm on Windows (as it's
formatted as a PHP comment), so cross platform programs can be written by
including it. A simple example of writing a command line PHP program is
shown below.
Example #2 Script intended to be run from command line (script.php)
#!/usr/bin/php
This is a command line PHP script with one option.
Usage:
can be some word you would like
to print out. With the --help, -help, -h,
or -? options, you can get this help.
The script above includes the Unix shebang first line to indicate that
this file should be run by PHP. We are working with a CLI version here, so
no HTTP headers will be output.
The program first checks that there is the required one argument (in
addition to the script name, which is also counted). If not, or if the
argument was --help , -help , -h or -? , the help message is printed out,
using $argv[0] to dynamically print the script name as typed on the
command line. Otherwise, the argument is echoed out exactly as received.
To run the above script on Unix, it must be made executable, and called
simply as script.php echothis or script.php -h. On Windows, a batch file
similar to the following can be created for this task:
Example #3 Batch file to run a command line PHP script (script.bat)
@echo OFF
"C:\php\php.exe" script.php %*
Assuming the above program is named script.php, and the CLI php.exe is in
C:\php\php.exe, this batch file will run it, passing on all appended
options: script.bat echothis or script.bat -h.
See also the Readline extension documentation for more functions which can
be used to enhance command line applications in PHP.
On Windows, PHP can be configured to run without the need to supply the
C:\php\php.exe or the .php extension, as described in Command Line PHP on
Microsoft Windows.
----------------------------------------------------------------------
----------------------------------------------------------------------
Input/output streams
The CLI SAPI defines a few constants for I/O streams to make programming
for the command line a bit easier.
CLI specific Constants
Constant Description
An already opened stream to stdin. This saves opening it with
STDIN If you want to read single line from stdin, you can use
An already opened stream to stdout. This saves opening it with
STDOUT
An already opened stream to stderr. This saves opening it with
STDERR
Given the above, you don't need to open e.g. a stream for stderr yourself
but simply use the constant instead of the stream resource:
php -r 'fwrite(STDERR, "stderr\n");'
You do not need to explicitly close these streams, as they are closed
automatically by PHP when your script ends.
Note:
These constants are not available in case of reading PHP script from
stdin.
----------------------------------------------------------------------
----------------------------------------------------------------------
Interactive shell
As of PHP 5.1.0, the CLI SAPI provides an interactive shell using the -a
option if PHP is compiled with the --with-readline option.
Using the interactive shell you are able to type PHP code and have it
executed directly.
Example #1 Executing code using the interactive shell
$ php -a
Interactive shell
php > echo 5+8;
13
php > function addTwo($n)
php > {
php { return $n + 2;
php { }
php > var_dump(addtwo(2));
int(4)
php >
The interactive shell also features tab completion for functions,
constants, class names, variables, static method calls and class
constants.
Example #2 Tab completion
Pressing the tab key twice when there are multiple possible completions
will result in a list of these completions:
php > strp[TAB][TAB]
strpbrk strpos strptime
php > strp
When there is only one possible completion, pressing tab once will
complete the rest on the same line:
php > strpt[TAB]ime(
Completion will also work for names that have been defined during the
current interactive shell session:
php > $fooThisIsAReallyLongVariableName = 42;
php > $foo[TAB]ThisIsAReallyLongVariableName
The interactive shell stores your history which can be accessed using the
up and down keys. The history is saved in the ~/.php_history file.
As of PHP 5.4.0, the CLI SAPI provides the php.ini settings cli.pager and
cli.prompt. The cli.pager setting allows an external program (such as
less) to act as a pager for the output instead of being displayed directly
on the screen. The cli.prompt setting makes it possible to change the php
> prompt.
In PHP 5.4.0 it was also made possible to set php.ini settings in the
interactive shell using a shorthand notation.
Example #3 Setting php.ini settings in the interactive shell
The cli.prompt setting:
php > #cli.prompt=hello world :>
hello world :>
Using backticks it is possible to have PHP code executed in the prompt:
php > #cli.prompt=`echo date('H:i:s');` php >
15:49:35 php > echo 'hi';
hi
15:49:43 php > sleep(2);
15:49:45 php >
Setting the pager to less:
php > #cli.pager=less
php > phpinfo();
(output displayed in less)
php >
The cli.prompt setting supports a few escape sequences:
cli.prompt escape sequences
Sequence Description
\e Used for adding colors to the prompt. An example could be
\e[032m\v \e[031m\b \e[34m\> \e[0m
\v The PHP version.
Indicates which block PHP is in. For instance /* to indicate
\b being inside a multi-line comment. The outer scope is denoted by
php.
Indicates the prompt character. By default this is >, but changes
\> when the shell is inside an unterminated block or string.
Possible characters are: ' " { ( >
Note:
Files included through auto_prepend_file and auto_append_file are parsed
in this mode but with some restrictions - e.g. functions have to be
defined before called.
Note:
Autoloading is not available if using PHP in CLI interactive mode.
----------------------------------------------------------------------
----------------------------------------------------------------------
Built-in web server
As of PHP 5.4.0, the CLI SAPI provides a built-in web server.
This web server is designed for developmental purposes only, and should
not be used in production.
URI requests are served from the current working directory where PHP was
started, unless the -t option is used to specify an explicit document
root.
If a URI request does not specify a file, then either index.html or
index.php in the given directory are returned. If neither file exists,
then a 404 response code is returned.
If a PHP file is given on the command line when the web server is started
it is treated as a "router" script for the web server. The script is run
at the start of each HTTP request. If this script returns FALSE, then the
requested resource is returned as-is. Otherwise the script's output is
returned to the browser.
Example #1 Starting the web server
$ php -S localhost:8000
The terminal will show:
PHP Development Server is listening on localhost:8000 in /home/mydir ... Press Ctrl-C to quit.
After URI requests for http://localhost:8000/ and
http://localhost:8000/myscript.html the terminal will show something
similar to:
PHP Development Server is listening on localhost:8000 in /home/mydir ... Press Ctrl-C to quit.
[Fri Jul 1 06:29:04 2011] ::1:63530: /
[Fri Jul 1 06:29:10 2011] ::1:63532: /index.php
[Fri Jul 1 06:29:11 2011] ::1:63533: /myscript.html
Example #2 Starting with a specific document root directory
$ php -S localhost:8000 -t foo/
The terminal will show:
PHP Development Server is listening on localhost:8000 in /home/mydir/foo ... Press Ctrl-C to quit.
Example #3 Using a Router Script
Requests for images will display them, but requests for HTML files will
display "Welcome to PHP"
Welcome to PHP";
}
?>
$ php -S localhost:8000 router.php
After several URI requests the terminal will show something similar to:
PHP Development Server is listening on localhost:8000 in /home/mydir ... Press Ctrl-C to quit.
[Fri Jul 1 06:29:04 2011] ::1:63530: /
[Fri Jul 1 06:29:10 2011] ::1:63532: /mylogo.jpg
[Fri Jul 1 06:29:11 2011] ::1:63533: /abc.html
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Garbage Collection
Table of Contents
* Reference Counting Basics
* Collecting Cycles
* Performance Considerations
This section explains the merits of the new Garbage Collection (also known
as GC) mechanism that is part of PHP 5.3.
----------------------------------------------------------------------
Reference Counting Basics
A PHP variable is stored in a container called a "zval". A zval container
contains, besides the variable's type and value, two additional bits of
information. The first is called "is_ref" and is a boolean value
indicating whether or not the variable is part of a "reference set". With
this bit, PHP's engine knows how to differentiate between normal variables
and references. Since PHP allows user-land references, as created by the &
operator, a zval container also has an internal reference counting
mechanism to optimize memory usage. This second piece of additional
information, called "refcount", contains how many variable names (also
called symbols) point to this one zval container. All symbols are stored
in a symbol table, of which there is one per scope. There is a scope for
the main script (i.e., the one requested through the browser), as well as
one for every function or method.
A zval container is created when a new variable is created with a constant
value, such as:
Example #1 Creating a new zval container
In this case, the new symbol name, a, is created in the current scope, and
a new variable container is created with the type string and the value new
string. The "is_ref" bit is by default set to FALSE because no user-land
reference has been created. The "refcount" is set to 1 as there is only
one symbol that makes use of this variable container. Note that if
"refcount" is 1, "is_ref" is always FALSE. If you have >> Xdebug
installed, you can display this information by calling
xdebug_debug_zval().
Example #2 Displaying zval information
The above example will output:
a: (refcount=1, is_ref=0)='new string'
Assigning this variable to another variable name will increase the
refcount.
Example #3 Increasing refcount of a zval
The above example will output:
a: (refcount=2, is_ref=0)='new string'
The refcount is 2 here, because the same variable container is linked with
both a and b. PHP is smart enough not to copy the actual variable
container when it is not necessary. Variable containers get destroyed when
the "refcount" reaches zero. The "refcount" gets decreased by one when any
symbol linked to the variable container leaves the scope (e.g. when the
function ends) or when unset() is called on a symbol. The following
example shows this:
Example #4 Decreasing zval refcount
The above example will output:
a: (refcount=3, is_ref=0)='new string'
a: (refcount=1, is_ref=0)='new string'
If we now call unset($a);, the variable container, including the type and
value, will be removed from memory.
Compound Types
Things get a tad more complex with compound types such as arrays and
objects. Instead of a scalar value, arrays and objects store their
properties in a symbol table of their own. This means that the following
example creates three zval containers:
Example #5 Creating a array zval
'life', 'number' => 42 );
xdebug_debug_zval( 'a' );
?>
The above example will output something similar to:
a: (refcount=1, is_ref=0)=array (
'meaning' => (refcount=1, is_ref=0)='life',
'number' => (refcount=1, is_ref=0)=42
)
Or graphically
Zvals for a simple array
The three zval containers are: a, meaning, and number. Similar rules apply
for increasing and decreasing "refcounts". Below, we add another element
to the array, and set its value to the contents of an already existing
element:
Example #6 Adding already existing element to an array
'life', 'number' => 42 );
$a['life'] = $a['meaning'];
xdebug_debug_zval( 'a' );
?>
The above example will output something similar to:
a: (refcount=1, is_ref=0)=array (
'meaning' => (refcount=2, is_ref=0)='life',
'number' => (refcount=1, is_ref=0)=42,
'life' => (refcount=2, is_ref=0)='life'
)
Or graphically
Zvals for a simple array with a reference
From the above Xdebug output, we see that both the old and new array
elements now point to a zval container whose "refcount" is 2. Although
Xdebug's output shows two zval containers with value 'life', they are the
same one. The xdebug_debug_zval() function does not show this, but you
could see it by also displaying the memory pointer.
Removing an element from the array is like removing a symbol from a scope.
By doing so, the "refcount" of a container that an array element points to
is decreased. Again, when the "refcount" reaches zero, the variable
container is removed from memory. Again, an example to show this:
Example #7 Removing an element from an array
'life', 'number' => 42 );
$a['life'] = $a['meaning'];
unset( $a['meaning'], $a['number'] );
xdebug_debug_zval( 'a' );
?>
The above example will output something similar to:
a: (refcount=1, is_ref=0)=array (
'life' => (refcount=1, is_ref=0)='life'
)
Now, things get interesting if we add the array itself as an element of
the array, which we do in the next example, in which we also sneak in a
reference operator, since otherwise PHP would create a copy:
Example #8 Adding the array itself as an element of it self
The above example will output something similar to:
a: (refcount=2, is_ref=1)=array (
0 => (refcount=1, is_ref=0)='one',
1 => (refcount=2, is_ref=1)=...
)
Or graphically
Zvals for an array with a circular reference
You can see that the array variable (a) as well as the second element (1)
now point to a variable container that has a "refcount" of 2. The "..." in
the display above shows that there is recursion involved, which, of
course, in this case means that the "..." points back to the original
array.
Just like before, unsetting a variable removes the symbol, and the
reference count of the variable container it points to is decreased by
one. So, if we unset variable $a after running the above code, the
reference count of the variable container that $a and element "1" point to
gets decreased by one, from "2" to "1". This can be represented as:
Example #9 Unsetting $a
(refcount=1, is_ref=1)=array (
0 => (refcount=1, is_ref=0)='one',
1 => (refcount=1, is_ref=1)=...
)
Or graphically
Zvals after removal of array with a circular reference demonstrating the
memory leak
Cleanup Problems
Although there is no longer a symbol in any scope pointing to this
structure, it cannot be cleaned up because the array element "1" still
points to this same array. Because there is no external symbol pointing to
it, there is no way for a user to clean up this structure; thus you get a
memory leak. Fortunately, PHP will clean up this data structure at the end
of the request, but before then, this is taking up valuable space in
memory. This situation happens often if you're implementing parsing
algorithms or other things where you have a child point back at a "parent"
element. The same situation can also happen with objects of course, where
it actually is more likely to occur, as objects are always implicitly used
by reference.
This might not be a problem if this only happens once or twice, but if
there are thousands, or even millions, of these memory losses, this
obviously starts being a problem. This is especially problematic in long
running scripts, such as daemons where the request basically never ends,
or in large sets of unit tests. The latter caused problems while running
the unit tests for the Template component of the eZ Components library. In
some cases, it would require over 2 GB of memory, which the test server
didn't quite have.
----------------------------------------------------------------------
----------------------------------------------------------------------
Collecting Cycles
Traditionally, reference counting memory mechanisms, such as that used
previously by PHP, fail to address circular reference memory leaks. As of
5.3.0 PHP however implements the synchronous algorithm from the
>> Concurrent Cycle Collection in Reference Counted Systems paper which
addresses that issue.
A full explanation of how the algorithm works would be slightly beyond the
scope of this section, but the basics are explained here. First of all, we
have to establish a few ground rules. If a refcount is increased, it's
still in use and therefore, not garbage. If the refcount is decreased and
hits zero, the zval can be freed. This means that garbage cycles can only
be created when a refcount argument is decreased to a non-zero value.
Secondly, in a garbage cycle, it is possible to discover which parts are
garbage by checking whether it is possible to decrease their refcount by
one, and then checking which of the zvals have a refcount of zero.
Garbage collection algorithm
To avoid having to call the checking of garbage cycles with every possible
decrease of a refcount, the algorithm instead puts all possible roots
(zvals) in the "root buffer" (marking them "purple"). It also makes sure
that each possible garbage root ends up in the buffer only once. Only when
the root buffer is full does the collection mechanism start for all the
different zvals inside. See step A in the figure above.
In step B, the algorithm runs a depth-first search on all possible roots
to decrease by one the refcounts of each zval it finds, making sure not to
decrease a refcount on the same zval twice (by marking them as "grey"). In
step C, the algorithm again runs a depth-first search from each root node,
to check the refcount of each zval again. If it finds that the refcount is
zero, the zval is marked "white" (blue in the figure). If it's larger than
zero, it reverts the decreasing of the refcount by one with a depth-first
search from that point on, and they are marked "black" again. In the last
step (D), the algorithm walks over the root buffer removing the zval roots
from there, and meanwhile, checks which zvals have been marked "white" in
the previous step. Every zval marked as "white" will be freed.
Now that you have a basic understanding of how the algorithm works, we
will look back at how this integrates with PHP. By default, PHP's garbage
collector is turned on. There is, however, a php.ini setting that allows
you to change this: zend.enable_gc .
When the garbage collector is turned on, the cycle-finding algorithm as
described above is executed whenever the root buffer runs full. The root
buffer has a fixed size of 10,000 possible roots (although you can alter
this by changing the GC_ROOT_BUFFER_MAX_ENTRIES constant in Zend/zend_gc.c
in the PHP source code, and re-compiling PHP). When the garbage collector
is turned off, the cycle-finding algorithm will never run. However,
possible roots will always be recorded in the root buffer, no matter
whether the garbage collection mechanism has been activated with this
configuration setting.
If the root buffer becomes full with possible roots while the garbage
collection mechanism is turned off, further possible roots will simply not
be recorded. Those possible roots that are not recorded will never be
analyzed by the algorithm. If they were part of a circular reference
cycle, they would never be cleaned up and would create a memory leak.
The reason why possible roots are recorded even if the mechanism has been
disabled is because it's faster to record possible roots than to have to
check whether the mechanism is turned on every time a possible root could
be found. The garbage collection and analysis mechanism itself, however,
can take a considerable amount of time.
Besides changing the zend.enable_gc configuration setting, it is also
possible to turn the garbage collecting mechanism on and off by calling
gc_enable() or gc_disable() respectively. Calling those functions has the
same effect as turning on or off the mechanism with the configuration
setting. It is also possible to force the collection of cycles even if the
possible root buffer is not full yet. For this, you can use the
gc_collect_cycles() function. This function will return how many cycles
were collected by the algorithm.
The rationale behind the ability to turn the mechanism on and off, and to
initiate cycle collection yourself, is that some parts of your application
could be highly time-sensitive. In those cases, you might not want the
garbage collection mechanism to kick in. Of course, by turning off the
garbage collection for certain parts of your application, you do risk
creating memory leaks because some possible roots might not fit into the
limited root buffer. Therefore, it is probably wise to call
gc_collect_cycles() just before you call gc_disable() to free up the
memory that could be lost through possible roots that are already recorded
in the root buffer. This then leaves an empty buffer so that there is more
space for storing possible roots while the cycle collecting mechanism is
turned off.
----------------------------------------------------------------------
----------------------------------------------------------------------
Performance Considerations
We have already mentioned in the previous section that simply collecting
the possible roots had a very tiny performance impact, but this is when
you compare PHP 5.2 against PHP 5.3. Although the recording of possible
roots compared to not recording them at all, like in PHP 5.2, is slower,
other changes to the PHP runtime in PHP 5.3 prevented this particular
performance loss from even showing.
There are two major areas in which performance is affected. The first area
is reduced memory usage, and the second area is run-time delay when the
garbage collection mechanism performs its memory cleanups. We will look at
both of those issues.
Reduced Memory Usage
First of all, the whole reason for implementing the garbage collection
mechanism is to reduce memory usage by cleaning up circular-referenced
variables as soon as the prerequisites are fulfilled. In PHP's
implementation, this happens as soon as the root-buffer is full, or when
the function gc_collect_cycles() is called. In the graph below, we display
the memory usage of the script below, in both PHP 5.2 and PHP 5.3,
excluding the base memory that PHP itself uses when starting up.
Example #1 Memory usage example
self = $a;
if ( $i % 500 === 0 )
{
echo sprintf( '%8d: ', $i ), memory_get_usage() - $baseMemory, "\n";
}
}
?>
Comparison of memory usage between PHP 5.2 and PHP 5.3
In this very academic example, we are creating an object in which a
property is set to point back to the object itself. When the $a variable
in the script is re-assigned in the next iteration of the loop, a memory
leak would typically occur. In this case, two zval-containers are leaked
(the object zval, and the property zval), but only one possible root is
found: the variable that was unset. When the root-buffer is full after
10,000 iterations (with a total of 10,000 possible roots), the garbage
collection mechanism kicks in and frees the memory associated with those
possible roots. This can very clearly be seen in the jagged memory-usage
graph for PHP 5.3. After each 10,000 iterations, the mechanism kicks in
and frees the memory associated with the circular referenced variables.
The mechanism itself does not have to do a whole lot of work in this
example, because the structure that is leaked is extremely simple. From
the diagram, you see that the maximum memory usage in PHP 5.3 is about 9
Mb, whereas in PHP 5.2 the memory usage keeps increasing.
Run-Time Slowdowns
The second area where the garbage collection mechanism influences
performance is the time taken when the garbage collection mechanism kicks
in to free the "leaked" memory. In order to see how much this is, we
slightly modify the previous script to allow for a larger number of
iterations and the removal of the intermediate memory usage figures. The
second script is here:
Example #2 GC performance influences
self = $a;
}
echo memory_get_peak_usage(), "\n";
?>
We will run this script two times, once with the zend.enable_gc setting
turned on, and once with it turned off:
Example #3 Running the above script
time php -dzend.enable_gc=0 -dmemory_limit=-1 -n example2.php
# and
time php -dzend.enable_gc=1 -dmemory_limit=-1 -n example2.php
On my machine, the first command seems to take consistently about 10.7
seconds, whereas the second command takes about 11.4 seconds. This is a
slowdown of about 7%. However, the maximum amount of memory used by the
script is reduced by 98% from 931Mb to 10Mb. This benchmark is not very
scientific, or even representative of real-life applications, but it does
demonstrate the memory usage benefits that this garbage collection
mechanism provides. The good thing is that the slowdown is always the same
7%, for this particular script, while the memory saving capabilities save
more and more memory as more circular references are found during script
execution.
PHP's Internal GC Statistics
It is possible to coax a little bit more information about how the garbage
collection mechanism is run from within PHP. But in order to do so, you
will have to re-compile PHP to enable the benchmark and data-collecting
code. You will have to set the CFLAGS environment variable to -DGC_BENCH=1
prior to running ./configure with your desired options. The following
sequence should do the trick:
Example #4 Recompiling PHP to enable GC benchmarking
export CFLAGS=-DGC_BENCH=1
./config.nice
make clean
make
When you run the above example code again with the newly built PHP binary,
you will see the following being shown after PHP has finished execution:
Example #5 GC statistics
GC Statistics
-------------
Runs: 110
Collected: 2072204
Root buffer length: 0
Root buffer peak: 10000
Possible Remove from Marked
Root Buffered buffer grey
-------- -------- ----------- ------
ZVAL 7175487 1491291 1241690 3611871
ZOBJ 28506264 1527980 677581 1025731
The most informative statistics are displayed in the first block. You can
see here that the garbage collection mechanism ran 110 times, and in
total, more than 2 million memory allocations were freed during those 110
runs. As soon as the garbage collection mechanism has run at least one
time, the "Root buffer peak" is always 10000.
Conclusion
In general the garbage collector in PHP will only cause a slowdown when
the cycle collecting algorithm actually runs, whereas in normal (smaller)
scripts there should be no performance hit at all.
However, in the cases where the cycle collection mechanism does run for
normal scripts, the memory reduction it will provide allows more of those
scripts to run concurrently on your server, since not so much memory is
used in total.
The benefits are most apparent for longer-running scripts, such as lengthy
test suites or daemon scripts. Also, for >> PHP-GTK applications that
generally tend to run longer than scripts for the Web, the new mechanism
should make quite a bit of a difference regarding memory leaks creeping in
over time.
----------------------------------------------------------------------
----------------------------------------------------------------------
* HTTP authentication with PHP
* Cookies
* Sessions
* Dealing with XForms
* Handling file uploads
* POST method uploads
* Error Messages Explained
* Common Pitfalls
* Uploading multiple files
* PUT method support
* Using remote files
* Connection handling
* Persistent Database Connections
* Safe Mode
* Security and Safe Mode
* Functions restricted/disabled by safe mode
* Command line usage - Using PHP from the command line
* Introduction
* Differences to other SAPIs
* Options - Command line options
* Usage - Executing PHP files
* I/O streams - Input/output streams
* Interactive shell
* Built-in web server
* Garbage Collection
* Reference Counting Basics
* Collecting Cycles
* Performance Considerations
----------------------------------------------------------------------
----------------------------------------------------------------------
Function Reference
Tip
See also Extension List/Categorization.
----------------------------------------------------------------------
Affecting PHP's Behaviour
----------------------------------------------------------------------
Alternative PHP Cache
----------------------------------------------------------------------
Introduction
The Alternative PHP Cache (APC) is a free and open opcode cache for PHP.
Its goal is to provide a free, open, and robust framework for caching and
optimizing PHP intermediate code.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
This >> PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here: >> http://pecl.php.net/package/apc.
A DLL for this PECL extension is currently unavailable. See also the
building on Windows section.
Note: On Windows, APC needs a temp path to exist, and be writable by the
web server. It checks the TMP, TEMP and USERPROFILE environment
variables in that order and finally tries the WINDOWS directory if none
of those are set.
Note: For more in-depth, highly technical implementation details, see
the >> developer-supplied TECHNOTES file .
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Although the default APC settings are fine for many installations, serious
users should consider tuning the following parameters.
There are two primary decisions to be made configuring APC. First, how
much memory is going to be allocated to APC; and second, whether APC will
check if a file has been modified on every request. The two ini directives
that control these settings are apc.shm_size and apc.stat, respectively.
Read the sections on these two directive carefully below.
Once the server is running, the apc.php script that is bundled with the
extension should be copied somewhere into the docroot and viewed with a
browser as it provides a detailed analysis of the internal workings of
APC. If GD is enabled in PHP, it will even display some interesting
graphs. The first thing to ensure, of course, is that it is actually
caching files. If APC is working, the Cache full count number (on the
left) will display the number of times the cache has reached maximum
capacity and has had to forcefully clean any entries that haven't been
accessed in the last apc.ttl seconds. This number is minimized in a
well-configured cache. If the cache is constantly being filled, and thusly
forcefully freed, the resulting churning will have disparaging effects on
script performance. The easiest way to minimize this number is to allocate
more memory for APC. Barring that, the apc.filters ought to be used to
cache fewer scripts.
When APC is compiled with mmap support (Memory Mapping), it will use only
one memory segment, unlike when APC is built with SHM (SysV Shared Memory)
support that uses multiple memory segments. MMAP does not have a maximum
limit like SHM does in /proc/sys/kernel/shmmax. In general MMAP support is
recommeded because it will reclaim the memory faster when the webserver is
restarted and all in all reduces memory allocation impact at startup.
APC configuration options
Name Default Changeable Changelog
PHP_INI_SYSTEM
apc.enabled "1" PHP_INI_SYSTEM in APC 2.
PHP_INI_ALL in
APC <= 3.0.12.
apc.shm_segments "1" PHP_INI_SYSTEM
apc.shm_size "32M" PHP_INI_SYSTEM
PHP_INI_SYSTEM
apc.optimization "0" PHP_INI_ALL in APC 2.
Removed in APC
3.0.13.
apc.num_files_hint "1000" PHP_INI_SYSTEM
Available
apc.user_entries_hint "4096" PHP_INI_SYSTEM since APC
3.0.0.
Available
apc.ttl "0" PHP_INI_SYSTEM since APC
3.0.0.
Available
apc.user_ttl "0" PHP_INI_SYSTEM since APC
3.0.0.
apc.gc_ttl "3600" PHP_INI_SYSTEM
PHP_INI_SYSTEM
in APC <=
apc.cache_by_default "1" PHP_INI_ALL 3.0.12.
Available
since APC
3.0.0.
apc.filters NULL PHP_INI_SYSTEM
apc.mmap_file_mask NULL PHP_INI_SYSTEM
Available
since APC
3.0.0. Prior
apc.slam_defense "1" PHP_INI_SYSTEM to APC 3.1.4,
the default
value was "0"
(disabled).
Available
apc.file_update_protection "2" PHP_INI_SYSTEM since APC
3.0.6.
Available
apc.enable_cli "0" PHP_INI_SYSTEM since APC
3.0.7.
Available
apc.max_file_size "1M" PHP_INI_SYSTEM since APC
3.0.7.
Available
apc.use_request_time "1" PHP_INI_ALL since APC
3.1.3.
Available
apc.stat "1" PHP_INI_SYSTEM since APC
3.0.10.
Available
apc.write_lock "1" PHP_INI_SYSTEM since APC
3.0.11.
Available
apc.report_autofilter "0" PHP_INI_SYSTEM since APC
3.0.11.
Available
apc.include_once_override "0" PHP_INI_SYSTEM since APC
3.0.12.
Available
apc.rfc1867 "0" PHP_INI_SYSTEM since APC
3.0.13.
apc.rfc1867_prefix "upload_" PHP_INI_SYSTEM
apc.rfc1867_name "APC_UPLOAD_PROGRESS" PHP_INI_SYSTEM
apc.rfc1867_freq "0" PHP_INI_SYSTEM
Available
apc.rfc1867_ttl "3600" PHP_INI_SYSTEM since APC
3.1.1.
Available
apc.localcache "0" PHP_INI_SYSTEM since APC
3.0.14.
Available
apc.localcache.size "512" PHP_INI_SYSTEM since APC
3.0.14.
Available
apc.coredump_unmap "0" PHP_INI_SYSTEM since APC
3.0.16.
Available
apc.stat_ctime "0" PHP_INI_SYSTEM since APC
3.0.13.
Available
apc.preload_path NULL PHP_INI_SYSTEM since APC
3.1.1.
Available
apc.file_md5 "0" PHP_INI_SYSTEM since APC
3.1.1.
Available
apc.canonicalize "1" PHP_INI_SYSTEM since APC
3.1.1.
Available
apc.lazy_functions 0 PHP_INI_SYSTEM since APC
3.1.3.
Available
apc.lazy_classes 0 PHP_INI_SYSTEM since APC
3.1.3.
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
apc.enabled boolean
apc.enabled can be set to 0 to disable APC. This is primarily
useful when APC is statically compiled into PHP, since there is no
other way to disable it (when compiled as a DSO, the extension
line in php.ini can just be commented-out).
apc.shm_segments integer
The number of shared memory segments to allocate for the compiler
cache. If APC is running out of shared memory but apc.shm_size is
set as high as the system allows, raising this value might prevent
APC from exhausting its memory.
apc.shm_size integer
The size of each shared memory segment in MB. By default, some
systems (including most BSD variants) have very low limits on the
size of a shared memory segment.
apc.optimization integer
The optimization level. Zero disables the optimizer, and higher
values use more aggressive optimizations. Expect very modest speed
improvements. This is experimental.
apc.num_files_hint integer
A "hint" about the number of distinct source files that will be
included or requested on your web server. Set to zero or omit if
unsure; this setting is mainly useful for sites that have many
thousands of source files.
apc.user_entries_hint integer
Just like apc.num_files_hint, a "hint" about the number of
distinct user cache variables to store. Set to zero or omit if not
sure.
apc.ttl integer
The number of seconds a cache entry is allowed to idle in a slot
in case this cache entry slot is needed by another entry. Leaving
this at zero means that APC's cache could potentially fill up with
stale entries while newer entries won't be cached. In the event of
a cache running out of available memory, the cache will be
completely expunged if ttl is equal to 0. Otherwise, if the ttl is
greater than 0, APC will attempt to remove expired entries.
apc.user_ttl integer
The number of seconds a cache entry is allowed to idle in a slot
in case this cache entry slot is needed by another entry. Leaving
this at zero means that APC's cache could potentially fill up with
stale entries while newer entries won't be cached. In the event of
a cache running out of available memory, the cache will be
completely expunged if ttl is equal to 0. Otherwise, if the ttl is
greater than 0, APC will attempt to remove expired entries.
apc.gc_ttl integer
The number of seconds that a cache entry may remain on the
garbage-collection list. This value provides a fail-safe in the
event that a server process dies while executing a cached source
file; if that source file is modified, the memory allocated for
the old version will not be reclaimed until this TTL reached. Set
to zero to disable this feature.
apc.cache_by_default boolean
On by default, but can be set to off and used in conjunction with
positive apc.filters so that files are only cached if matched by a
positive filter.
apc.filters string
A comma-separated list of POSIX extended regular expressions. If
any pattern matches the source filename, the file will not be
cached. Note that the filename used for matching is the one passed
to include/require, not the absolute path. If the first character
of the expression is a + then the expression will be additive in
the sense that any files matched by the expression will be cached,
and if the first character is a - then anything matched will not
be cached. The - case is the default, so it can be left off.
apc.mmap_file_mask string
If compiled with MMAP support by using --enable-mmap this is the
mktemp-style file_mask to pass to the mmap module for determining
whether your mmap'ed memory region is going to be file-backed or
shared memory backed. For straight file-backed mmap, set it to
something like /tmp/apc.XXXXXX (exactly 6 Xs). To use POSIX-style
shm_open/mmap put a .shm somewhere in your mask. e.g.
/apc.shm.XXXXXX You can also set it to /dev/zero to use your
kernel's /dev/zero interface to anonymous mmap'ed memory. Leaving
it undefined will force an anonymous mmap.
apc.slam_defense integer
On very busy servers whenever you start the server or modify files
you can create a race of many processes all trying to cache the
same file at the same time. This option sets the percentage of
processes that will skip trying to cache an uncached file. Or
think of it as the probability of a single process to skip
caching. For example, setting apc.slam_defense to 75 would mean
that there is a 75% chance that the process will not cache an
uncached file. So, the higher the setting the greater the defense
against cache slams. Setting this to 0 disables this feature.
Deprecated by apc.write_lock.
apc.file_update_protection integer
When a file is modified on a live web server it really ought to be
done in an atomic manner. That is, written to a temporary file and
renamed (mv) the file into its permanent position when it is
ready. Many text editors, cp, tar and other such programs don't do
this. This means that there is a chance that a file is accessed
(and cached) while it is still being written to. This
apc.file_update_protection setting puts a delay on caching brand
new files. The default is 2 seconds, which means that if the
modification timestamp (mtime) on a file shows that it is less
than 2 seconds old when it is accessed, it will not be cached. The
unfortunate person who accessed this half-written file will still
see weirdness, but at least it won't persist. If all of the
webserver's files are atomically updated, via some method like
rsync (which updates correctly), this protection can be disabled
by setting this directive to 0. If the system is flooded with i/o
and some update procedures are taking longer than 2 seconds, this
setting should be increased to enable the protection on those
slower update operations.
apc.enable_cli integer
Mostly for testing and debugging. Setting this enables APC for the
CLI version of PHP. Under normal circumstances, it is not ideal to
create, populate and destroy the APC cache on every CLI request,
but for various test scenarios it is useful to be able to enable
APC for the CLI version of PHP easily.
apc.max_file_size integer
Prevent files larger than this value from getting cached. Defaults
to 1M.
apc.stat integer
Be careful changing this setting. This defaults to on, forcing APC
to stat (check) the script on each request to determine if it has
been modified. If it has been modified it will recompile and cache
the new version. If this setting is off, APC will not check, which
usually means that to force APC to recheck files, the web server
will have to be restarted or the cache will have to be manually
cleared. Note that FastCGI web server configurations may not clear
the cache on restart. On a production server where the script
files rarely change, a significant performance boost can be
achieved by disabled stats.
For included/required files this option applies as well, but note
that for relative path includes (any path that doesn't start with
/ on Unix) APC has to check in order to uniquely identify the
file. If you use absolute path includes APC can skip the stat and
use that absolute path as the unique identifier for the file.
apc.write_lock boolean
On busy servers, when the web server is first started, or when
many files have been modified at the same time, APC may try to
compile and cache the same file multiple times. Write_lock
guarantees that only one process will attempt to compile and cache
an uncached script. The other processes attempting to use the
script will run without using the opcode cache, rather than
locking and waiting for the cache to prime.
apc.report_autofilter boolean
Logs any scripts that were automatically excluded from being
cached due to early/late binding issues.
apc.include_once_override boolean
Optimize include_once() and require_once() calls and avoid the
expensive system calls used.
apc.rfc1867 boolean
RFC1867 File Upload Progress hook handler is only available if APC
was compiled against PHP 5.2.0 or later. When enabled, any file
uploads which includes a field called APC_UPLOAD_PROGRESS before
the file field in an upload form will cause APC to automatically
create an upload_key user cache entry where key is the value of
the APC_UPLOAD_PROGRESS form entry.
Note that the hidden field specified by APC_UPLOAD_PROGRESS must
come before the file field, otherwise the upload progress will not
work correctly.
Note that the file upload tracking is not threadsafe at this
point, so new uploads that happen while a previous one is still
going will disable the tracking for the previous.
Example #1 An apc.rfc1867 example
The above example will output something similar to:
Array
(
[total] => 1142543
[current] => 1142543
[rate] => 1828068.8
[filename] => test
[name] => file
[temp_filename] => /tmp/php8F
[cancel_upload] => 0
[done] => 1
)
apc.rfc1867_prefix string
Key prefix to use for the user cache entry generated by rfc1867
upload progress functionality.
apc.rfc1867_name string
Specify the hidden form entry name that activates APC upload
progress and specifies the user cache key suffix.
apc.rfc1867_freq string
The frequency that updates should be made to the user cache entry
for upload progress. This can take the form of a percentage of the
total file size or a size in bytes optionally suffixed with "k",
"m", or "g" for kilobytes, megabytes, or gigabytes respectively
(case insensitive). A setting of 0 updates as often as possible,
which may cause slower uploads.
apc.rfc1867_ttl bool
TTL for rfc1867 entries.
apc.localcache boolean
This enables a lock-free local process shadow-cache which reduces
lock contention when the cache is being written to.
apc.localcache.size integer
The size of the local process shadow-cache, should be set to a
sufficiently large value, approximately half of
apc.num_files_hint.
apc.coredump_unmap boolean
Enables APC handling of signals, such as SIGSEGV, that write core
files when signaled. When these signals are received, APC will
attempt to unmap the shared memory segment in order to exclude it
from the core file. This setting may improve system stability when
fatal signals are received and a large APC shared memory segment
is configured.
Warning
This feature is potentially dangerous. Unmapping the shared memory
segment in a fatal signal handler may cause undefined behaviour if
a fatal error occurs.
Note:
Although some kernels may provide a facility to ignore various
types of shared memory when generating a core dump file, these
implementations may also ignore important shared memory segments
such as the Apache scoreboard.
apc.stat_ctime integer
Verification with ctime will avoid problems caused by programs
such as svn or rsync by making sure inodes haven't changed since
the last stat. APC will normally only check mtime.
apc.canonicalize bool
If on, then relative paths are canonicalized in no-stat mode. If
set, then files included via stream wrappers can not be cached as
realpath() does not support stream wrappers.
apc.preload_path string
apc.use_request_time bool
Use the SAPI request start time for TTL.
apc.file_md5 bool
Records a md5 hash of files.
apc.lazy_functions integer
Enables lazy loading for functions.
apc.lazy_classes integer
Enables lazy loading for classes.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
APC_BIN_VERIFY_CRC32 (integer)
APC_BIN_VERIFY_MD5 (integer)
APC_ITER_ALL (integer)
APC_ITER_ATIME (integer)
APC_ITER_CTIME (integer)
APC_ITER_DEVICE (integer)
APC_ITER_DTIME (integer)
APC_ITER_FILENAME (integer)
APC_ITER_INODE (integer)
APC_ITER_KEY (integer)
APC_ITER_MD5 (integer)
APC_ITER_MEM_SIZE (integer)
APC_ITER_MTIME (integer)
APC_ITER_NONE (integer)
APC_ITER_NUM_HITS (integer)
APC_ITER_REFCOUNT (integer)
APC_ITER_TTL (integer)
APC_ITER_TYPE (integer)
APC_ITER_VALUE (integer)
APC_LIST_ACTIVE (integer)
APC_LIST_DELETED (integer)
----------------------------------------------------------------------
----------------------------------------------------------------------
APC Functions
----------------------------------------------------------------------
apc_add
(PECL apc >= 3.0.13)
apc_add - Cache a variable in the data store
Description
bool apc_add ( string $key [, mixed $var [, int $ttl = 0 ]] )
array apc_add ( array $values [, mixed $unused [, int $ttl = 0 ]] )
Caches a variable in the data store, only if it's not already stored.
Note: Unlike many other mechanisms in PHP, variables stored using
apc_add() will persist between requests (until the value is removed from
the cache).
Parameters
key
Store the variable using this name. keys are cache-unique, so
attempting to use apc_add() to store data with a key that already
exists will not overwrite the existing data, and will instead
return FALSE. (This is the only difference between apc_add() and
apc_store().)
var
The variable to store
ttl
Time To Live; store var in the cache for ttl seconds. After the
ttl has passed, the stored variable will be expunged from the
cache (on the next request). If no ttl is supplied (or if the ttl
is 0), the value will persist until it is removed from the cache
manually, or otherwise fails to exist in the cache (clear,
restart, etc.).
values
Names in key, variables in value.
Return Values
Returns TRUE on success or FALSE on failure. Second syntax returns array
with error keys.
Examples
Example #1 A apc_add() example
The above example will output:
string(3) "BAR"
string(3) "BAR"
See Also
* apc_store() - Cache a variable in the data store
* apc_fetch() - Fetch a stored variable from the cache
* apc_delete() - Removes a stored variable from the cache
----------------------------------------------------------------------
----------------------------------------------------------------------
apc_bin_dump
(PECL apc >= 3.1.4)
apc_bin_dump - Get a binary dump of the given files and user variables
Description
string apc_bin_dump ([ array $files [, array $user_vars ]] )
Returns a binary dump of the given files and user variables from the APC
cache. A NULL for files or user_vars signals a dump of every entry,
whereas array() will dump nothing.
Parameters
files
The files. Passing in NULL signals a dump of every entry, while
passing in array() will dump nothing.
user_vars
The user vars. Passing in NULL signals a dump of every entry,
while passing in array() will dump nothing.
Return Values
Returns a binary dump of the given files and user variables from the APC
cache, FALSE if APC is not enabled, or NULL if an unknown error is
encountered.
See Also
* apc_bin_dumpfile() - Output a binary dump of cached files and user
variables to a file
* apc_bin_load() - Load a binary dump into the APC file/user cache
----------------------------------------------------------------------
----------------------------------------------------------------------
apc_bin_dumpfile
(PECL apc >= 3.1.4)
apc_bin_dumpfile - Output a binary dump of cached files and user variables
to a file
Description
int apc_bin_dumpfile ( array $files , array $user_vars , string $filename
[, int $flags = 0 [, resource $context ]] )
Outputs a binary dump of the given files and user variables from the APC
cache to the named file.
Parameters
files
The file names being dumped.
user_vars
The user variables being dumped.
filename
The filename where the dump is being saved.
flags
Flags passed to the filename stream. See the file_put_contents()
documentation for details.
context
The context passed to the filename stream. See the
file_put_contents() documentation for details.
Return Values
The number of bytes written to the file, otherwise FALSE if APC is not
enabled, filename is an invalid file name, filename can't be opened, the
file dump can't be completed (e.g., the hard drive is out of disk space),
or an unknown error was encountered.
See Also
* apc_bin_dump() - Get a binary dump of the given files and user
variables
* apc_bin_load() - Load a binary dump into the APC file/user cache
----------------------------------------------------------------------
----------------------------------------------------------------------
apc_bin_load
(PECL apc >= 3.1.4)
apc_bin_load - Load a binary dump into the APC file/user cache
Description
bool apc_bin_load ( string $data [, int $flags = 0 ] )
Loads the given binary dump into the APC file/user cache.
Parameters
data
The binary dump being loaded, likely from apc_bin_dump().
flags
Either APC_BIN_VERIFY_CRC32, APC_BIN_VERIFY_MD5, or both.
Return Values
Returns TRUE if the binary dump data was loaded with success, otherwise
FALSE is returned. FALSE is returned if APC is not enabled, or if the data
is not a valid APC binary dump (e.g., unexpected size).
Examples
Example #1 apc_bin_load() example
See Also
* apc_bin_dump() - Get a binary dump of the given files and user
variables
* apc_bin_loadfile() - Load a binary dump from a file into the APC
file/user cache
----------------------------------------------------------------------
----------------------------------------------------------------------
apc_bin_loadfile
(PECL apc >= 3.1.4)
apc_bin_loadfile - Load a binary dump from a file into the APC file/user
cache
Description
bool apc_bin_loadfile ( string $filename [, resource $context [, int
$flags ]] )
Loads a binary dump from a file into the APC file/user cache.
Parameters
filename
The file name containing the dump, likely from apc_bin_dumpfile().
context
The files context.
flags
Either APC_BIN_VERIFY_CRC32, APC_BIN_VERIFY_MD5, or both.
Return Values
Returns TRUE on success, otherwise FALSE Reasons it may return FALSE
include APC is not enabled, filename is an invalid file name or empty,
filename can't be opened, the file dump can't be completed, or if the data
is not a valid APC binary dump (e.g., unexpected size).
See Also
* apc_bin_dumpfile() - Output a binary dump of cached files and user
variables to a file
* apc_bin_load() - Load a binary dump into the APC file/user cache
----------------------------------------------------------------------
----------------------------------------------------------------------
apc_cache_info
(PECL apc >= 2.0.0)
apc_cache_info - Retrieves cached information from APC's data store
Description
array apc_cache_info ([ string $cache_type [, bool $limited = false ]] )
Retrieves cached information and meta-data from APC's data store.
Return Values
Array of cached data (and meta-data) or FALSE on failure
Note: apc_cache_info() will raise a warning if it is unable to retrieve
APC cache data. This typically occurs when APC is not enabled.
Parameters
cache_type
If cache_type is "user", information about the user cache will be
returned.
If cache_type is "filehits", information about which files have
been served from the bytecode cache for the current request will
be returned. This feature must be enabled at compile time using
--enable-filehits .
If an invalid or no cache_type is specified, information about the
system cache (cached files) will be returned.
limited
If limited is TRUE, the return value will exclude the individual
list of cache entries. This is useful when trying to optimize
calls for statistics gathering.
Changelog
Version Description
3.0.11 The limited parameter was introduced.
3.0.16 The "filehits" option for the cache_type parameter was introduced.
Examples
Example #1 A apc_cache_info() example
The above example will output something similar to:
Array
(
[num_slots] => 2000
[ttl] => 0
[num_hits] => 9
[num_misses] => 3
[start_time] => 1123958803
[cache_list] => Array
(
[0] => Array
(
[filename] => /path/to/apc_test.php
[device] => 29954
[inode] => 1130511
[type] => file
[num_hits] => 1
[mtime] => 1123960686
[creation_time] => 1123960696
[deletion_time] => 0
[access_time] => 1123962864
[ref_count] => 1
[mem_size] => 677
)
[1] => Array (...iterates for each cached file)
)
See Also
* APC configuration directives
* APCIterator::getTotalSize() - Get total cache size
* APCIterator::getTotalHits() - Get total cache hits
* APCIterator::getTotalCount() - Get total count
----------------------------------------------------------------------
----------------------------------------------------------------------
apc_cas
(PECL apc >= 3.1.1)
apc_cas - Updates an old value with a new value
Description
bool apc_cas ( string $key , int $old , int $new )
apc_cas() updates an already existing integer value if the old parameter
matches the currently stored value with the value of the new parameter.
Parameters
key
The key of the value being updated.
old
The old value (the value currently stored).
new
The new value to update to.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 apc_cas() example
The above example will output something similar to:
$foobar = 2
$foobar == 1 ? 2 : 1 = fail
$foobar == 2 ? 1 : 2 = ok
$foobar = 1
$f__bar == 1 ? 2 : 1 = fail
$perfection == 2 ? 1 : 2 = epic fail
$foobar = 1
See Also
* apc_dec() - Decrease a stored number
* apc_store() - Cache a variable in the data store
----------------------------------------------------------------------
----------------------------------------------------------------------
apc_clear_cache
(PECL apc >= 2.0.0)
apc_clear_cache - Clears the APC cache
Description
bool apc_clear_cache ([ string $cache_type ] )
Clears the user/system cache.
Return Values
Returns TRUE on success or FALSE on failure.
Parameters
cache_type
If cache_type is "user", the user cache will be cleared;
otherwise, the system cache (cached files) will be cleared.
See Also
* apc_cache_info() - Retrieves cached information from APC's data store
----------------------------------------------------------------------
----------------------------------------------------------------------
apc_compile_file
(PECL apc >= 3.0.13)
apc_compile_file - Stores a file in the bytecode cache, bypassing all
filters.
Description
mixed apc_compile_file ( string $filename [, bool $atomic = true ] )
Stores a file in the bytecode cache, bypassing all filters.
Parameters
filename
Full or relative path to a PHP file that will be compiled and
stored in the bytecode cache.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* apc_bin_dumpfile() - Output a binary dump of cached files and user
variables to a file
* apc_bin_loadfile() - Load a binary dump from a file into the APC
file/user cache
----------------------------------------------------------------------
----------------------------------------------------------------------
apc_dec
(PECL apc >= 3.1.1)
apc_dec - Decrease a stored number
Description
int apc_dec ( string $key [, int $step = 1 [, bool &$success ]] )
Decreases a stored integer value.
Parameters
key
The key of the value being decreased.
step
The step, or value to decrease.
success
Optionally pass the success or fail boolean value to this
referenced variable.
Return Values
Returns the current value of key's value on success, or FALSE on failure
Examples
Example #1 apc_dec() example
The above example will output something similar to:
Let's do something with success
42
41
31
21
bool(true)
Now, let's fail
bool(false)
bool(false)
See Also
* apc_inc() - Increase a stored number
----------------------------------------------------------------------
----------------------------------------------------------------------
apc_define_constants
(PECL apc >= 3.0.0)
apc_define_constants - Defines a set of constants for retrieval and
mass-definition
Description
bool apc_define_constants ( string $key , array $constants [, bool
$case_sensitive = true ] )
define() is notoriously slow. Since the main benefit of APC is to increase
the performance of scripts/applications, this mechanism is provided to
streamline the process of mass constant definition. However, this function
does not perform as well as anticipated.
For a better-performing solution, try the >> hidef extension from PECL.
Note: To remove a set of stored constants (without clearing the entire
cache), an empty array may be passed as the constants parameter,
effectively clearing the stored value(s).
Parameters
key
The key serves as the name of the constant set being stored. This
key is used to retrieve the stored constants in
apc_load_constants().
constants
An associative array of constant_name => value pairs. The
constant_name must follow the normal constant naming rules. value
must evaluate to a scalar value.
case_sensitive
The default behaviour for constants is to be declared
case-sensitive; i.e. CONSTANT and Constant represent different
values. If this parameter evaluates to FALSE the constants will be
declared as case-insensitive symbols.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 apc_define_constants() example
1,
'TWO' => 2,
'THREE' => 3,
);
apc_define_constants('numbers', $constants);
echo ONE, TWO, THREE;
?>
The above example will output:
123
See Also
* apc_load_constants() - Loads a set of constants from the cache
* define() - Defines a named constant
* constant() - Returns the value of a constant
* Or the PHP constants reference
----------------------------------------------------------------------
----------------------------------------------------------------------
apc_delete_file
(PECL apc >= 3.1.1)
apc_delete_file - Deletes files from the opcode cache
Description
mixed apc_delete_file ( mixed $keys )
Deletes the given files from the opcode cache.
Parameters
keys
The files to be deleted. Accepts a string, array of strings, or an
APCIterator object.
Return Values
Returns TRUE on success or FALSE on failure. Or if keys is an array, then
an empty array is returned on success, or an array of failed files is
returned.
Examples
Example #1 apc_delete_file() example
The above example will output something similar to:
Successfully deleted file file.php from APC cache.
[Mon May 24 09:30:33 2010] [apc-warning] Could not stat file donotexist.php, unable to delete from cache. in /tmp/test.php on line 13.
array(1) {
[0]=>
string(14) "donotexist.php"
}
[Mon May 24 09:30:33 2010] [apc-warning] Could not stat file donotexist.php, unable to delete from cache. in /tmp/test.php on line 18.
bool(false)
See Also
* apc_clear_cache() - Clears the APC cache
* apc_delete() - Removes a stored variable from the cache
* apc_exists() - Checks if APC key exists
----------------------------------------------------------------------
----------------------------------------------------------------------
apc_delete
(PECL apc >= 3.0.0)
apc_delete - Removes a stored variable from the cache
Description
mixed apc_delete ( string $key )
Removes a stored variable from the cache.
Parameters
key
The key used to store the value (with apc_store()).
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 A apc_delete() example
See Also
* apc_store() - Cache a variable in the data store
* apc_fetch() - Fetch a stored variable from the cache
----------------------------------------------------------------------
----------------------------------------------------------------------
apc_exists
(PECL apc >= 3.1.4)
apc_exists - Checks if APC key exists
Description
mixed apc_exists ( mixed $keys )
Checks if one ore more APC keys exist.
Parameters
keys
A string, or an array of strings, that contain keys.
Return Values
Returns TRUE if the key exists, otherwise FALSE Or if an array was passed
to keys, then an array is returned that contains all existing keys, or an
empty array if none exist.
Examples
Example #1 apc_exists() example
The above example will output something similar to:
Foo exists: apple
Baz does not exist
array(2) {
["foo"]=>
bool(true)
["bar"]=>
bool(true)
}
See Also
* apc_cache_info() - Retrieves cached information from APC's data store
* apc_fetch() - Fetch a stored variable from the cache
----------------------------------------------------------------------
----------------------------------------------------------------------
apc_fetch
(PECL apc >= 3.0.0)
apc_fetch - Fetch a stored variable from the cache
Description
mixed apc_fetch ( mixed $key [, bool &$success ] )
Fetchs a stored variable from the cache.
Parameters
key
The key used to store the value (with apc_store()). If an array is
passed then each element is fetched and returned.
success
Set to TRUE in success and FALSE in failure.
Return Values
The stored variable or array of variables on success; FALSE on failure
Examples
Example #1 A apc_fetch() example
The above example will output:
string(3) "BAR"
Changelog
Version Description
3.0.17 The success parameter was added.
See Also
* apc_store() - Cache a variable in the data store
* apc_delete() - Removes a stored variable from the cache
* APCIterator
----------------------------------------------------------------------
----------------------------------------------------------------------
apc_inc
(PECL apc >= 3.1.1)
apc_inc - Increase a stored number
Description
int apc_inc ( string $key [, int $step = 1 [, bool &$success ]] )
Increases a stored number.
Parameters
key
The key of the value being increased.
step
The step, or value to increase.
success
Optionally pass the success or fail boolean value to this
referenced variable.
Return Values
Returns the current value of key's value on success, or FALSE on failure
Examples
Example #1 apc_inc() example
The above example will output something similar to:
42
43
53
63
bool(true)
Now, let's fail
bool(false)
bool(false)
See Also
* apc_dec() - Decrease a stored number
----------------------------------------------------------------------
----------------------------------------------------------------------
apc_load_constants
(PECL apc >= 3.0.0)
apc_load_constants - Loads a set of constants from the cache
Description
bool apc_load_constants ( string $key [, bool $case_sensitive = true ] )
Loads a set of constants from the cache.
Parameters
key
The name of the constant set (that was stored with
apc_define_constants()) to be retrieved.
case_sensitive
The default behaviour for constants is to be declared
case-sensitive; i.e. CONSTANT and Constant represent different
values. If this parameter evaluates to FALSE the constants will be
declared as case-insensitive symbols.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 apc_load_constants() example
1,
'TWO' => 2,
'THREE' => 3,
);
apc_define_constants('numbers', $constants);
apc_load_constants('numbers');
echo ONE, TWO, THREE;
?>
The above example will output:
123
See Also
* apc_define_constants() - Defines a set of constants for retrieval and
mass-definition
* define() - Defines a named constant
* constant() - Returns the value of a constant
* Or the PHP constants reference
----------------------------------------------------------------------
----------------------------------------------------------------------
apc_sma_info
(PECL apc >= 2.0.0)
apc_sma_info - Retrieves APC's Shared Memory Allocation information
Description
array apc_sma_info ([ bool $limited = false ] )
Retrieves APC's Shared Memory Allocation information.
Parameters
limited
When set to FALSE (default) apc_sma_info() will return a detailed
information about each segment.
Return Values
Array of Shared Memory Allocation data; FALSE on failure.
Examples
Example #1 A apc_sma_info() example
The above example will output something similar to:
Array
(
[num_seg] => 1
[seg_size] => 31457280
[avail_mem] => 31448408
[block_lists] => Array
(
[0] => Array
(
[0] => Array
(
[size] => 31448408
[offset] => 8864
)
)
)
)
See Also
* APC configuration directives
----------------------------------------------------------------------
----------------------------------------------------------------------
apc_store
(PECL apc >= 3.0.0)
apc_store - Cache a variable in the data store
Description
bool apc_store ( string $key , mixed $var [, int $ttl = 0 ] )
array apc_store ( array $values [, mixed $unused [, int $ttl = 0 ]] )
Cache a variable in the data store.
Note: Unlike many other mechanisms in PHP, variables stored using
apc_store() will persist between requests (until the value is removed
from the cache).
Parameters
key
Store the variable using this name. keys are cache-unique, so
storing a second value with the same key will overwrite the
original value.
var
The variable to store
ttl
Time To Live; store var in the cache for ttl seconds. After the
ttl has passed, the stored variable will be expunged from the
cache (on the next request). If no ttl is supplied (or if the ttl
is 0), the value will persist until it is removed from the cache
manually, or otherwise fails to exist in the cache (clear,
restart, etc.).
values
Names in key, variables in value.
Return Values
Returns TRUE on success or FALSE on failure. Second syntax returns array
with error keys.
Examples
Example #1 A apc_store() example
The above example will output:
string(3) "BAR"
See Also
* apc_add() - Cache a variable in the data store
* apc_fetch() - Fetch a stored variable from the cache
* apc_delete() - Removes a stored variable from the cache
----------------------------------------------------------------------
Table of Contents
* apc_add - Cache a variable in the data store
* apc_bin_dump - Get a binary dump of the given files and user variables
* apc_bin_dumpfile - Output a binary dump of cached files and user
variables to a file
* apc_bin_load - Load a binary dump into the APC file/user cache
* apc_bin_loadfile - Load a binary dump from a file into the APC
file/user cache
* apc_cache_info - Retrieves cached information from APC's data store
* apc_cas - Updates an old value with a new value
* apc_clear_cache - Clears the APC cache
* apc_compile_file - Stores a file in the bytecode cache, bypassing all
filters.
* apc_dec - Decrease a stored number
* apc_define_constants - Defines a set of constants for retrieval and
mass-definition
* apc_delete_file - Deletes files from the opcode cache
* apc_delete - Removes a stored variable from the cache
* apc_exists - Checks if APC key exists
* apc_fetch - Fetch a stored variable from the cache
* apc_inc - Increase a stored number
* apc_load_constants - Loads a set of constants from the cache
* apc_sma_info - Retrieves APC's Shared Memory Allocation information
* apc_store - Cache a variable in the data store
----------------------------------------------------------------------
----------------------------------------------------------------------
The APCIterator class
Introduction
The APCIterator class makes it easier to iterate over large APC caches.
This is helpful as it allows iterating over large caches in steps, while
grabbing a defined number of entries per lock instance, so it frees the
cache locks for other activities rather than hold up the entire cache to
grab 100 (the default) entries. Also, using regular expression matching is
more efficient as it's been moved to the C level.
Class synopsis
APCIterator implements Iterator , Traversable {
/* Methods */
__construct ( string $cache [, mixed $search = null [, int $format [, int
$chunk_size = 100 [, int $list ]]]] )
public mixed current ( void )
public int getTotalCount ( void )
public int getTotalHits ( void )
public int getTotalSize ( void )
public string key ( void )
public void next ( void )
public void rewind ( void )
public void valid ( void )
}
----------------------------------------------------------------------
APCIterator::__construct
(PECL apc >= 3.1.1)
APCIterator::__construct - Constructs an APCIterator iterator object
Description
APCIterator::__construct ( string $cache [, mixed $search = null [, int
$format [, int $chunk_size = 100 [, int $list ]]]] )
Constructs an APCIterator object.
Parameters
cache
The cache type, which will be user or file.
search
A PCRE regular expression that matches against APC key names,
either as a string for a single regular expression, or as an array
of regular expressions. Or, optionally pass in NULL to skip the
search.
format
The desired format, as configured with one ore more of the
APC_ITER_* constants.
chunk_size
The chunk size. Must be a value greater than 0. The default value
is 100.
list
The type to list. Either pass in APC_LIST_ACTIVE or
APC_LIST_DELETED.
Return Values
An APCIterator object on success, or NULL on failure.
See Also
* apc_exists() - Checks if APC key exists
* apc_cache_info() - Retrieves cached information from APC's data store
----------------------------------------------------------------------
----------------------------------------------------------------------
APCIterator::current
(PECL apc >= 3.1.1)
APCIterator::current - Get current item
Description
public mixed APCIterator::current ( void )
Gets the current item from the APCIterator stack.
Parameters
This function has no parameters.
Return Values
Returns the current item on success, or FALSE if no more items or exist,
or on failure.
See Also
* APCIterator::next() - Move pointer to next item
* Iterator::current() - Return the current element
----------------------------------------------------------------------
----------------------------------------------------------------------
APCIterator::getTotalCount
(PECL apc >= 3.1.1)
APCIterator::getTotalCount - Get total count
Description
public int APCIterator::getTotalCount ( void )
Get the total count.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
This function has no parameters.
Return Values
The total count.
See Also
* APCIterator::getTotalHits() - Get total cache hits
* APCIterator::getTotalSize() - Get total cache size
* apc_cache_info() - Retrieves cached information from APC's data store
----------------------------------------------------------------------
----------------------------------------------------------------------
APCIterator::getTotalHits
(PECL apc >= 3.1.1)
APCIterator::getTotalHits - Get total cache hits
Description
public int APCIterator::getTotalHits ( void )
Gets the total number of cache hits.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
This function has no parameters.
Return Values
The number of hits on success, or FALSE on failure.
See Also
* APCIterator::getTotalCount() - Get total count
* APCIterator::getTotalSize() - Get total cache size
* apc_cache_info() - Retrieves cached information from APC's data store
----------------------------------------------------------------------
----------------------------------------------------------------------
APCIterator::getTotalSize
(PECL apc >= 3.1.1)
APCIterator::getTotalSize - Get total cache size
Description
public int APCIterator::getTotalSize ( void )
Gets the total cache size.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
This function has no parameters.
Return Values
The total cache size.
See Also
* APCIterator::getTotalCount() - Get total count
* APCIterator::getTotalHits() - Get total cache hits
* apc_cache_info() - Retrieves cached information from APC's data store
----------------------------------------------------------------------
----------------------------------------------------------------------
APCIterator::key
(PECL apc >= 3.1.1)
APCIterator::key - Get iterator key
Description
public string APCIterator::key ( void )
Gets the current iterator key.
Parameters
This function has no parameters.
Return Values
Returns the key on success, or FALSE upon failure.
See Also
* APCIterator::current() - Get current item
* Iterator::key() - Return the key of the current element
----------------------------------------------------------------------
----------------------------------------------------------------------
APCIterator::next
(PECL apc >= 3.1.1)
APCIterator::next - Move pointer to next item
Description
public void APCIterator::next ( void )
Moves the iterator pointer to the next element.
Parameters
This function has no parameters.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* APCIterator::current() - Get current item
* APCIterator::rewind() - Rewinds iterator
* Iterator::next() - Move forward to next element
----------------------------------------------------------------------
----------------------------------------------------------------------
APCIterator::rewind
(PECL apc >= 3.1.1)
APCIterator::rewind - Rewinds iterator
Description
public void APCIterator::rewind ( void )
Rewinds back the iterator to the first element.
Parameters
This function has no parameters.
Return Values
No value is returned.
See Also
* APCIterator::next() - Move pointer to next item
* Iterator::next() - Move forward to next element
----------------------------------------------------------------------
----------------------------------------------------------------------
APCIterator::valid
(PECL apc >= 3.1.1)
APCIterator::valid - Checks if current position is valid
Description
public void APCIterator::valid ( void )
Checks if the current iterator position is valid.
Parameters
This function has no parameters.
Return Values
Returns TRUE if the current iterator position is valid, otherwise FALSE.
See Also
* APCIterator::current() - Get current item
* Iterator::valid() - Checks if current position is valid
----------------------------------------------------------------------
Table of Contents
* APCIterator::__construct - Constructs an APCIterator iterator object
* APCIterator::current - Get current item
* APCIterator::getTotalCount - Get total count
* APCIterator::getTotalHits - Get total cache hits
* APCIterator::getTotalSize - Get total cache size
* APCIterator::key - Get iterator key
* APCIterator::next - Move pointer to next item
* APCIterator::rewind - Rewinds iterator
* APCIterator::valid - Checks if current position is valid
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* APC Functions
* apc_add - Cache a variable in the data store
* apc_bin_dump - Get a binary dump of the given files and user
variables
* apc_bin_dumpfile - Output a binary dump of cached files and user
variables to a file
* apc_bin_load - Load a binary dump into the APC file/user cache
* apc_bin_loadfile - Load a binary dump from a file into the APC
file/user cache
* apc_cache_info - Retrieves cached information from APC's data
store
* apc_cas - Updates an old value with a new value
* apc_clear_cache - Clears the APC cache
* apc_compile_file - Stores a file in the bytecode cache, bypassing
all filters.
* apc_dec - Decrease a stored number
* apc_define_constants - Defines a set of constants for retrieval
and mass-definition
* apc_delete_file - Deletes files from the opcode cache
* apc_delete - Removes a stored variable from the cache
* apc_exists - Checks if APC key exists
* apc_fetch - Fetch a stored variable from the cache
* apc_inc - Increase a stored number
* apc_load_constants - Loads a set of constants from the cache
* apc_sma_info - Retrieves APC's Shared Memory Allocation
information
* apc_store - Cache a variable in the data store
* APCIterator - The APCIterator class
* APCIterator::__construct - Constructs an APCIterator iterator
object
* APCIterator::current - Get current item
* APCIterator::getTotalCount - Get total count
* APCIterator::getTotalHits - Get total cache hits
* APCIterator::getTotalSize - Get total cache size
* APCIterator::key - Get iterator key
* APCIterator::next - Move pointer to next item
* APCIterator::rewind - Rewinds iterator
* APCIterator::valid - Checks if current position is valid
----------------------------------------------------------------------
----------------------------------------------------------------------
Advanced PHP debugger
----------------------------------------------------------------------
Introduction
APD is the Advanced PHP Debugger. It was written to provide profiling and
debugging capabilities for PHP code, as well as to provide the ability to
print out a full stack backtrace. APD supports interactive debugging, but
by default it writes data to trace files. It also offers event based
logging so that varying levels of information (including function calls,
arguments passed, timings, etc.) can be turned on or off for individual
scripts.
Caution
APD is a Zend Extension, modifying the way the internals of PHP handle
function calls, and thus may or may not be compatible with other Zend
Extensions (for example Zend Optimizer).
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Building on Win32
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here: >> http://pecl.php.net/package/apd.
A DLL for this PECL extension is currently unavailable. See also the
building on Windows section.
In your INI file, add the following lines:
zend_extension = /absolute/path/to/apd.so
apd.dumpdir = /absolute/path/to/trace/directory
apd.statement_tracing = 0
Depending on your PHP build, the zend_extension directive can be one of
the following:
zend_extension (non ZTS, non debug build)
zend_extension_ts ( ZTS, non debug build)
zend_extension_debug (non ZTS, debug build)
zend_extension_debug_ts ( ZTS, debug build)
----------------------------------------------------------------------
----------------------------------------------------------------------
Building on Win32
To build APD under Windows you need a working PHP compilation environment
as described on http://php.net/ -- basically, it requires you to have
Microsoft Visual C++, win32build.zip, bison/flex, and some know how to get
it to work. Also ensure that adp.dsp has DOS line endings; if it has unix
line endings, Microsoft Visual C++ will complain about it.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
APD Configuration Options
Name Default Changeable Changelog
apd.dumpdir NULL PHP_INI_ALL
apd.statement_tracing "0" PHP_INI_ALL Available since apd 0.9.
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
apd.dumpdir string
Sets the directory in which APD writes profile dump files. You can
specify an absolute path or a relative path.
You can specify a different directory as an argument to
apd_set_pprof_trace().
apd.statement_tracing boolean
Specfies whether or not to do per-line tracings. Turning this on
(1) will impact the performance of your application.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
APD constants
Constant Value Description
FUNCTION_TRACE (integer) 1
ARGS_TRACE (integer) 2
ASSIGNMENT_TRACE (integer) 4
STATEMENT_TRACE (integer) 8
MEMORY_TRACE (integer) 16
TIMING_TRACE (integer) 32
SUMMARY_TRACE (integer) 64
ERROR_TRACE (integer) 128
PROF_TRACE (integer) 256
APD_VERSION (string) example: 1.0.2-dev
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Table of Contents
* How to use PHP-APD in your scripts
----------------------------------------------------------------------
How to use PHP-APD in your scripts
1. As the first line of your PHP script, call the apd_set_pprof_trace()
function to start the trace:
You can insert the line anywhere in your script, but if you do not
start tracing at the beginning of your script you discard profile data
that might otherwise lead you to a performance bottleneck.
2. Now run your script. The dump output will be written to
apd.dumpdir/pprof_pid.ext.
Tip
If you're running the CGI version of PHP, you will need to add the
'-e' flag to enable extended information for apd to work properly. For
example: php -e -f script.php
3. To display formatted profile data, issue the pprofp command with the
sort and display options of your choice. The formatted output will
look something like:
bash-2.05b$ pprofp -R /tmp/pprof.22141.0
Trace for /home/dan/testapd.php
Total Elapsed Time = 0.00
Total System Time = 0.00
Total User Time = 0.00
Real User System secs/ cumm
%Time (excl/cumm) (excl/cumm) (excl/cumm) Calls call s/call Memory Usage Name
--------------------------------------------------------------------------------------
100.0 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0000 0.0009 0 main
56.9 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0005 0.0005 0 apd_set_pprof_trace
28.0 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 preg_replace
14.3 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 str_replace
The -R option used in this example sorts the profile table by the
amount of real time the script spent executing a given function. The
"cumm call" column reveals how many times each function was called,
and the "s/call" column reveals how many seconds each call to the
function required, on average.
4. To generate a calltree file that you can import into the KCacheGrind
profile analysis application, issue the pprof2calltree comand.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
APD Functions
Contact information
If you have comments, bugfixes, enhancements or want to help developing
this beast, you can send an mail to >> apd@mail.communityconnect.com. Any
help is very welcome.
----------------------------------------------------------------------
apd_breakpoint
(PECL apd >= 0.2)
apd_breakpoint - Stops the interpreter and waits on a CR from the socket
Description
bool apd_breakpoint ( int $debug_level )
This can be used to stop the running of your script, and await responses
on the connected socket. To step the program, just send enter (a blank
line), or enter a php command to be executed.
Parameters
debug_level
An integer which is formed by adding together the XXX_TRACE
constants.
It is not recommended to use MEMORY_TRACE. It is very slow and
does not appear to be accurate. ASSIGNMENT_TRACE is not
implemented yet.
To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY
(like strace -c)) use the value 99
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Typical session using tcplisten
bash#tcplisten localhost 7777
APD - Advanced PHP Debugger Trace File
---------------------------------------------------------------------------
Process Pid (6118)
Trace Begun at Sun Mar 10 23:13:12 2002
---------------------------------------------------------------------------
( 0.000000): apd_set_session_trace called at /home/alan/Projects/project2/test.
php:5
( 0.074824): apd_set_session_trace_socket() at /home/alan/Projects/project2/tes
t.php:5 returned. Elapsed (0.074824)
( 0.074918): apd_breakpoint() /home/alan/Projects/project2/test.php:7
++ argv[0] $(??) = 9
apd_breakpoint() at /home/alan/Projects/project2/test.php:7 returned. Elapsed (
-2089521468.1073275368)
>\n
statement: /home/alan/Projects/project2/test.php:8
>\n
statement: /home/alan/Projects/project2/test.php:8
>\n
statement: /home/alan/Projects/project2/test.php:10
>apd_echo($i);
EXEC: apd_echo($i);
0
>apd_echo(serialize(apd_get_active_symbols()));
EXEC: apd_echo(serialize(apd_get_active_symbols()));
a:47:{i:0;s:4:"PWD";i:1;s:10:"COLORFGBG";i:2;s:11:"XAUTHORITY";i:3;s:14:"
COLORTERM_BCE";i:4;s:9:"WINDOWID";i:5;s:14:"ETERM_VERSION";i:6;s:16:"SE
SSION_MANAGER";i:7;s:4:"PS1";i:8;s:11:"GDMSESSION";i:9;s:5:"USER";i:10;s:5:"
MAIL";i:11;s:7:"OLDPWD";i:12;s:5:"LANG";i:13;s:10:"COLORTERM";i:14;s:8:"DISP
LAY";i:15;s:8:"LOGNAME";i:16;s:6:"
>apd_echo(system('ls /home/mydir'));
........
>apd_continue(0);
----------------------------------------------------------------------
----------------------------------------------------------------------
apd_callstack
(PECL apd 0.2-0.4)
apd_callstack - Returns the current call stack as an array
Description
array apd_callstack ( void )
Returns the current call stack as an array
Return Values
An array containing the current call stack.
Examples
Example #1 apd_callstack() example
----------------------------------------------------------------------
----------------------------------------------------------------------
apd_clunk
(PECL apd 0.2-0.4)
apd_clunk - Throw a warning and a callstack
Description
void apd_clunk ( string $warning [, string $delimiter ] )
Behaves like perl's Carp::cluck. Throw a warning and a callstack.
Parameters
warning
The warning to throw.
delimiter
The delimiter. Default to .
Return Values
No value is returned.
Examples
Example #1 apd_clunk() example
");
?>
See Also
* apd_croak() - Throw an error, a callstack and then exit
----------------------------------------------------------------------
----------------------------------------------------------------------
apd_continue
(PECL apd >= 0.2)
apd_continue - Restarts the interpreter
Description
bool apd_continue ( int $debug_level )
Usually sent via the socket to restart the interpreter.
Parameters
debug_level
An integer which is formed by adding together the XXX_TRACE
constants.
It is not recommended to use MEMORY_TRACE. It is very slow and
does not appear to be accurate. ASSIGNMENT_TRACE is not
implemented yet.
To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY
(like strace -c)) use the value 99
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 apd_continue() example
----------------------------------------------------------------------
----------------------------------------------------------------------
apd_croak
(PECL apd 0.2-0.4)
apd_croak - Throw an error, a callstack and then exit
Description
void apd_croak ( string $warning [, string $delimiter ] )
Behaves like perl's Carp::croak. Throw an error, a callstack and then
exit.
Parameters
warning
The warning to throw.
delimiter
The delimiter. Default to .
Return Values
No value is returned.
Examples
Example #1 apd_croak() example
");
?>
See Also
* apd_clunk() - Throw a warning and a callstack
----------------------------------------------------------------------
----------------------------------------------------------------------
apd_dump_function_table
(Unknown)
apd_dump_function_table - Outputs the current function table
Description
void apd_dump_function_table ( void )
Outputs the current function table.
Return Values
No value is returned.
Examples
Example #1 apd_dump_function_table() example
----------------------------------------------------------------------
----------------------------------------------------------------------
apd_dump_persistent_resources
(PECL apd 0.2-0.4)
apd_dump_persistent_resources - Return all persistent resources as an
array
Description
array apd_dump_persistent_resources ( void )
Return all persistent resources as an array.
Return Values
An array containing the current call stack.
Examples
Example #1 apd_dump_persistent_resources() example
See Also
* apd_dump_regular_resources() - Return all current regular resources as
an array
----------------------------------------------------------------------
----------------------------------------------------------------------
apd_dump_regular_resources
(PECL apd 0.2-0.4)
apd_dump_regular_resources - Return all current regular resources as an
array
Description
array apd_dump_regular_resources ( void )
Return all current regular resources as an array.
Return Values
An array containing the current regular resources.
Examples
Example #1 apd_dump_regular_resources() example
See Also
* apd_dump_persistent_resources() - Return all persistent resources as
an array
----------------------------------------------------------------------
----------------------------------------------------------------------
apd_echo
(PECL apd >= 0.2)
apd_echo - Echo to the debugging socket
Description
bool apd_echo ( string $output )
Usually sent via the socket to request information about the running
script.
Parameters
output
The debugged variable.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 apd_echo() example
----------------------------------------------------------------------
----------------------------------------------------------------------
apd_get_active_symbols
(PECL apd 0.2)
apd_get_active_symbols - Get an array of the current variables names in
the local scope
Description
array apd_get_active_symbols ( void )
Returns the names of all the variables defined in the active scope, (not
their values).
Return Values
A multidimensional array with all the variables.
Examples
Example #1 apd_get_active_symbols() example
----------------------------------------------------------------------
----------------------------------------------------------------------
apd_set_pprof_trace
(PECL apd >= 0.2)
apd_set_pprof_trace - Starts the session debugging
Description
string apd_set_pprof_trace ([ string $dump_directory [, string $fragment =
"pprof" ]] )
Starts debugging to pprof_{process_id} in the dump directory.
Parameters
dump_directory
The directory in which the profile dump file is written. If not
set, the apd.dumpdir setting from the php.ini file is used.
fragment
Return Values
Returns path of the destination file.
Examples
Example #1 apd_set_pprof_trace() example
See Also
* apd_set_session_trace() - Starts the session debugging
----------------------------------------------------------------------
----------------------------------------------------------------------
apd_set_session_trace_socket
(PECL apd >= 0.2)
apd_set_session_trace_socket - Starts the remote session debugging
Description
bool apd_set_session_trace_socket ( string $tcp_server , int $socket_type
, int $port , int $debug_level )
Connects to the specified tcp_server (eg. tcplisten) and sends debugging
data to the socket.
Parameters
tcp_server
IP or Unix Domain socket (like a file) of the TCP server.
socket_type
Can be AF_UNIX for file based sockets or APD_AF_INET for standard
tcp/ip.
port
You can use any port, but higher numbers are better as most of the
lower numbers may be used by other system services.
debug_level
An integer which is formed by adding together the XXX_TRACE
constants.
It is not recommended to use MEMORY_TRACE. It is very slow and
does not appear to be accurate. ASSIGNMENT_TRACE is not
implemented yet.
To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY
(like strace -c)) use the value 99
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 apd_set_session_trace_socket() example
----------------------------------------------------------------------
----------------------------------------------------------------------
apd_set_session_trace
(PECL apd 0.2-0.4)
apd_set_session_trace - Starts the session debugging
Description
void apd_set_session_trace ( int $debug_level [, string $dump_directory ]
)
Starts debugging to apd_dump_{process_id} in the dump directory.
Parameters
debug_level
An integer which is formed by adding together the XXX_TRACE
constants.
It is not recommended to use MEMORY_TRACE. It is very slow and
does not appear to be accurate. ASSIGNMENT_TRACE is not
implemented yet.
To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY
(like strace -c)) use the value 99
dump_directory
The directory in which the profile dump file is written. If not
set, the apd.dumpdir setting from the php.ini file is used.
Return Values
No value is returned.
Examples
Example #1 apd_set_session_trace() example
----------------------------------------------------------------------
----------------------------------------------------------------------
apd_set_session
(PECL apd 0.2-0.4)
apd_set_session - Changes or sets the current debugging level
Description
void apd_set_session ( int $debug_level )
This can be used to increase or decrease debugging in a different area of
your application.
Parameters
debug_level
An integer which is formed by adding together the XXX_TRACE
constants.
It is not recommended to use MEMORY_TRACE. It is very slow and
does not appear to be accurate. ASSIGNMENT_TRACE is not
implemented yet.
To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY
(like strace -c)) use the value 99
Return Values
No value is returned.
Examples
Example #1 apd_set_session() example
----------------------------------------------------------------------
----------------------------------------------------------------------
override_function
(PECL apd >= 0.2)
override_function - Overrides built-in functions
Description
bool override_function ( string $function_name , string $function_args ,
string $function_code )
Overrides built-in functions by replacing them in the symbol table.
Parameters
function_name
The function to override.
function_args
The function arguments, as a comma separated string.
Usually you will want to pass this parameter, as well as the
function_code parameter, as a single quote delimited string. The
reason for using single quoted strings, is to protect the variable
names from parsing, otherwise, if you use double quotes there will
be a need to escape the variable names, e.g. \$your_var.
function_code
The new code for the function.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 override_function() example
----------------------------------------------------------------------
----------------------------------------------------------------------
rename_function
(PECL apd >= 0.2)
rename_function - Renames orig_name to new_name in the global function
table
Description
bool rename_function ( string $original_name , string $new_name )
Renames a orig_name to new_name in the global function table. Useful for
temporarily overriding built-in functions.
Parameters
original_name
The original function name.
new_name
The new name for the original_name function.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 rename_function() example
----------------------------------------------------------------------
Table of Contents
* apd_breakpoint - Stops the interpreter and waits on a CR from the
socket
* apd_callstack - Returns the current call stack as an array
* apd_clunk - Throw a warning and a callstack
* apd_continue - Restarts the interpreter
* apd_croak - Throw an error, a callstack and then exit
* apd_dump_function_table - Outputs the current function table
* apd_dump_persistent_resources - Return all persistent resources as an
array
* apd_dump_regular_resources - Return all current regular resources as
an array
* apd_echo - Echo to the debugging socket
* apd_get_active_symbols - Get an array of the current variables names
in the local scope
* apd_set_pprof_trace - Starts the session debugging
* apd_set_session_trace_socket - Starts the remote session debugging
* apd_set_session_trace - Starts the session debugging
* apd_set_session - Changes or sets the current debugging level
* override_function - Overrides built-in functions
* rename_function - Renames orig_name to new_name in the global function
table
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Building on Win32
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* How to use PHP-APD in your scripts
* APD Functions
* apd_breakpoint - Stops the interpreter and waits on a CR from the
socket
* apd_callstack - Returns the current call stack as an array
* apd_clunk - Throw a warning and a callstack
* apd_continue - Restarts the interpreter
* apd_croak - Throw an error, a callstack and then exit
* apd_dump_function_table - Outputs the current function table
* apd_dump_persistent_resources - Return all persistent resources
as an array
* apd_dump_regular_resources - Return all current regular resources
as an array
* apd_echo - Echo to the debugging socket
* apd_get_active_symbols - Get an array of the current variables
names in the local scope
* apd_set_pprof_trace - Starts the session debugging
* apd_set_session_trace_socket - Starts the remote session
debugging
* apd_set_session_trace - Starts the session debugging
* apd_set_session - Changes or sets the current debugging level
* override_function - Overrides built-in functions
* rename_function - Renames orig_name to new_name in the global
function table
----------------------------------------------------------------------
----------------------------------------------------------------------
PHP bytecode Compiler
----------------------------------------------------------------------
Introduction
Warning
This extension is EXPERIMENTAL. The behaviour of this extension including
the names of its functions and any other documentation surrounding this
extension may change without notice in a future release of PHP. This
extension should be used at your own risk.
Bcompiler was written for several reasons:
* To encode entire script in a proprietary PHP application
* To encode some classes and/or functions in a proprietary PHP
application
* To enable the production of php-gtk applications that could be used on
client desktops, without the need for a php.exe.
* To do the feasibility study for a PHP to C converter
The first of these goals is achieved using the bcompiler_write_header(),
bcompiler_write_file() and bcompiler_write_footer() functions. The
bytecode files can be written as either uncompressed or plain. To use the
generated bytecode, you can simply include it with include or require
statements.
The second of these goals is achieved using the bcompiler_write_header(),
bcompiler_write_class(), bcompiler_write_footer(), bcompiler_read(), and
bcompiler_load() functions. The bytecode files can be written as either
uncompressed or plain. The bcompiler_load() reads a bzip compressed
bytecode file, which tends to be 1/3 of the size of the original file.
To create EXE type files, bcompiler has to be used with a modified sapi
file or a version of PHP which has been compiled as a shared library. In
this scenario, bcompiler reads the compressed bytecode from the end of the
exe file.
bcompiler can improve performance by about 30% when used with uncompressed
bytecodes only. But keep in mind that uncompressed bytecode can be up to 5
times larger than the original source code. Using bytecode compression can
save your space, but decompression requires much more time than parsing a
source. bcompiler also does not do any bytecode optimization, this could
be added in the future...
In terms of code protection, it is safe to say that it would be impossible
to recreate the exact source code that it was built from, and without the
accompanying source code comments. It would effectively be useless to use
the bcompiler bytecodes to recreate and modify a class. However it is
possible to retrieve data from a bcompiled bytecode file - so don't put
your private passwords or anything in it.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
This >> PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here:
>> http://pecl.php.net/package/bcompiler.
A DLL for this PECL extension is currently unavailable. See also the
building on Windows section.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
This extension has no constants defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
bcompiler Functions
Contact Information
If you have comments, bugfixes, enhancements or want to help developing
this beast, you can drop me a mail at >> alan_k@php.net. Any help is very
welcome.
----------------------------------------------------------------------
bcompiler_load_exe
(PECL bcompiler >= 0.4)
bcompiler_load_exe - Reads and creates classes from a bcompiler exe file
Description
bool bcompiler_load_exe ( string $filename )
Reads data from a bcompiler exe file and creates classes from the
bytecodes.
Parameters
filename
The exe file path, as a string.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 bcompiler_load_exe() example
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* bcompiler_load() - Reads and creates classes from a bz compressed file
----------------------------------------------------------------------
----------------------------------------------------------------------
bcompiler_load
(PECL bcompiler >= 0.4)
bcompiler_load - Reads and creates classes from a bz compressed file
Description
bool bcompiler_load ( string $filename )
Reads data from a bzcompressed file and creates classes from the
bytecodes.
Parameters
filename
The bzcompressed file path, as a string.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 bcompiler_load() example
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Note:
Please use include or require statements to parse bytecodes, it's more
portable and convenient way than using this function.
Please note that this function won't execute script body code contained
in the bytecode file.
See Also
* bcompiler_load_exe() - Reads and creates classes from a bcompiler exe
file
----------------------------------------------------------------------
----------------------------------------------------------------------
bcompiler_parse_class
(PECL bcompiler >= 0.4)
bcompiler_parse_class - Reads the bytecodes of a class and calls back to a
user function
Description
bool bcompiler_parse_class ( string $class , string $callback )
Reads the bytecodes of a class and calls back to a user function.
Parameters
class
The class name, as a string.
callback
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 bcompiler_parse_class() example
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Note:
This function has been removed from bcompiler and is no longer available
as of bcompiler 0.5.
----------------------------------------------------------------------
----------------------------------------------------------------------
bcompiler_read
(PECL bcompiler >= 0.4)
bcompiler_read - Reads and creates classes from a filehandle
Description
bool bcompiler_read ( resource $filehandle )
Reads data from a open file handle and creates classes from the bytecodes.
Parameters
filehandle
A file handle as returned by fopen().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 bcompiler_read() example
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Note:
Please use include or require statements to parse bytecodes, it's more
portable and convenient way than using this function.
Please note that this function won't execute script body code contained
in the bytecode file.
----------------------------------------------------------------------
----------------------------------------------------------------------
bcompiler_write_class
(PECL bcompiler >= 0.4)
bcompiler_write_class - Writes an defined class as bytecodes
Description
bool bcompiler_write_class ( resource $filehandle , string $className [,
string $extends ] )
Reads the bytecodes from PHP for an existing class, and writes them to the
open file handle.
Parameters
filehandle
A file handle as returned by fopen().
className
The class name, as a string.
extends
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 bcompiler_write_class() example
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Note:
This function does not perform dependency checking, so make sure you
write the classes in an order that will not result in an undefined class
error occurring when you load it.
See Also
* bcompiler_write_header() - Writes the bcompiler header
* bcompiler_write_footer() - Writes the single character \x00 to
indicate End of compiled data
----------------------------------------------------------------------
----------------------------------------------------------------------
bcompiler_write_constant
(PECL bcompiler >= 0.5)
bcompiler_write_constant - Writes a defined constant as bytecodes
Description
bool bcompiler_write_constant ( resource $filehandle , string
$constantName )
Reads the bytecodes from PHP for an existing constant, and writes them to
the open file handle.
Parameters
filehandle
A file handle as returned by fopen().
constantName
The name of the defined constant, as a string.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 bcompiler_write_constant() example
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* bcompiler_write_header() - Writes the bcompiler header
* bcompiler_write_footer() - Writes the single character \x00 to
indicate End of compiled data
----------------------------------------------------------------------
----------------------------------------------------------------------
bcompiler_write_exe_footer
(PECL bcompiler >= 0.4)
bcompiler_write_exe_footer - Writes the start pos, and sig to the end of a
exe type file
Description
bool bcompiler_write_exe_footer ( resource $filehandle , int $startpos )
An EXE (or self executable) file consists of 3 parts:
* The stub (executable code, e.g. a compiled C program) that loads PHP
interpreter, bcompiler extension, stored Bytecodes and initiates a
call for the specified function (e.g. main) or class method (e.g.
main::main)
* The Bytecodes (uncompressed only for the moment)
* The bcompiler EXE footer
To obtain a suitable stub you can compile php_embed-based stub phpe.c
located in the examples/embed directory on bcompiler's CVS.
Parameters
filehandle
A file handle as returned by fopen().
startpos
The file position at which the Bytecodes start, and can be
obtained using ftell().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 bcompiler_write_exe_footer() example
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* bcompiler_write_header() - Writes the bcompiler header
* bcompiler_write_class() - Writes an defined class as bytecodes
* bcompiler_write_footer() - Writes the single character \x00 to
indicate End of compiled data
----------------------------------------------------------------------
----------------------------------------------------------------------
bcompiler_write_file
(PECL bcompiler >= 0.6)
bcompiler_write_file - Writes a php source file as bytecodes
Description
bool bcompiler_write_file ( resource $filehandle , string $filename )
This function complies specified source file into bytecodes, and writes
them to the open file handle.
Parameters
filehandle
A file handle as returned by fopen().
filename
The source file path, as a string.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 bcompiler_write_file() example
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* bcompiler_write_header() - Writes the bcompiler header
* bcompiler_write_footer() - Writes the single character \x00 to
indicate End of compiled data
----------------------------------------------------------------------
----------------------------------------------------------------------
bcompiler_write_footer
(PECL bcompiler >= 0.4)
bcompiler_write_footer - Writes the single character \x00 to indicate End
of compiled data
Description
bool bcompiler_write_footer ( resource $filehandle )
Writes the single character \x00 to indicate End of compiled data.
Parameters
filehandle
A file handle as returned by fopen().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 bcompiler_write_footer() example
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* bcompiler_write_header() - Writes the bcompiler header
----------------------------------------------------------------------
----------------------------------------------------------------------
bcompiler_write_function
(PECL bcompiler >= 0.5)
bcompiler_write_function - Writes an defined function as bytecodes
Description
bool bcompiler_write_function ( resource $filehandle , string
$functionName )
Reads the bytecodes from PHP for an existing function, and writes them to
the open file handle. Order is not important, (eg. if function b uses
function a, and you compile it like the example below, it will work
perfectly OK).
Parameters
filehandle
A file handle as returned by fopen().
functionName
The function name, as a string.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 bcompiler_write_function() example
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* bcompiler_write_header() - Writes the bcompiler header
* bcompiler_write_footer() - Writes the single character \x00 to
indicate End of compiled data
----------------------------------------------------------------------
----------------------------------------------------------------------
bcompiler_write_functions_from_file
(PECL bcompiler >= 0.5)
bcompiler_write_functions_from_file - Writes all functions defined in a
file as bytecodes
Description
bool bcompiler_write_functions_from_file ( resource $filehandle , string
$fileName )
Searches for all functions declared in the given file, and writes their
correspondent bytecodes to the open file handle.
Parameters
filehandle
A file handle as returned by fopen().
fileName
The file to be compiled. You must always include or require the
file you intend to compile.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 bcompiler_write_functions_from_file() example
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* bcompiler_write_header() - Writes the bcompiler header
* bcompiler_write_footer() - Writes the single character \x00 to
indicate End of compiled data
----------------------------------------------------------------------
----------------------------------------------------------------------
bcompiler_write_header
(PECL bcompiler >= 0.3)
bcompiler_write_header - Writes the bcompiler header
Description
bool bcompiler_write_header ( resource $filehandle [, string $write_ver ]
)
Writes the header part of a bcompiler file.
Parameters
filehandle
A file handle as returned by fopen().
write_ver
Can be used to write bytecode in a previously used format, so that
you can use it with older versions of bcompiler.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 bcompiler_write_header() example
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* bcompiler_write_footer() - Writes the single character \x00 to
indicate End of compiled data
----------------------------------------------------------------------
----------------------------------------------------------------------
bcompiler_write_included_filename
(PECL bcompiler >= 0.5)
bcompiler_write_included_filename - Writes an included file as bytecodes
Description
bool bcompiler_write_included_filename ( resource $filehandle , string
$filename )
Warning
This function is currently not documented; only its argument list is
available.
Return Values
Returns TRUE on success or FALSE on failure.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
Table of Contents
* bcompiler_load_exe - Reads and creates classes from a bcompiler exe
file
* bcompiler_load - Reads and creates classes from a bz compressed file
* bcompiler_parse_class - Reads the bytecodes of a class and calls back
to a user function
* bcompiler_read - Reads and creates classes from a filehandle
* bcompiler_write_class - Writes an defined class as bytecodes
* bcompiler_write_constant - Writes a defined constant as bytecodes
* bcompiler_write_exe_footer - Writes the start pos, and sig to the end
of a exe type file
* bcompiler_write_file - Writes a php source file as bytecodes
* bcompiler_write_footer - Writes the single character \x00 to indicate
End of compiled data
* bcompiler_write_function - Writes an defined function as bytecodes
* bcompiler_write_functions_from_file - Writes all functions defined in
a file as bytecodes
* bcompiler_write_header - Writes the bcompiler header
* bcompiler_write_included_filename - Writes an included file as
bytecodes
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* bcompiler Functions
* bcompiler_load_exe - Reads and creates classes from a bcompiler
exe file
* bcompiler_load - Reads and creates classes from a bz compressed
file
* bcompiler_parse_class - Reads the bytecodes of a class and calls
back to a user function
* bcompiler_read - Reads and creates classes from a filehandle
* bcompiler_write_class - Writes an defined class as bytecodes
* bcompiler_write_constant - Writes a defined constant as bytecodes
* bcompiler_write_exe_footer - Writes the start pos, and sig to the
end of a exe type file
* bcompiler_write_file - Writes a php source file as bytecodes
* bcompiler_write_footer - Writes the single character \x00 to
indicate End of compiled data
* bcompiler_write_function - Writes an defined function as
bytecodes
* bcompiler_write_functions_from_file - Writes all functions
defined in a file as bytecodes
* bcompiler_write_header - Writes the bcompiler header
* bcompiler_write_included_filename - Writes an included file as
bytecodes
----------------------------------------------------------------------
----------------------------------------------------------------------
Error Handling and Logging
----------------------------------------------------------------------
Introduction
These are functions dealing with error handling and logging. They allow
you to define your own error handling rules, as well as modify the way the
errors can be logged. This allows you to change and enhance error
reporting to suit your needs.
With the logging functions, you can send messages directly to other
machines, to an email (or email to pager gateway!), to system logs, etc.,
so you can selectively log and monitor the most important parts of your
applications and websites.
The error reporting functions allow you to customize what level and kind
of error feedback is given, ranging from simple notices to customized
functions returned during errors.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
There is no installation needed to use these functions; they are part of
the PHP core.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Errors and Logging Configuration Options
Name Default Changeable Changelog
error_reporting NULL PHP_INI_ALL
display_errors "1" PHP_INI_ALL
display_startup_errors "0" PHP_INI_ALL
log_errors "0" PHP_INI_ALL
log_errors_max_len "1024" PHP_INI_ALL Available since PHP 4.3.0.
ignore_repeated_errors "0" PHP_INI_ALL Available since PHP 4.3.0.
ignore_repeated_source "0" PHP_INI_ALL Available since PHP 4.3.0.
report_memleaks "1" PHP_INI_ALL Available since PHP 4.3.0.
track_errors "0" PHP_INI_ALL
html_errors "1" PHP_INI_ALL PHP_INI_SYSTEM in PHP <=
4.2.3.
xmlrpc_errors "0" PHP_INI_SYSTEM Available since PHP 4.1.0.
xmlrpc_error_number "0" PHP_INI_ALL Available since PHP 4.1.0.
docref_root "" PHP_INI_ALL Available since PHP 4.3.0.
docref_ext "" PHP_INI_ALL Available since PHP 4.3.2.
error_prepend_string NULL PHP_INI_ALL
error_append_string NULL PHP_INI_ALL
error_log NULL PHP_INI_ALL
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
error_reporting integer
Set the error reporting level. The parameter is either an integer
representing a bit field, or named constants. The error_reporting
levels and constants are described in Predefined Constants, and in
php.ini. To set at runtime, use the error_reporting() function.
See also the display_errors directive.
In PHP 4 and PHP 5 the default value is E_ALL & ~E_NOTICE. This
setting does not show E_NOTICE level errors. You may want to show
them during development.
Note:
Enabling E_NOTICE during development has some benefits. For
debugging purposes: NOTICE messages will warn you about possible
bugs in your code. For example, use of unassigned values is
warned. It is extremely useful to find typos and to save time
for debugging. NOTICE messages will warn you about bad style.
For example, $arr[item] is better to be written as $arr['item']
since PHP tries to treat "item" as constant. If it is not a
constant, PHP assumes it is a string index for the array.
Note:
In PHP 5 a new error level E_STRICT is available. As E_STRICT is
not included within E_ALL you have to explicitly enable this
kind of error level. Enabling E_STRICT during development has
some benefits. STRICT messages will help you to use the latest
and greatest suggested method of coding, for example warn you
about using deprecated functions.
Note: PHP Constants outside of PHP
Using PHP Constants outside of PHP, like in httpd.conf, will
have no useful meaning so in such cases the integer values are
required. And since error levels will be added over time, the
maximum value (for E_ALL) will likely change. So in place of
E_ALL consider using a larger value to cover all bit fields from
now and well into the future, a numeric value like 2147483647
(includes all errors, not just E_ALL).
display_errors string
This determines whether errors should be printed to the screen as
part of the output or if they should be hidden from the user.
Value "stderr" sends the errors to stderr instead of stdout. The
value is available as of PHP 5.2.4. In earlier versions, this
directive was of type boolean.
Note:
This is a feature to support your development and should never
be used on production systems (e.g. systems connected to the
internet).
Note:
Although display_errors may be set at runtime (with ini_set()),
it won't have any affect if the script has fatal errors. This is
because the desired runtime action does not get executed.
display_startup_errors boolean
Even when display_errors is on, errors that occur during PHP's
startup sequence are not displayed. It's strongly recommended to
keep display_startup_errors off, except for debugging.
log_errors boolean
Tells whether script error messages should be logged to the
server's error log or error_log. This option is thus
server-specific.
Note:
You're strongly advised to use error logging in place of error
displaying on production web sites.
log_errors_max_len integer
Set the maximum length of log_errors in bytes. In error_log
information about the source is added. The default is 1024 and 0
allows to not apply any maximum length at all. This length is
applied to logged errors, displayed errors and also to
$php_errormsg.
When an integer is used, the value is measured in bytes. Shorthand
notation, as described in this FAQ, may also be used.
ignore_repeated_errors boolean
Do not log repeated messages. Repeated errors must occur in the
same file on the same line unless ignore_repeated_source is set
true.
ignore_repeated_source boolean
Ignore source of message when ignoring repeated messages. When
this setting is On you will not log errors with repeated messages
from different files or sourcelines.
report_memleaks boolean
If this parameter is set to On (the default), this parameter will
show a report of memory leaks detected by the Zend memory manager.
This report will be send to stderr on Posix platforms. On Windows,
it will be send to the debugger using OutputDebugString(), and can
be viewed with tools like >> DbgView. This parameter only has
effect in a debug build, and if error_reporting includes E_WARNING
in the allowed list.
track_errors boolean
If enabled, the last error message will always be present in the
variable $php_errormsg.
html_errors boolean
Turn off HTML tags in error messages. The new format for HTML
errors produces clickable messages that direct the user to a page
describing the error or function in causing the error. These
references are affected by docref_root and docref_ext.
xmlrpc_errors boolean
Turns off normal error reporting and formats errors as XML-RPC
error message.
xmlrpc_error_number integer
Used as the value of the XML-RPC faultCode element.
docref_root string
The new error format contains a reference to a page describing the
error or function causing the error. In case of manual pages you
can download the manual in your language and set this ini
directive to the URL of your local copy. If your local copy of the
manual can be reached by "/manual/" you can simply use
docref_root=/manual/. Additional you have to set docref_ext to
match the fileextensions of your copy docref_ext=.html. It is
possible to use external references. For example you can use
docref_root=http://manual/en/ or
docref_root="http://landonize.it/?how=url&theme=classic&filter=Landon
&url=http%3A%2F%2Fwww.php.net%2F"
Most of the time you want the docref_root value to end with a
slash "/". But see the second example above which does not have
nor need it.
Note:
This is a feature to support your development since it makes it
easy to lookup a function description. However it should never
be used on production systems (e.g. systems connected to the
internet).
docref_ext string
See docref_root.
Note:
The value of docref_ext must begin with a dot ".".
error_prepend_string string
String to output before an error message.
error_append_string string
String to output after an error message.
error_log string
Name of the file where script errors should be logged. The file
should be writable by the web server's user. If the special value
syslog is used, the errors are sent to the system logger instead.
On Unix, this means syslog(3) and on Windows NT it means the event
log. The system logger is not supported on Windows 95. See also:
syslog(). If this directive is not set, errors are sent to the
SAPI error logger. For example, it is an error log in Apache or
stderr in CLI.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are always available as part of the PHP core.
Note: You may use these constant names in php.ini but not outside of
PHP, like in httpd.conf, where you'd use the bitmask values instead.
Errors and Logging
Value Constant Description Note
Fatal run-time errors. These
indicate errors that can not
1 E_ERROR (integer) be recovered from, such as a
memory allocation problem.
Execution of the script is
halted.
Run-time warnings (non-fatal
2 E_WARNING (integer) errors). Execution of the
script is not halted.
Compile-time parse errors.
4 E_PARSE (integer) Parse errors should only be
generated by the parser.
Run-time notices. Indicate
that the script encountered
8 E_NOTICE (integer) something that could indicate
an error, but could also
happen in the normal course
of running a script.
Fatal errors that occur
during PHP's initial startup.
16 E_CORE_ERROR (integer) This is like an E_ERROR, since PHP 4
except it is generated by the
core of PHP.
Warnings (non-fatal errors)
E_CORE_WARNING that occur during PHP's
32 (integer) initial startup. This is like since PHP 4
an E_WARNING, except it is
generated by the core of PHP.
Fatal compile-time errors.
64 E_COMPILE_ERROR This is like an E_ERROR, since PHP 4
(integer) except it is generated by the
Zend Scripting Engine.
Compile-time warnings
E_COMPILE_WARNING (non-fatal errors). This is
128 (integer) like an E_WARNING, except it since PHP 4
is generated by the Zend
Scripting Engine.
User-generated error message.
This is like an E_ERROR,
256 E_USER_ERROR (integer) except it is generated in PHP since PHP 4
code by using the PHP
function trigger_error().
User-generated warning
message. This is like an
512 E_USER_WARNING E_WARNING, except it is since PHP 4
(integer) generated in PHP code by
using the PHP function
trigger_error().
User-generated notice
message. This is like an
1024 E_USER_NOTICE (integer) E_NOTICE, except it is since PHP 4
generated in PHP code by
using the PHP function
trigger_error().
Enable to have PHP suggest
changes to your code which
2048 E_STRICT (integer) will ensure the best since PHP 5
interoperability and forward
compatibility of your code.
Catchable fatal error. It
indicates that a probably
dangerous error occured, but
did not leave the Engine in
4096 E_RECOVERABLE_ERROR an unstable state. If the since PHP
(integer) error is not caught by a user 5.2.0
defined handle (see also
set_error_handler()), the
application aborts as it was
an E_ERROR.
Run-time notices. Enable this
8192 E_DEPRECATED (integer) to receive warnings about since PHP
code that will not work in 5.3.0
future versions.
User-generated warning
message. This is like an
16384 E_USER_DEPRECATED E_DEPRECATED, except it is since PHP
(integer) generated in PHP code by 5.3.0
using the PHP function
trigger_error().
30719 in PHP
All errors and warnings, as 5.3.x, 6143 in
30719 E_ALL (integer) supported, except of level PHP 5.2.x,
E_STRICT. 2047
previously
The above values (either numerical or symbolic) are used to build up a
bitmask that specifies which errors to report. You can use the bitwise
operators to combine these values or mask out certain types of errors.
Note that only '|', '~', '!', '^' and '&' will be understood within
php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Below we can see an example of using the error handling capabilities in
PHP. We define an error handling function which logs the information into
a file (using an XML format), and e-mails the developer in case a critical
error in the logic happens.
Example #1 Using error handling in a script
'Error',
E_WARNING => 'Warning',
E_PARSE => 'Parsing Error',
E_NOTICE => 'Notice',
E_CORE_ERROR => 'Core Error',
E_CORE_WARNING => 'Core Warning',
E_COMPILE_ERROR => 'Compile Error',
E_COMPILE_WARNING => 'Compile Warning',
E_USER_ERROR => 'User Error',
E_USER_WARNING => 'User Warning',
E_USER_NOTICE => 'User Notice',
E_STRICT => 'Runtime Notice',
E_RECOVERABLE_ERROR => 'Catchable Fatal Error'
);
// set of errors for which a var trace will be saved
$user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);
$err = "\n";
$err .= "\t" . $dt . " \n";
$err .= "\t" . $errno . " \n";
$err .= "\t" . $errortype[$errno] . " \n";
$err .= "\t" . $errmsg . " \n";
$err .= "\t" . $filename . " \n";
$err .= "\t" . $linenum . " \n";
if (in_array($errno, $user_errors)) {
$err .= "\t" . wddx_serialize_value($vars, "Variables") . " \n";
}
$err .= " \n\n";
// for testing
// echo $err;
// save to the error log, and e-mail me if there is a critical user error
error_log($err, 3, "/usr/local/php4/error.log");
if ($errno == E_USER_ERROR) {
mail("phpdev@example.com", "Critical User Error", $err);
}
}
function distance($vect1, $vect2)
{
if (!is_array($vect1) || !is_array($vect2)) {
trigger_error("Incorrect parameters, arrays expected", E_USER_ERROR);
return NULL;
}
if (count($vect1) != count($vect2)) {
trigger_error("Vectors need to be of the same size", E_USER_ERROR);
return NULL;
}
for ($i=0; $i
----------------------------------------------------------------------
----------------------------------------------------------------------
Error Handling Functions
See Also
See also syslog().
----------------------------------------------------------------------
debug_backtrace
(PHP 4 >= 4.3.0, PHP 5)
debug_backtrace - Generates a backtrace
Description
array debug_backtrace ([ int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT [,
int $limit = 0 ]] )
debug_backtrace() generates a PHP backtrace.
Parameters
options
As of 5.3.6, this parameter is a bitmask for the following
options:
debug_backtrace() options
DEBUG_BACKTRACE_PROVIDE_OBJECT Whether or not to populate the
"object" index.
Whether or not to omit the "args"
DEBUG_BACKTRACE_IGNORE_ARGS index, and thus all the
function/method arguments, to save
memory.
Before 5.3.6, the only values recognized are TRUE or FALSE, which
are the same as setting or not setting the
DEBUG_BACKTRACE_PROVIDE_OBJECT option respectively.
limit
As of 5.4.0, this parameter can be used to limit the number of
stack frames returned. By default (limit=0) it returns all stack
frames.
Return Values
Returns an array of associative arrays. The possible returned elements are
as follows:
Possible returned elements from debug_backtrace()
Name Type Description
function string The current function name. See also __FUNCTION__.
line integer The current line number. See also __LINE__.
file string The current file name. See also __FILE__.
class string The current class name. See also __CLASS__
object object The current object.
The current call type. If a method call, "->" is
type string returned. If a static method call, "::" is returned. If a
function call, nothing is returned.
If inside a function, this lists the functions arguments.
args array If inside an included file, this lists the included file
name(s).
Changelog
Version Description
5.4.0 Added the optional parameter limit.
5.3.6 The parameter provide_object changed to options and additional
option DEBUG_BACKTRACE_IGNORE_ARGS is added.
5.2.5 Added the optional parameter provide_object.
5.1.1 Added the current object as a possible return element.
Examples
Example #1 debug_backtrace() example
Results similar to the following when executing /tmp/b.php:
Hi: friend
array(2) {
[0]=>
array(4) {
["file"] => string(10) "/tmp/a.php"
["line"] => int(10)
["function"] => string(6) "a_test"
["args"]=>
array(1) {
[0] => &string(6) "friend"
}
}
[1]=>
array(4) {
["file"] => string(10) "/tmp/b.php"
["line"] => int(2)
["args"] =>
array(1) {
[0] => string(10) "/tmp/a.php"
}
["function"] => string(12) "include_once"
}
}
See Also
* trigger_error() - Generates a user-level error/warning/notice message
* debug_print_backtrace() - Prints a backtrace
----------------------------------------------------------------------
----------------------------------------------------------------------
debug_print_backtrace
(PHP 5)
debug_print_backtrace - Prints a backtrace
Description
void debug_print_backtrace ([ int $options = 0 [, int $limit = 0 ]] )
debug_print_backtrace() prints a PHP backtrace. It prints the function
calls, included/required files and eval()ed stuff.
Parameters
options
As of 5.3.6, this parameter is a bitmask for the following
options:
debug_print_backtrace() options
Whether or not to omit the "args"
DEBUG_BACKTRACE_IGNORE_ARGS index, and thus all the
function/method arguments, to save
memory.
limit
As of 5.4.0, this parameter can be used to limit the number of
stack frames printed. By default (limit=0) it prints all stack
frames.
Return Values
No value is returned.
Changelog
Version Description
5.4.0 Added the optional parameter limit.
5.3.6 Added the optional parameter options.
Examples
Example #1 debug_print_backtrace() example
The above example will output something similar to:
#0 c() called at [/tmp/include.php:10]
#1 b() called at [/tmp/include.php:6]
#2 a() called at [/tmp/include.php:17]
#3 include(/tmp/include.php) called at [/tmp/test.php:3]
See Also
* debug_backtrace() - Generates a backtrace
----------------------------------------------------------------------
----------------------------------------------------------------------
error_get_last
(PHP 5 >= 5.2.0)
error_get_last - Get the last occurred error
Description
array error_get_last ( void )
Gets information about the last error that occurred.
Return Values
Returns an associative array describing the last error with keys "type",
"message", "file" and "line". If the error has been caused by a PHP
internal function then the "message" begins with its name. Returns NULL if
there hasn't been an error yet.
Examples
Example #1 An error_get_last() example
The above example will output something similar to:
Array
(
[type] => 8
[message] => Undefined variable: a
[file] => C:\WWW\index.php
[line] => 2
)
See Also
* Error constants
* Variable $php_errormsg
* Directive display_errors
* Directive html_errors
* Directive xmlrpc_errors
----------------------------------------------------------------------
----------------------------------------------------------------------
error_log
(PHP 4, PHP 5)
error_log - Send an error message somewhere
Description
bool error_log ( string $message [, int $message_type = 0 [, string
$destination [, string $extra_headers ]]] )
Sends an error message to the web server's error log or to a file.
Parameters
message
The error message that should be logged.
message_type
Says where the error should go. The possible message types are as
follows:
error_log() log types
message is sent to PHP's system logger, using the Operating
0 System's system logging mechanism or a file, depending on what
the error_log configuration directive is set to. This is the
default option.
message is sent by email to the address in the destination
1 parameter. This is the only message type where the fourth
parameter, extra_headers is used.
2 No longer an option.
3 message is appended to the file destination. A newline is not
automatically added to the end of the message string.
4 message is sent directly to the SAPI logging handler.
destination
The destination. Its meaning depends on the message_type parameter
as described above.
extra_headers
The extra headers. It's used when the message_type parameter is
set to 1. This message type uses the same internal function as
mail() does.
Return Values
Returns TRUE on success or FALSE on failure.
Changelog
Version Description
5.2.7 The possible value of 4 was added to message_type.
Examples
Example #1 error_log() examples
----------------------------------------------------------------------
----------------------------------------------------------------------
error_reporting
(PHP 4, PHP 5)
error_reporting - Sets which PHP errors are reported
Description
int error_reporting ([ int $level ] )
The error_reporting() function sets the error_reporting directive at
runtime. PHP has many levels of errors, using this function sets that
level for the duration (runtime) of your script. If the optional level is
not set, error_reporting() will just return the current error reporting
level.
Parameters
level
The new error_reporting level. It takes on either a bitmask, or
named constants. Using named constants is strongly encouraged to
ensure compatibility for future versions. As error levels are
added, the range of integers increases, so older integer-based
error levels will not always behave as expected.
The available error level constants and the actual meanings of
these error levels are described in the predefined constants.
Return Values
Returns the old error_reporting level or the current level if no level
parameter is given.
Changelog
Version Description
5.0.0 E_STRICT introduced (not part of E_ALL).
5.2.0 E_RECOVERABLE_ERROR introduced.
5.3.0 E_DEPRECATED and E_USER_DEPRECATED introduced.
Examples
Example #1 error_reporting() examples
Notes
Warning
Most of E_STRICT errors are evaluated at the compile time thus such errors
are not reported in the file where error_reporting is enhanced to include
E_STRICT errors (and vice versa).
Tip
Passing in the value -1 will show every possible error, even when new
levels and constants are added in future PHP versions.
See Also
* The display_errors directive
* The html_errors directive
* The xmlrpc_errors directive
* ini_set() - Sets the value of a configuration option
----------------------------------------------------------------------
----------------------------------------------------------------------
restore_error_handler
(PHP 4 >= 4.0.1, PHP 5)
restore_error_handler - Restores the previous error handler function
Description
bool restore_error_handler ( void )
Used after changing the error handler function using set_error_handler(),
to revert to the previous error handler (which could be the built-in or a
user defined function).
Return Values
This function always returns TRUE.
Examples
Example #1 restore_error_handler() example
Decide if unserialize() caused an error, then restore the original error
handler.
The above example will output:
Invalid serialized value.
Notes
Note:
Calling restore_error_handler() from the error_handler function is
ignored.
See Also
* error_reporting() - Sets which PHP errors are reported
* set_error_handler() - Sets a user-defined error handler function
* restore_exception_handler() - Restores the previously defined
exception handler function
* trigger_error() - Generates a user-level error/warning/notice message
----------------------------------------------------------------------
----------------------------------------------------------------------
restore_exception_handler
(PHP 5)
restore_exception_handler - Restores the previously defined exception
handler function
Description
bool restore_exception_handler ( void )
Used after changing the exception handler function using
set_exception_handler(), to revert to the previous exception handler
(which could be the built-in or a user defined function).
Return Values
This function always returns TRUE.
Examples
Example #1 restore_exception_handler() example
getMessage();
}
function exception_handler_2(Exception $e)
{
echo '[' . __FUNCTION__ . '] ' . $e->getMessage();
}
set_exception_handler('exception_handler_1');
set_exception_handler('exception_handler_2');
restore_exception_handler();
throw new Exception('This triggers the first exception handler...');
?>
The above example will output:
[exception_handler_1] This triggers the first exception handler...
See Also
* set_exception_handler() - Sets a user-defined exception handler
function
* set_error_handler() - Sets a user-defined error handler function
* restore_error_handler() - Restores the previous error handler function
* error_reporting() - Sets which PHP errors are reported
----------------------------------------------------------------------
----------------------------------------------------------------------
set_error_handler
(PHP 4 >= 4.0.1, PHP 5)
set_error_handler - Sets a user-defined error handler function
Description
mixed set_error_handler ( callback $error_handler [, int $error_types =
E_ALL | E_STRICT ] )
Sets a user function (error_handler) to handle errors in a script.
This function can be used for defining your own way of handling errors
during runtime, for example in applications in which you need to do
cleanup of data/files when a critical error happens, or when you need to
trigger an error under certain conditions (using trigger_error()).
It is important to remember that the standard PHP error handler is
completely bypassed for the error types specified by error_types unless
the callback function returns FALSE. error_reporting() settings will have
no effect and your error handler will be called regardless - however you
are still able to read the current value of error_reporting and act
appropriately. Of particular note is that this value will be 0 if the
statement that caused the error was prepended by the @ error-control
operator.
Also note that it is your responsibility to die() if necessary. If the
error-handler function returns, script execution will continue with the
next statement after the one that caused an error.
The following error types cannot be handled with a user defined function:
E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR,
E_COMPILE_WARNING, and most of E_STRICT raised in the file where
set_error_handler() is called.
If errors occur before the script is executed (e.g. on file uploads) the
custom error handler cannot be called since it is not registered at that
time.
Parameters
error_handler
The user function needs to accept two parameters: the error code,
and a string describing the error. Then there are three optional
parameters that may be supplied: the filename in which the error
occurred, the line number in which the error occurred, and the
context in which the error occurred (an array that points to the
active symbol table at the point the error occurred). The function
can be shown as:
handler ( int $errno , string $errstr [, string $errfile [, int
$errline [, array $errcontext ]]] )
errno
The first parameter, errno, contains the level of the
error raised, as an integer.
errstr
The second parameter, errstr, contains the error
message, as a string.
errfile
The third parameter is optional, errfile, which
contains the filename that the error was raised in,
as a string.
errline
The fourth parameter is optional, errline, which
contains the line number the error was raised at, as
an integer.
errcontext
The fifth parameter is optional, errcontext, which is
an array that points to the active symbol table at
the point the error occurred. In other words,
errcontext will contain an array of every variable
that existed in the scope the error was triggered in.
User error handler must not modify error context.
If the function returns FALSE then the normal error handler
continues.
error_types
Can be used to mask the triggering of the error_handler function
just like the error_reporting ini setting controls which errors
are shown. Without this mask set the error_handler will be called
for every error regardless to the setting of the error_reporting
setting.
Return Values
Returns a string containing the previously defined error handler (if any).
If the built-in error handler is used NULL is returned. NULL is also
returned in case of an error such as an invalid callback. If the previous
error handler was a class method, this function will return an indexed
array with the class and the method name.
Changelog
Version Description
5.2.0 The error handler must return FALSE to populate $php_errormsg.
5.0.0 The error_types parameter was introduced.
Instead of a function name, an array containing an object
4.3.0 reference and a method name can also be supplied as the
error_handler.
Three optional parameters for the error_handler user function was
4.0.2 introduced. These are the filename, the line number, and the
context.
Examples
Example #1 Error handling with set_error_handler() and trigger_error()
The example below shows the handling of internal exceptions by triggering
errors and handling them with a user defined function:
My ERROR [$errno] $errstr \n";
echo " Fatal error on line $errline in file $errfile";
echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ") \n";
echo "Aborting... \n";
exit(1);
break;
case E_USER_WARNING:
echo "My WARNING [$errno] $errstr \n";
break;
case E_USER_NOTICE:
echo "My NOTICE [$errno] $errstr \n";
break;
default:
echo "Unknown error type: [$errno] $errstr \n";
break;
}
/* Don't execute PHP internal error handler */
return true;
}
// function to test the error handling
function scale_by_log($vect, $scale)
{
if (!is_numeric($scale) || $scale <= 0) {
trigger_error("log(x) for x <= 0 is undefined, you used: scale = $scale", E_USER_ERROR);
}
if (!is_array($vect)) {
trigger_error("Incorrect input vector, array of values expected", E_USER_WARNING);
return null;
}
$temp = array();
foreach($vect as $pos => $value) {
if (!is_numeric($value)) {
trigger_error("Value at position $pos is not a number, using 0 (zero)", E_USER_NOTICE);
$value = 0;
}
$temp[$pos] = log($scale) * $value;
}
return $temp;
}
// set to the user defined error handler
$old_error_handler = set_error_handler("myErrorHandler");
// trigger some errors, first define a mixed array with a non-numeric item
echo "vector a\n";
$a = array(2, 3, "foo", 5.5, 43.3, 21.11);
print_r($a);
// now generate second array
echo "----\nvector b - a notice (b = log(PI) * a)\n";
/* Value at position $pos is not a number, using 0 (zero) */
$b = scale_by_log($a, M_PI);
print_r($b);
// this is trouble, we pass a string instead of an array
echo "----\nvector c - a warning\n";
/* Incorrect input vector, array of values expected */
$c = scale_by_log("not array", 2.3);
var_dump($c); // NULL
// this is a critical error, log of zero or negative number is undefined
echo "----\nvector d - fatal error\n";
/* log(x) for x <= 0 is undefined, you used: scale = $scale" */
$d = scale_by_log($a, -2.5);
var_dump($d); // Never reached
?>
The above example will output something similar to:
vector a
Array
(
[0] => 2
[1] => 3
[2] => foo
[3] => 5.5
[4] => 43.3
[5] => 21.11
)
----
vector b - a notice (b = log(PI) * a)
My NOTICE [1024] Value at position 2 is not a number, using 0 (zero)
Array
(
[0] => 2.2894597716988
[1] => 3.4341896575482
[2] => 0
[3] => 6.2960143721717
[4] => 49.566804057279
[5] => 24.165247890281
)
----
vector c - a warning
My WARNING [512] Incorrect input vector, array of values expected
NULL
----
vector d - fatal error
My ERROR [256] log(x) for x <= 0 is undefined, you used: scale = -2.5
Fatal error on line 35 in file trigger_error.php, PHP 5.2.1 (FreeBSD)
Aborting...
See Also
* ErrorException
* error_reporting() - Sets which PHP errors are reported
* restore_error_handler() - Restores the previous error handler function
* trigger_error() - Generates a user-level error/warning/notice message
* error level constants
* information about the callback type
----------------------------------------------------------------------
----------------------------------------------------------------------
set_exception_handler
(PHP 5)
set_exception_handler - Sets a user-defined exception handler function
Description
callback set_exception_handler ( callback $exception_handler )
Sets the default exception handler if an exception is not caught within a
try/catch block. Execution will stop after the exception_handler is
called.
Parameters
exception_handler
Name of the function to be called when an uncaught exception
occurs. This function must be defined before calling
set_exception_handler(). This handler function needs to accept one
parameter, which will be the exception object that was thrown.
Return Values
Returns the name of the previously defined exception handler, or NULL on
error. If no previous handler was defined, NULL is also returned.
Examples
Example #1 set_exception_handler() example
getMessage(), "\n";
}
set_exception_handler('exception_handler');
throw new Exception('Uncaught Exception');
echo "Not Executed\n";
?>
See Also
* restore_exception_handler() - Restores the previously defined
exception handler function
* restore_error_handler() - Restores the previous error handler function
* error_reporting() - Sets which PHP errors are reported
* information about the callback type
* PHP 5 Exceptions
----------------------------------------------------------------------
----------------------------------------------------------------------
trigger_error
(PHP 4 >= 4.0.1, PHP 5)
trigger_error - Generates a user-level error/warning/notice message
Description
bool trigger_error ( string $error_msg [, int $error_type = E_USER_NOTICE
] )
Used to trigger a user error condition, it can be used by in conjunction
with the built-in error handler, or with a user defined function that has
been set as the new error handler (set_error_handler()).
This function is useful when you need to generate a particular response to
an exception at runtime.
Parameters
error_msg
The designated error message for this error. It's limited to 1024
characters in length. Any additional characters beyond 1024 will
be truncated.
error_type
The designated error type for this error. It only works with the
E_USER family of constants, and will default to E_USER_NOTICE.
Return Values
This function returns FALSE if wrong error_type is specified, TRUE
otherwise.
Examples
Example #1 trigger_error() example
See set_error_handler() for a more extensive example.
Notes
Warning
HTML entities in error_msg are not escaped. Use htmlentities() on the
message if the error is to be displayed in a browser.
See Also
* error_reporting() - Sets which PHP errors are reported
* set_error_handler() - Sets a user-defined error handler function
* restore_error_handler() - Restores the previous error handler function
* The error level constants
----------------------------------------------------------------------
----------------------------------------------------------------------
user_error
(PHP 4, PHP 5)
user_error - Alias of trigger_error()
Description
This function is an alias of: trigger_error().
----------------------------------------------------------------------
Table of Contents
* debug_backtrace - Generates a backtrace
* debug_print_backtrace - Prints a backtrace
* error_get_last - Get the last occurred error
* error_log - Send an error message somewhere
* error_reporting - Sets which PHP errors are reported
* restore_error_handler - Restores the previous error handler function
* restore_exception_handler - Restores the previously defined exception
handler function
* set_error_handler - Sets a user-defined error handler function
* set_exception_handler - Sets a user-defined exception handler function
* trigger_error - Generates a user-level error/warning/notice message
* user_error - Alias of trigger_error
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* Error Handling Functions
* debug_backtrace - Generates a backtrace
* debug_print_backtrace - Prints a backtrace
* error_get_last - Get the last occurred error
* error_log - Send an error message somewhere
* error_reporting - Sets which PHP errors are reported
* restore_error_handler - Restores the previous error handler
function
* restore_exception_handler - Restores the previously defined
exception handler function
* set_error_handler - Sets a user-defined error handler function
* set_exception_handler - Sets a user-defined exception handler
function
* trigger_error - Generates a user-level error/warning/notice
message
* user_error - Alias of trigger_error
----------------------------------------------------------------------
----------------------------------------------------------------------
htaccess-like support for all SAPIs
----------------------------------------------------------------------
Introduction
The htscanner extension gives the possibility to use htaccess-like file to
configure PHP per directory, just like apache's htaccess. It is especially
useful with fastcgi (ISS5/6/7, lighttpd, etc.).
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
PHP version 5.2.0 or greater.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here: >> http://pecl.php.net/package/htscanner
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
htscanner Configure Options
Name Default Changeable Changelog
htscanner.config_file ".htscanner" PHP_INI_SYSTEM
htscanner.default_docroot "/" PHP_INI_SYSTEM
htscanner.default_ttl "300" PHP_INI_SYSTEM
htscanner."stop_on_error" "Off" PHP_INI_SYSTEM
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
htscanner.config_file string
Filename to use as configuration file.
htscanner.default_docroot string
Default document root.
htscanner.default_ttl int
Cache time out for the configuration data, in seconds.
htscanner.stop_on_error int
Stop on error (parse error, cannot set an ini setting).
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
----------------------------------------------------------------------
Inclusion hierarchy viewer
----------------------------------------------------------------------
Introduction
Traces through and dumps the hierarchy of file inclusions and class
inheritance at runtime.
The files may have been included using include(), include_once(),
require(), or require_once().
Class inheritance dependencies are also reported.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
PHP version 5.1.0 or greater.
The included gengraph.php file utilizes the >> graphviz library, however,
this is not required.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here: >> http://pecl.php.net/package/inclued
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
inclued Configure Options
Name Default Changeable Changelog
inclued.enabled Off PHP_INI_SYSTEM
inclued.dumpdir NULL PHP_INI_SYSTEM
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
inclued.enabled bool
Whether or not to enable inclued.
inclued.dumpdir string
Location (path) to the directory that stores inclued files. If
set, each PHP request will create a file. These files are
serialized versions of what inclued_get_data() would produce, so
may be unserialized with unserialize().
Caution
Because every request creates a file, this directory may fill up
fast!
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
This extension has no constants defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Table of Contents
* Example that implements inclued into an application
----------------------------------------------------------------------
Example that implements inclued into an application
This example demonstrates the process of implementing inclued into an
existing application, and viewing the results.
Example #1 Getting the data within the PHP application itself (function)
Now that some data exists, it's time to make sense of it in the form of a
graph. The inclued extension includes a PHP file named gengraph.php that
creates a dot file that requires the >> graphviz library. However, this
form is not required.
Example #2 Example use of gengraph.php
This example creates an image named inclued.png that shows the inclued
data.
# First, create the dot file
$ php graphviz.php -i /tmp/wp.ser -o wp.dot
# Next, create the image
$ dot -Tpng -o inclued.png wp.dot
Example #3 Listing data via inclued dumps (configuration)
When using the inclued.dumpdir directive, files (include clues) are dumped
with every request. Here's one way to list those files, and unserialize()
them.
count() === 0) {
echo 'No clues today', PHP_EOL;
exit;
}
foreach ($inclues as $inclue) {
echo 'Inclued file: ', $inclue->getFilename(), PHP_EOL;
$data = file_get_contents($inclue->getPathname());
if ($data) {
$inc = unserialize($data);
echo ' -- filename: ', $inc['request']['SCRIPT_FILENAME'], PHP_EOL;
echo ' -- number of includes: ', count($inc['includes']), PHP_EOL;
}
echo PHP_EOL;
}
} else {
echo 'I am totally clueless today.', PHP_EOL;
}
?>
The above example will output something similar to:
PATH: /tmp/inclued
Inclued file: inclued.56521.1
-- filename: /Users/philip/test.php
-- number of includes: 1
Inclued file: inclued.56563.1
-- filename: /tmp/none.php
-- number of includes: 0
Inclued file: inclued.56636.1
-- filename: /tmp/three.php
-- number of includes: 3
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
inclued Functions
----------------------------------------------------------------------
inclued_get_data
(PECL inclued >= 0.1.0)
inclued_get_data - Get the inclued data
Description
array inclued_get_data ( void )
Get the inclued data.
Parameters
This function has no parameters.
Return Values
The inclued data.
Examples
Example #1 inclued_get_data() example
See the inclued examples section for ways to create graphs with this data.
The above example will output something similar to:
Array
(
[includes] => Array
(
[0] => Array
(
[operation] => include
[op_type] => 2
[filename] => x.php
[opened_path] => /tmp/x.php
[fromfile] => /tmp/z.php
[fromline] => 2
)
)
)
See Also
* inclued examples
* debug_backtrace() - Generates a backtrace
* include() - include
----------------------------------------------------------------------
Table of Contents
* inclued_get_data - Get the inclued data
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* Example that implements inclued into an application
* inclued Functions
* inclued_get_data - Get the inclued data
----------------------------------------------------------------------
----------------------------------------------------------------------
PHP Options and Information
----------------------------------------------------------------------
Introduction
This functions enable you to get a lot of information about PHP itself,
e.g. runtime configuration, loaded extensions, version and much more.
You'll also find functions to set options for your running PHP. The
probably best known function of PHP - phpinfo() - can be found here.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
There is no installation needed to use these functions; they are part of
the PHP core.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
PHP Options/Inf Configuration Options
Name Default Changeable Changelog
assert.active "1" PHP_INI_ALL
assert.bail "0" PHP_INI_ALL
assert.warning "1" PHP_INI_ALL
assert.callback NULL PHP_INI_ALL
assert.quiet_eval "0" PHP_INI_ALL
This deprecated feature
enable_dl "1" PHP_INI_SYSTEM will certainly be removed
in the future.
max_execution_time "30" PHP_INI_ALL
max_input_time "-1" PHP_INI_PERDIR Available since PHP 4.3.0.
max_input_nesting_level "64" PHP_INI_PERDIR Available since PHP 4.4.8.
Removed in PHP 5.0.0.
PHP_INI_ALL in PHP <=
magic_quotes_gpc "1" PHP_INI_PERDIR 4.2.3. This deprecated
feature will certainly be
removed in the future.
This deprecated feature
magic_quotes_runtime "0" PHP_INI_ALL will certainly be removed
in the future.
zend.enable_gc "1" PHP_INI_ALL Available since PHP 5.3.0.
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
assert.active boolean
Enable assert() evaluation.
assert.bail boolean
Terminate script execution on failed assertions.
assert.warning boolean
Issue a PHP warning for each failed assertion.
assert.callback string
user function to call on failed assertions
assert.quiet_eval boolean
Use the current setting of error_reporting() during assertion
expression evaluation. If enabled, no errors are shown (implicit
error_reporting(0)) while evaluation. If disabled, errors are
shown according to the settings of error_reporting()
enable_dl boolean
This directive is really only useful in the Apache module version
of PHP. You can turn dynamic loading of PHP extensions with dl()
on and off per virtual server or per directory.
The main reason for turning dynamic loading off is security. With
dynamic loading, it's possible to ignore all open_basedir
restrictions. The default is to allow dynamic loading, except when
using safe mode. In safe mode, it's always impossible to use dl().
max_execution_time integer
This sets the maximum time in seconds a script is allowed to run
before it is terminated by the parser. This helps prevent poorly
written scripts from tying up the server. The default setting is
30. When running PHP from the command line the default setting is
0.
The maximum execution time is not affected by system calls, stream
operations etc. Please see the set_time_limit() function for more
details.
You can not change this setting with ini_set() when running in
safe mode. The only workaround is to turn off safe mode or by
changing the time limit in the php.ini.
Your web server can have other timeout configurations that may
also interrupt PHP execution. Apache has a Timeout directive and
IIS has a CGI timeout function. Both default to 300 seconds. See
your web server documentation for specific details.
max_input_time integer
This sets the maximum time in seconds a script is allowed to parse
input data, like POST and GET. It is measured from the moment of
receiving all data on the server to the start of script execution.
max_input_nesting_level integer
Sets the max nesting depth of input variables (i.e. $_GET,
$_POST..)
magic_quotes_gpc boolean
Warning
This feature has been DEPRECATED as of PHP 5.3.0. Relying on this
feature is highly discouraged.
Sets the magic_quotes state for GPC (Get/Post/Cookie) operations.
When magic_quotes are on, all ' (single-quote), " (double quote),
\ (backslash) and NUL's are escaped with a backslash
automatically.
Note:
In PHP 4, also $_ENV variables are escaped.
Note:
If the magic_quotes_sybase directive is also ON it will
completely override magic_quotes_gpc. Having both directives
enabled means only single quotes are escaped as ''. Double
quotes, backslashes and NUL's will remain untouched and
unescaped.
See also get_magic_quotes_gpc()
magic_quotes_runtime boolean
Warning
This feature has been DEPRECATED as of PHP 5.3.0. Relying on this
feature is highly discouraged.
If magic_quotes_runtime is enabled, most functions that return
data from any sort of external source including databases and text
files will have quotes escaped with a backslash. If
magic_quotes_sybase is also on, a single-quote is escaped with a
single-quote instead of a backslash.
Functions affected by magic_quotes_runtime (does not include
functions from PECL):
* get_meta_tags()
* file_get_contents()
* file()
* fgets()
* fwrite()
* fread()
* fputcsv()
* stream_socket_recvfrom()
* exec()
* system()
* passthru()
* stream_get_contents()
* bzread()
* gzfile()
* gzgets()
* gzwrite()
* gzread()
* phar_file_get_contents()
* exif_read_data()
* dba_insert()
* dba_replace()
* dba_fetch()
* ibase_fetch_row()
* ibase_fetch_assoc()
* ibase_fetch_object()
* mssql_fetch_row()
* mssql_fetch_object()
* mssql_fetch_array()
* mssql_fetch_assoc()
* mysqli_fetch_row()
* mysqli_fetch_array()
* mysqli_fetch_assoc()
* mysqli_fetch_object()
* pg_fetch_row()
* pg_fetch_assoc()
* pg_fetch_array()
* pg_fetch_object()
* pg_fetch_all()
* pg_select()
* sybase_fetch_object()
* sybase_fetch_array()
* sybase_fetch_assoc()
* SplFileObject::fgets()
* SplFileObject::fgetcsv()
* SplFileObject::fwrite()
zend.enable_gc boolean
Enables or disables the circular reference collector.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are always available as part of the PHP core.
Pre-defined phpcredits() constants
Constant Value Description
CREDITS_GROUP 1 A list of the core developers
CREDITS_GENERAL 2 General credits: Language design and concept, PHP
authors and SAPI module.
CREDITS_SAPI 4 A list of the server API modules for PHP, and their
authors.
CREDITS_MODULES 8 A list of the extension modules for PHP, and their
authors.
CREDITS_DOCS 16 The credits for the documentation team.
Usually used in combination with the other flags.
CREDITS_FULLPAGE 32 Indicates that a complete stand-alone HTML page
needs to be printed including the information
indicated by the other flags.
CREDITS_QA 64 The credits for the quality assurance team.
All the credits, equivalent to using: CREDITS_DOCS
+ CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES
CREDITS_ALL -1 + CREDITS_QA CREDITS_FULLPAGE. It generates a
complete stand-alone HTML page with the appropriate
tags. This is the default value.
phpinfo() constants
Constant Value Description
INFO_GENERAL 1 The configuration line, php.ini location, build
date, Web Server, System and more.
INFO_CREDITS 2 PHP Credits. See also phpcredits().
INFO_CONFIGURATION 4 Current Local and Master values for PHP
directives. See also ini_get().
INFO_MODULES 8 Loaded modules and their respective settings.
INFO_ENVIRONMENT 16 Environment Variable information that's also
available in $_ENV.
INFO_VARIABLES 32 Shows all predefined variables from EGPCS
(Environment, GET, POST, Cookie, Server).
INFO_LICENSE 64 PHP License information. See also the >> license
faq.
INFO_ALL -1 Shows all of the above. This is the default
value.
Assert constants, these values are used to set the assertion options in
assert_options().
assert() constants
Constant INI Setting Description
ASSERT_ACTIVE assert.active Enable assert() evaluation.
ASSERT_CALLBACK assert.callback Callback to call on failed assertions.
ASSERT_BAIL assert.bail Terminate execution on failed
assertions.
ASSERT_WARNING assert.warning Issues a PHP warning for each failed
assertion
ASSERT_QUITE_EVAL assert.quiet_eval Disable error_reporting during
assertion expression evaluation.
The following constants are only available if the host operating system is
Windows, and can tell different versioning information so its possible to
detect various features and make use of them. They are all available as of
PHP 5.3.0.
Windows specific constants
Constant Description
The major version of Windows, this can be
PHP_WINDOWS_VERSION_MAJOR either 4 (NT4/Me/98/95), 5 (XP/2003
R2/2003/2000) or 6 (Vista/2008).
The minor version of Windows, this can be
PHP_WINDOWS_VERSION_MINOR either 0 (Vista/2008/2000/NT4/95), 1
(XP), 2 (2003 R2/2003/XP x64), 10 (98) or
90 (ME).
The Windows build number (for example,
PHP_WINDOWS_VERSION_BUILD Windows Vista with SP1 applied is build
6001)
The platform that PHP currently is
PHP_WINDOWS_VERSION_PLATFORM running on, this value is 2 on Windows
Vista/XP/2000/NT4, Server 2008/2003 and
on Windows ME/98/95 this value is 1.
The major version of the service pack
installed, this value is 0 if no service
PHP_WINDOWS_VERSION_SP_MAJOR pack is installed. For example, Windows
XP with service pack 3 installed will
make this value 3.
The minor version of the service pack
PHP_WINDOWS_VERSION_SP_MINOR installed, this value is 0 if no service
pack is installed.
The suitemask is a bitmask that can tell
PHP_WINDOWS_VERSION_SUITEMASK if various features of Windows is
installed, see the table below for
possible bitfield values.
This contains the value used to determine
PHP_WINDOWS_VERSION_PRODUCTTYPE the PHP_WINDOWS_NT_* constants. This
value may be one of the PHP_WINDOWS_NT_*
constants indicating the platform type.
PHP_WINDOWS_NT_DOMAIN_CONTROLLER This is a domain controller
This is a server system (eg. Server
PHP_WINDOWS_NT_SERVER 2008/2003/2000), note that if this is a
domain controller its reported as
PHP_WINDOWS_NT_DOMAIN_CONTROLLER.
PHP_WINDOWS_NT_WORKSTATION This is a workstation system (eg.
Vista/XP/2000/NT4)
This table shows a list of features that can be checked for using the
PHP_WINDOWS_VERSION_SUITEMASK bitmask.
Windows suitemask bitfields
Bits Description
0x00000004 Microsoft BackOffice components are installed.
0x00000400 Windows Server 2003, Web Edition is installed.
0x00004000 Windows Server 2003, Compute Cluster Edition is installed.
0x00000080 Windows Server 2008 Datacenter, Windows Server 2003, Datacenter
Edition or Windows 2000 Datacenter Server is installed.
Windows Server 2008 Enterprise, Windows Server 2003, Enterprise
0x00000002 Edition, Windows 2000 Advanced Server, or Windows NT Server 4.0
Enterprise Edition is installed.
0x00000040 Windows XP Embedded is installed.
0x00000200 Windows Vista Home Premium, Windows Vista Home Basic, or
Windows XP Home Edition is installed.
Remote Desktop is supported, but only one interactive session
0x00000100 is supported. This value is set unless the system is running in
application server mode.
Microsoft Small Business Server was once installed on the
0x00000001 system, but may have been upgraded to another version of
Windows.
0x00000020 Microsoft Small Business Server is installed with the
restrictive client license in force.
0x00002000 Windows Storage Server 2003 R2 or Windows Storage Server 2003
is installed.
Terminal Services is installed. This value is always set. If
0x00000010 this value is set but 0x00000100 is not set, then the system is
running in application server mode.
0x00008000 Windows Home Server is installed.
----------------------------------------------------------------------
----------------------------------------------------------------------
PHP Options/Info Functions
----------------------------------------------------------------------
assert_options
(PHP 4, PHP 5)
assert_options - Set/get the various assert flags
Description
mixed assert_options ( int $what [, mixed $value ] )
Set the various assert() control options or just query their current
settings.
Parameters
what
Assert Options
Option INI Setting Default Description
value
ASSERT_ACTIVE assert.active 1 enable assert()
evaluation
issue a PHP warning
ASSERT_WARNING assert.warning 1 for each failed
assertion
ASSERT_BAIL assert.bail 0 terminate execution on
failed assertions
disable
ASSERT_QUIET_EVAL assert.quiet_eval 0 error_reporting during
assertion expression
evaluation
ASSERT_CALLBACK assert.callback (NULL) Callback to call on
failed assertions
value
An optional new value for the option.
Return Values
Returns the original setting of any option or FALSE on errors.
Examples
Example #1 assert_options() example
See Also
* assert() - Checks if assertion is FALSE
----------------------------------------------------------------------
----------------------------------------------------------------------
assert
(PHP 4, PHP 5)
assert - Checks if assertion is FALSE
Description
bool assert ( mixed $assertion )
assert() will check the given assertion and take appropriate action if its
result is FALSE.
If the assertion is given as a string it will be evaluated as PHP code by
assert(). The advantages of a string assertion are less overhead when
assertion checking is off and messages containing the assertion expression
when an assertion fails. This means that if you pass a boolean condition
as assertion this condition will not show up as parameter to the assertion
function which you may have defined with the assert_options() function,
the condition is converted to a string before calling that handler
function, and the boolean FALSE is converted as the empty string.
Assertions should be used as a debugging feature only. You may use them
for sanity-checks that test for conditions that should always be TRUE and
that indicate some programming errors if not or to check for the presence
of certain features like extension functions or certain system limits and
features.
Assertions should not be used for normal runtime operations like input
parameter checks. As a rule of thumb your code should always be able to
work correctly if assertion checking is not activated.
The behavior of assert() may be configured by assert_options() or by
.ini-settings described in that functions manual page.
The assert_options() function and/or ASSERT_CALLBACK configuration
directive allow a callback function to be set to handle failed assertions.
assert() callbacks are particularly useful for building automated test
suites because they allow you to easily capture the code passed to the
assertion, along with information on where the assertion was made. While
this information can be captured via other methods, using assertions makes
it much faster and easier!
The callback function should accept three arguments. The first argument
will contain the file the assertion failed in. The second argument will
contain the line the assertion failed on and the third argument will
contain the expression that failed (if any - literal values such as 1 or
"two" will not be passed via this argument)
Parameters
assertion
The assertion.
Return Values
FALSE if the assertion is false, TRUE otherwise.
Examples
Example #1 Handle a failed assertion with a custom handler
Assertion Failed:
File '$file'
Line '$line'
Code '$code' ";
}
// Set up the callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');
// Make an assertion that should fail
assert('mysql_query("")');
?>
See Also
* assert_options() - Set/get the various assert flags
----------------------------------------------------------------------
----------------------------------------------------------------------
dl
(PHP 4, PHP 5)
dl - Loads a PHP extension at runtime
Description
bool dl ( string $library )
Loads the PHP extension given by the parameter library.
Use extension_loaded() to test whether a given extension is already
available or not. This works on both built-in extensions and dynamically
loaded ones (either through php.ini or dl()).
Warning
This function has been removed from some SAPI's in PHP 5.3.
Parameters
library
This parameter is only the filename of the extension to load which
also depends on your platform. For example, the sockets extension
(if compiled as a shared module, not the default!) would be called
sockets.so on Unix platforms whereas it is called php_sockets.dll
on the Windows platform.
The directory where the extension is loaded from depends on your
platform:
Windows - If not explicitly set in the php.ini, the extension is
loaded from C:\php4\extensions\ (PHP4) or C:\php5\ (PHP5) by
default.
Unix - If not explicitly set in the php.ini, the default extension
directory depends on
* whether PHP has been built with --enable-debug or not
* whether PHP has been built with (experimental) ZTS (Zend
Thread Safety) support or not
* the current internal ZEND_MODULE_API_NO (Zend internal module
API number, which is basically the date on which a major
module API change happened, e.g. 20010901)
Taking into account the above, the directory then defaults to
/lib/php/extensions/
--ZEND_MODULE_API_NO, e.g.
/usr/local/php/lib/php/extensions/debug-non-zts-20010901 or
/usr/local/php/lib/php/extensions/no-debug-zts-20010901.
Return Values
Returns TRUE on success or FALSE on failure. If the functionality of
loading modules is not available or has been disabled (either by setting
enable_dl off or by enabling safe mode in php.ini) an E_ERROR is emitted
and execution is stopped. If dl() fails because the specified library
couldn't be loaded, in addition to FALSE an E_WARNING message is emitted.
Examples
Example #1 dl() examples
Changelog
Version Description
dl() is now disabled in some SAPI's due to stability issues. The
5.3.0 only SAPI's that allow dl() are: CLI, CGI and Embed. Use the
Extension Loading Directives instead.
Notes
Note:
dl() is not supported when PHP is built with ZTS support. Use the
Extension Loading Directives instead.
Note:
dl() is case sensitive on Unix platforms.
Note: This function is disabled when PHP is running in safe mode.
See Also
* Extension Loading Directives
* extension_loaded() - Find out whether an extension is loaded
----------------------------------------------------------------------
----------------------------------------------------------------------
extension_loaded
(PHP 4, PHP 5)
extension_loaded - Find out whether an extension is loaded
Description
bool extension_loaded ( string $name )
Finds out whether the extension is loaded.
Parameters
name
The extension name.
You can see the names of various extensions by using phpinfo() or
if you're using the CGI or CLI version of PHP you can use the -m
switch to list all available extensions:
$ php -m
[PHP Modules]
xml
tokenizer
standard
sockets
session
posix
pcre
overload
mysql
mbstring
ctype
[Zend Modules]
Return Values
Returns TRUE if the extension identified by name is loaded, FALSE
otherwise.
Examples
Example #1 extension_loaded() example
Changelog
Version Description
extension_loaded() uses the internal extension name to test
whether a certain extension is available or not. Most internal
5.0.0 extension names are written in lower case but there may be
extensions available which also use uppercase letters. Prior to
PHP 5, this function compared the names case sensitively.
See Also
* get_loaded_extensions() - Returns an array with the names of all
modules compiled and loaded
* get_extension_funcs() - Returns an array with the names of the
functions of a module
* phpinfo() - Outputs information about PHP's configuration
* dl() - Loads a PHP extension at runtime
----------------------------------------------------------------------
----------------------------------------------------------------------
gc_collect_cycles
(PHP 5 >= 5.3.0)
gc_collect_cycles - Forces collection of any existing garbage cycles
Description
int gc_collect_cycles ( void )
Warning
This function is currently not documented; only its argument list is
available.
Forces collection of any existing garbage cycles.
Parameters
This function has no parameters.
Return Values
Returns number of collected cycles.
----------------------------------------------------------------------
----------------------------------------------------------------------
gc_disable
(PHP 5 >= 5.3.0)
gc_disable - Deactivates the circular reference collector
Description
void gc_disable ( void )
Warning
This function is currently not documented; only its argument list is
available.
Deactivates the circular reference collector.
Parameters
This function has no parameters.
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
gc_enable
(PHP 5 >= 5.3.0)
gc_enable - Activates the circular reference collector
Description
void gc_enable ( void )
Warning
This function is currently not documented; only its argument list is
available.
Activates the circular reference collector.
Parameters
This function has no parameters.
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
gc_enabled
(PHP 5 >= 5.3.0)
gc_enabled - Returns status of the circular reference collector
Description
bool gc_enabled ( void )
Warning
This function is currently not documented; only its argument list is
available.
Returns status of the circular reference collector.
Parameters
This function has no parameters.
Return Values
Returns TRUE if the garbage collector is enabled, FALSE otherwise.
----------------------------------------------------------------------
----------------------------------------------------------------------
get_cfg_var
(PHP 4, PHP 5)
get_cfg_var - Gets the value of a PHP configuration option
Description
string get_cfg_var ( string $option )
Gets the value of a PHP configuration option.
This function will not return configuration information set when the PHP
was compiled, or read from an Apache configuration file.
To check whether the system is using a configuration file, try retrieving
the value of the cfg_file_path configuration setting. If this is
available, a configuration file is being used.
Parameters
option
The configuration option name.
Return Values
Returns the current value of the PHP configuration variable specified by
option, or FALSE if an error occurs.
Changelog
Version Description
5.3.0 get_cfg_var() was fixed to be able to return "array" ini options.
See Also
* ini_get() - Gets the value of a configuration option
* ini_get_all() - Gets all configuration options
----------------------------------------------------------------------
----------------------------------------------------------------------
get_current_user
(PHP 4, PHP 5)
get_current_user - Gets the name of the owner of the current PHP script
Description
string get_current_user ( void )
Returns the name of the owner of the current PHP script.
Return Values
Returns the username as a string.
Examples
Example #1 get_current_user() example
The above example will output something similar to:
Current script owner: SYSTEM
See Also
* getmyuid() - Gets PHP script owner's UID
* getmygid() - Get PHP script owner's GID
* getmypid() - Gets PHP's process ID
* getmyinode() - Gets the inode of the current script
* getlastmod() - Gets time of last page modification
----------------------------------------------------------------------
----------------------------------------------------------------------
get_defined_constants
(PHP 4 >= 4.1.0, PHP 5)
get_defined_constants - Returns an associative array with the names of all
the constants and their values
Description
array get_defined_constants ([ bool $categorize = false ] )
Returns the names and values of all the constants currently defined. This
includes those created by extensions as well as those created with the
define() function.
Parameters
categorize
Causing this function to return a multi-dimensional array with
categories in the keys of the first dimension and constants and
their values in the second dimension.
The above example will output something similar to:
Array
(
[Core] => Array
(
[E_ERROR] => 1
[E_WARNING] => 2
[E_PARSE] => 4
[E_NOTICE] => 8
[E_CORE_ERROR] => 16
[E_CORE_WARNING] => 32
[E_COMPILE_ERROR] => 64
[E_COMPILE_WARNING] => 128
[E_USER_ERROR] => 256
[E_USER_WARNING] => 512
[E_USER_NOTICE] => 1024
[E_ALL] => 2047
[TRUE] => 1
)
[pcre] => Array
(
[PREG_PATTERN_ORDER] => 1
[PREG_SET_ORDER] => 2
[PREG_OFFSET_CAPTURE] => 256
[PREG_SPLIT_NO_EMPTY] => 1
[PREG_SPLIT_DELIM_CAPTURE] => 2
[PREG_SPLIT_OFFSET_CAPTURE] => 4
[PREG_GREP_INVERT] => 1
)
[user] => Array
(
[MY_CONSTANT] => 1
)
)
Return Values
Changelog
Version Description
5.3.1 Windows only: Core constants are categorized under Core,
previously mhash.
5.3.0 Core constants are categorized under Core, previously internal. On
Windows, the Core Constants are categorized under mhash.
The categorize parameter now operates appropriately. Previously,
5.2.11 the categorize parameter was interpreted as !is_null($categorize),
making any value other than NULL force the constants to be
categorized.
5.0.0 The categorize parameter was added.
Examples
Example #1 get_defined_constants() Example
The above example will output something similar to:
Array
(
[E_ERROR] => 1
[E_WARNING] => 2
[E_PARSE] => 4
[E_NOTICE] => 8
[E_CORE_ERROR] => 16
[E_CORE_WARNING] => 32
[E_COMPILE_ERROR] => 64
[E_COMPILE_WARNING] => 128
[E_USER_ERROR] => 256
[E_USER_WARNING] => 512
[E_USER_NOTICE] => 1024
[E_ALL] => 2047
[TRUE] => 1
)
See Also
* defined() - Checks whether a given named constant exists
* get_loaded_extensions() - Returns an array with the names of all
modules compiled and loaded
* get_defined_functions() - Returns an array of all defined functions
* get_defined_vars() - Returns an array of all defined variables
----------------------------------------------------------------------
----------------------------------------------------------------------
get_extension_funcs
(PHP 4, PHP 5)
get_extension_funcs - Returns an array with the names of the functions of
a module
Description
array get_extension_funcs ( string $module_name )
This function returns the names of all the functions defined in the module
indicated by module_name.
Parameters
module_name
The module name.
Note:
This parameter must be in lowercase.
Return Values
Returns an array with all the functions, or FALSE if module_name is not a
valid extension.
Examples
Example #1 Prints the XML functions
The above example will output something similar to:
Array
(
[0] => xml_parser_create
[1] => xml_parser_create_ns
[2] => xml_set_object
[3] => xml_set_element_handler
[4] => xml_set_character_data_handler
[5] => xml_set_processing_instruction_handler
[6] => xml_set_default_handler
[7] => xml_set_unparsed_entity_decl_handler
[8] => xml_set_notation_decl_handler
[9] => xml_set_external_entity_ref_handler
[10] => xml_set_start_namespace_decl_handler
[11] => xml_set_end_namespace_decl_handler
[12] => xml_parse
[13] => xml_parse_into_struct
[14] => xml_get_error_code
[15] => xml_error_string
[16] => xml_get_current_line_number
[17] => xml_get_current_column_number
[18] => xml_get_current_byte_index
[19] => xml_parser_free
[20] => xml_parser_set_option
[21] => xml_parser_get_option
[22] => utf8_encode
[23] => utf8_decode
)
See Also
* get_loaded_extensions() - Returns an array with the names of all
modules compiled and loaded
----------------------------------------------------------------------
----------------------------------------------------------------------
get_include_path
(PHP 4 >= 4.3.0, PHP 5)
get_include_path - Gets the current include_path configuration option
Description
string get_include_path ( void )
Gets the current include_path configuration option value.
Return Values
Returns the path, as a string.
Examples
Example #1 get_include_path() example
See Also
* ini_get() - Gets the value of a configuration option
* restore_include_path() - Restores the value of the include_path
configuration option
* set_include_path() - Sets the include_path configuration option
* include() - include
----------------------------------------------------------------------
----------------------------------------------------------------------
get_included_files
(PHP 4, PHP 5)
get_included_files - Returns an array with the names of included or
required files
Description
array get_included_files ( void )
Gets the names of all files that have been included using include(),
include_once(), require() or require_once().
Return Values
Returns an array of the names of all files.
The script originally called is considered an "included file," so it will
be listed together with the files referenced by include() and family.
Files that are included or required multiple times only show up once in
the returned array.
Changelog
Version Description
In PHP 4.0.1 and previous versions this function assumed that the
required files ended in the extension .php; other extensions would
4.0.1 not be returned. The array returned by get_included_files() was an
associative array and only listed files included by include() and
include_once().
Examples
Example #1 get_included_files() example
The above example will output:
abc.php
test1.php
test2.php
test3.php
test4.php
Notes
Note:
Files included using the auto_prepend_file configuration directive are
not included in the returned array.
See Also
* include() - include
* include_once() - include_once
* require() - require
* require_once() - require_once
* get_required_files() - Alias of get_included_files
----------------------------------------------------------------------
----------------------------------------------------------------------
get_loaded_extensions
(PHP 4, PHP 5)
get_loaded_extensions - Returns an array with the names of all modules
compiled and loaded
Description
array get_loaded_extensions ([ bool $zend_extensions = false ] )
This function returns the names of all the modules compiled and loaded in
the PHP interpreter.
Parameters
zend_extensions
Only return Zend extensions, if not then regular extensions, like
mysqli are listed. Defaults to FALSE (return regular extensions).
Return Values
Returns an indexed array of all the modules names.
Changelog
Version Description
5.2.4 The optional zend_extensions parameter was added
Examples
Example #1 get_loaded_extensions() Example
The above example will output something similar to:
Array
(
[0] => xml
[1] => wddx
[2] => standard
[3] => session
[4] => posix
[5] => pgsql
[6] => pcre
[7] => gd
[8] => ftp
[9] => db
[10] => calendar
[11] => bcmath
)
See Also
* get_extension_funcs() - Returns an array with the names of the
functions of a module
* extension_loaded() - Find out whether an extension is loaded
* dl() - Loads a PHP extension at runtime
* phpinfo() - Outputs information about PHP's configuration
----------------------------------------------------------------------
----------------------------------------------------------------------
get_magic_quotes_gpc
(PHP 4, PHP 5)
get_magic_quotes_gpc - Gets the current configuration setting of
magic_quotes_gpc
Description
int get_magic_quotes_gpc ( void )
Returns the current configuration setting of magic_quotes_gpc
Keep in mind that attempting to set magic_quotes_gpc at runtime will not
work.
For more information about magic_quotes, see this security section.
Return Values
Returns 0 if magic_quotes_gpc is off, 1 otherwise.
Examples
Example #1 get_magic_quotes_gpc() example
Notes
Note:
If the directive magic_quotes_sybase is ON it will completely override
magic_quotes_gpc. So even when get_magic_quotes_gpc() returns TRUE
neither double quotes, backslashes or NUL's will be escaped. Only single
quotes will be escaped. In this case they'll look like: ''
See Also
* addslashes() - Quote string with slashes
* stripslashes() - Un-quotes a quoted string
* get_magic_quotes_runtime() - Gets the current active configuration
setting of magic_quotes_runtime
* ini_get() - Gets the value of a configuration option
----------------------------------------------------------------------
----------------------------------------------------------------------
get_magic_quotes_runtime
(PHP 4, PHP 5)
get_magic_quotes_runtime - Gets the current active configuration setting
of magic_quotes_runtime
Description
int get_magic_quotes_runtime ( void )
Returns the current active configuration setting of magic_quotes_runtime.
Return Values
Returns 0 if magic_quotes_runtime is off, 1 otherwise.
Examples
Example #1 get_magic_quotes_runtime() example
See Also
* get_magic_quotes_gpc() - Gets the current configuration setting of
magic_quotes_gpc
* set_magic_quotes_runtime() - Sets the current active configuration
setting of magic_quotes_runtime
----------------------------------------------------------------------
----------------------------------------------------------------------
get_required_files
(PHP 4, PHP 5)
get_required_files - Alias of get_included_files()
Description
This function is an alias of: get_included_files().
----------------------------------------------------------------------
----------------------------------------------------------------------
getenv
(PHP 4, PHP 5)
getenv - Gets the value of an environment variable
Description
string getenv ( string $varname )
Gets the value of an environment variable.
You can see a list of all the environmental variables by using phpinfo().
Many of these variables are listed within >> RFC 3875, specifically
section 4.1, "Request Meta-Variables".
Parameters
varname
The variable name.
Return Values
Returns the value of the environment variable varname, or FALSE if the
environment variable varname does not exist.
Examples
Example #1 getenv() Example
See Also
* putenv() - Sets the value of an environment variable
* apache_getenv() - Get an Apache subprocess_env variable
* Superglobals
----------------------------------------------------------------------
----------------------------------------------------------------------
getlastmod
(PHP 4, PHP 5)
getlastmod - Gets time of last page modification
Description
int getlastmod ( void )
Gets the time of the last modification of the current page.
If you're interested in getting the last modification time of a different
file, consider using filemtime().
Return Values
Returns the time of the last modification of the current page. The value
returned is a Unix timestamp, suitable for feeding to date(). Returns
FALSE on error.
Examples
Example #1 getlastmod() example
See Also
* date() - Format a local time/date
* getmyuid() - Gets PHP script owner's UID
* getmygid() - Get PHP script owner's GID
* get_current_user() - Gets the name of the owner of the current PHP
script
* getmyinode() - Gets the inode of the current script
* getmypid() - Gets PHP's process ID
* filemtime() - Gets file modification time
----------------------------------------------------------------------
----------------------------------------------------------------------
getmygid
(PHP 4 >= 4.1.0, PHP 5)
getmygid - Get PHP script owner's GID
Description
int getmygid ( void )
Gets the group ID of the current script.
Return Values
Returns the group ID of the current script, or FALSE on error.
See Also
* getmyuid() - Gets PHP script owner's UID
* getmypid() - Gets PHP's process ID
* get_current_user() - Gets the name of the owner of the current PHP
script
* getmyinode() - Gets the inode of the current script
* getlastmod() - Gets time of last page modification
----------------------------------------------------------------------
----------------------------------------------------------------------
getmyinode
(PHP 4, PHP 5)
getmyinode - Gets the inode of the current script
Description
int getmyinode ( void )
Gets the inode of the current script.
Return Values
Returns the current script's inode as an integer, or FALSE on error.
See Also
* getmygid() - Get PHP script owner's GID
* getmyuid() - Gets PHP script owner's UID
* getmypid() - Gets PHP's process ID
* get_current_user() - Gets the name of the owner of the current PHP
script
* getlastmod() - Gets time of last page modification
----------------------------------------------------------------------
----------------------------------------------------------------------
getmypid
(PHP 4, PHP 5)
getmypid - Gets PHP's process ID
Description
int getmypid ( void )
Gets the current PHP process ID.
Return Values
Returns the current PHP process ID, or FALSE on error.
Notes
Warning
Process IDs are not unique, thus they are a weak entropy source. We
recommend against relying on pids in security-dependent contexts.
See Also
* getmygid() - Get PHP script owner's GID
* getmyuid() - Gets PHP script owner's UID
* get_current_user() - Gets the name of the owner of the current PHP
script
* getmyinode() - Gets the inode of the current script
* getlastmod() - Gets time of last page modification
----------------------------------------------------------------------
----------------------------------------------------------------------
getmyuid
(PHP 4, PHP 5)
getmyuid - Gets PHP script owner's UID
Description
int getmyuid ( void )
Gets the user ID of the current script.
Return Values
Returns the user ID of the current script, or FALSE on error.
See Also
* getmygid() - Get PHP script owner's GID
* getmypid() - Gets PHP's process ID
* get_current_user() - Gets the name of the owner of the current PHP
script
* getmyinode() - Gets the inode of the current script
* getlastmod() - Gets time of last page modification
----------------------------------------------------------------------
----------------------------------------------------------------------
getopt
(PHP 4 >= 4.3.0, PHP 5)
getopt - Gets options from the command line argument list
Description
array getopt ( string $options [, array $longopts ] )
Parses options passed to the script.
Parameters
options
Each character in this string will be used as option characters
and matched against options passed to the script starting with a
single hyphen (-). For example, an option string "x" recognizes an
option -x. Only a-z, A-Z and 0-9 are allowed.
longopts
An array of options. Each element in this array will be used as
option strings and matched against options passed to the script
starting with two hyphens (--). For example, an longopts element
"opt" recognizes an option --opt.
Note: Prior to PHP5.3.0 this parameter was only available on few
systems
The options parameter may contain the following elements:
* Individual characters (do not accept values)
* Characters followed by a colon (parameter requires value)
* Characters followed by two colons (optional value)
Option values are the first argument after the string. It does not matter
if a value has leading white space or not.
Note: Optional values do not accept " " (space) as a separator.
Note:
The format for the options and longopts is almost the same, the only
difference is that longopts takes an array of options (where each
element is the option) where as options takes a string (where each
character is the option).
Return Values
This function will return an array of option / argument pairs or FALSE on
failure.
Note:
The parsing of options will end at the first non-option found, anything
that follows is discarded.
Changelog
Version Description
5.3.0 Added support for "=" as argument/value separator.
5.3.0 Added support for optional values (specified with "::").
5.3.0 This function is no longer system dependent and works on Windows
too.
Examples
Example #1 getopt() example
Running the above script with php script.php -fvalue -h will output:
array(2) {
["f"]=>
string(5) "value"
["h"]=>
bool(false)
}
Example #2 getopt() example#2
Running the above script with php script.php -f "value for f" -v -a
--required value --optional="optional value" --option will output:
array(6) {
["f"]=>
string(11) "value for f"
["v"]=>
bool(false)
["a"]=>
bool(false)
["required"]=>
string(5) "value"
["optional"]=>
string(14) "optional value"
["option"]=>
bool(false)
}
Example #3 getopt() example#3
Passing multiple options as one
Running the above script with php script.php -aaac will output:
array(2) {
["a"]=>
array(3) {
[0]=>
bool(false)
[1]=>
bool(false)
[2]=>
bool(false)
}
["c"]=>
bool(false)
}
See Also
* $argv
----------------------------------------------------------------------
----------------------------------------------------------------------
getrusage
(PHP 4, PHP 5)
getrusage - Gets the current resource usages
Description
array getrusage ([ int $who = 0 ] )
This is an interface to getrusage(2). It gets data returned from the
system call.
Parameters
who
If who is 1, getrusage will be called with RUSAGE_CHILDREN.
Return Values
Returns an associative array containing the data returned from the system
call. All entries are accessible by using their documented field names.
Examples
Example #1 getrusage() example
Notes
Note: This function is not implemented on Windows platforms.
See Also
* Your system's man page on getrusage(2)
----------------------------------------------------------------------
----------------------------------------------------------------------
ini_alter
(PHP 4, PHP 5)
ini_alter - Alias of ini_set()
Description
This function is an alias of: ini_set().
----------------------------------------------------------------------
----------------------------------------------------------------------
ini_get_all
(PHP 4 >= 4.2.0, PHP 5)
ini_get_all - Gets all configuration options
Description
array ini_get_all ([ string $extension [, bool $details = true ]] )
Returns all the registered configuration options.
Parameters
extension
An optional extension name. If set, the function return only
options specific for that extension.
details
Retrieve details settings or only the current value for each
setting. Default is TRUE (retrieve details).
Return Values
Returns an associative array with directive name as the array key.
When details is TRUE (default) the array will contain global_value (set in
php.ini), local_value (perhaps set with ini_set() or .htaccess), and
access (the access level).
When details is FALSE the value will be the current value of the option.
See the manual section for information on what access levels mean.
Note:
It's possible for a directive to have multiple access levels, which is
why access shows the appropriate bitmask values.
Changelog
Version Description
5.3.0 Added details.
Examples
Example #1 ini_get_all() examples
The above example will output something similar to:
Array
(
[pcre.backtrack_limit] => Array
(
[global_value] => 100000
[local_value] => 100000
[access] => 7
)
[pcre.recursion_limit] => Array
(
[global_value] => 100000
[local_value] => 100000
[access] => 7
)
)
Array
(
[allow_call_time_pass_reference] => Array
(
[global_value] => 0
[local_value] => 0
[access] => 6
)
[allow_url_fopen] => Array
(
[global_value] => 1
[local_value] => 1
[access] => 4
)
...
)
Example #2 Disabling details
The above example will output something similar to:
Array
(
[pcre.backtrack_limit] => 100000
[pcre.recursion_limit] => 100000
)
Array
(
[allow_call_time_pass_reference] => 0
[allow_url_fopen] => 1
...
)
See Also
* How to change configuration settings
* ini_get() - Gets the value of a configuration option
* ini_restore() - Restores the value of a configuration option
* ini_set() - Sets the value of a configuration option
* get_loaded_extensions() - Returns an array with the names of all
modules compiled and loaded
* phpinfo() - Outputs information about PHP's configuration
----------------------------------------------------------------------
----------------------------------------------------------------------
ini_get
(PHP 4, PHP 5)
ini_get - Gets the value of a configuration option
Description
string ini_get ( string $varname )
Returns the value of the configuration option on success.
Parameters
varname
The configuration option name.
Return Values
Returns the value of the configuration option as a string on success, or
an empty string for null values. Returns FALSE if the configuration option
doesn't exist.
Examples
Example #1 A few ini_get() examples
The above example will output something similar to:
display_errors = 1
register_globals = 0
post_max_size = 8M
post_max_size+1 = 9
post_max_size in bytes = 8388608
Notes
Note: When querying boolean values
A boolean ini value of off will be returned as an empty string or "0"
while a boolean ini value of on will be returned as "1". The function
can also return the literal string of INI value.
Note: When querying memory size values
Many ini memory size values, such as upload_max_filesize, are stored in
the php.ini file in shorthand notation. ini_get() will return the exact
string stored in the php.ini file and NOT its integer equivalent.
Attempting normal arithmetic functions on these values will not have
otherwise expected results. The example above shows one way to convert
shorthand notation into bytes, much like how the PHP source does it.
See Also
* get_cfg_var() - Gets the value of a PHP configuration option
* ini_get_all() - Gets all configuration options
* ini_restore() - Restores the value of a configuration option
* ini_set() - Sets the value of a configuration option
----------------------------------------------------------------------
----------------------------------------------------------------------
ini_restore
(PHP 4, PHP 5)
ini_restore - Restores the value of a configuration option
Description
void ini_restore ( string $varname )
Restores a given configuration option to its original value.
Parameters
varname
The configuration option name.
Return Values
No value is returned.
Examples
Example #1 ini_restore() example
The above example will output:
Current value for 'y2k_compliance': 1
New value for 'y2k_compliance': 0
Original value for 'y2k_compliance': 1
See Also
* ini_get() - Gets the value of a configuration option
* ini_get_all() - Gets all configuration options
* ini_set() - Sets the value of a configuration option
----------------------------------------------------------------------
----------------------------------------------------------------------
ini_set
(PHP 4, PHP 5)
ini_set - Sets the value of a configuration option
Description
string ini_set ( string $varname , string $newvalue )
Sets the value of the given configuration option. The configuration option
will keep this new value during the script's execution, and will be
restored at the script's ending.
Parameters
varname
Not all the available options can be changed using ini_set().
There is a list of all available options in the appendix.
newvalue
The new value for the option.
Return Values
Returns the old value on success, FALSE on failure.
Examples
Example #1 Setting an ini option
See Also
* get_cfg_var() - Gets the value of a PHP configuration option
* ini_get() - Gets the value of a configuration option
* ini_get_all() - Gets all configuration options
* ini_restore() - Restores the value of a configuration option
* How to change configuration settings
----------------------------------------------------------------------
----------------------------------------------------------------------
magic_quotes_runtime
(PHP 4, PHP 5)
magic_quotes_runtime - Alias of set_magic_quotes_runtime()
Description
This function is an alias of: set_magic_quotes_runtime()
----------------------------------------------------------------------
----------------------------------------------------------------------
main
main - Dummy for main()
Description
There is no function named main() except in the PHP source. In PHP 4.3.0,
a new type of error handling in the PHP source (php_error_docref) was
introduced. One feature is to provide links to a manual page in PHP error
messages when the PHP directives html_errors (on by default) and
docref_root (on by default until PHP 4.3.2) are set.
Sometimes error messages refer to a manual page for the function main()
which is why this page exists. If you discover such a reference, please
>> file a bug report, indicating the PHP function caused the error that
linked to main() and it will be fixed and properly documented.
Known errors that point to main()
Function name No longer points here as of
include() 5.1.0
include_once() 5.1.0
require() 5.1.0
require_once() 5.1.0
See Also
* html_errors
* display_errors
----------------------------------------------------------------------
----------------------------------------------------------------------
memory_get_peak_usage
(PHP 5 >= 5.2.0)
memory_get_peak_usage - Returns the peak of memory allocated by PHP
Description
int memory_get_peak_usage ([ bool $real_usage = false ] )
Returns the peak of memory, in bytes, that's been allocated to your PHP
script.
Parameters
real_usage
Set this to TRUE to get the real size of memory allocated from
system. If not set or FALSE only the memory used by emalloc() is
reported.
Return Values
Returns the memory peak in bytes.
Changelog
Version Description
5.2.1 Compiling with --enable-memory-limit is no longer required for
this function to exist.
5.2.0 real_usage was added.
See Also
* memory_get_usage() - Returns the amount of memory allocated to PHP
* memory_limit
----------------------------------------------------------------------
----------------------------------------------------------------------
memory_get_usage
(PHP 4 >= 4.3.2, PHP 5)
memory_get_usage - Returns the amount of memory allocated to PHP
Description
int memory_get_usage ([ bool $real_usage = false ] )
Returns the amount of memory, in bytes, that's currently being allocated
to your PHP script.
Parameters
real_usage
Set this to TRUE to get the real size of memory allocated from
system. If not set or FALSE only the memory used by emalloc() is
reported.
Return Values
Returns the memory amount in bytes.
Changelog
Version Description
5.2.1 Compiling with --enable-memory-limit is no longer required for
this function to exist.
5.2.0 real_usage was added.
Examples
Example #1 A memory_get_usage() example
See Also
* memory_get_peak_usage() - Returns the peak of memory allocated by PHP
* memory_limit
----------------------------------------------------------------------
----------------------------------------------------------------------
php_ini_loaded_file
(PHP 5 >= 5.2.4)
php_ini_loaded_file - Retrieve a path to the loaded php.ini file
Description
string php_ini_loaded_file ( void )
Check if a php.ini file is loaded, and retrieve its path.
Parameters
This function has no parameters.
Return Values
The loaded php.ini path, or FALSE if one is not loaded.
Examples
Example #1 php_ini_loaded_file() example
The above example will output something similar to:
Loaded php.ini: /usr/local/php/php.ini
See Also
* php_ini_scanned_files() - Return a list of .ini files parsed from the
additional ini dir
* phpinfo() - Outputs information about PHP's configuration
* The configuration file
----------------------------------------------------------------------
----------------------------------------------------------------------
php_ini_scanned_files
(PHP 4 >= 4.3.0, PHP 5)
php_ini_scanned_files - Return a list of .ini files parsed from the
additional ini dir
Description
string php_ini_scanned_files ( void )
php_ini_scanned_files() returns a comma-separated list of configuration
files parsed after php.ini. These files are found in a directory defined
by the --with-config-file-scan-dir option which is set during compilation.
The returned configuration files also include the path as declared in the
--with-config-file-scan-dir option.
Return Values
Returns a comma-separated string of .ini files on success. Each comma is
followed by a newline. If the directive --with-config-file-scan-dir wasn't
set, FALSE is returned. If it was set and the directory was empty, an
empty string is returned. If a file is unrecognizable, the file will still
make it into the returned string but a PHP error will also result. This
PHP error will be seen both at compile time and while using
php_ini_scanned_files().
Examples
Example #1 A simple example to list the returned ini files
0) {
$files = explode(',', $filelist);
foreach ($files as $file) {
echo "" . trim($file) . " \n";
}
}
}
?>
See Also
* ini_set() - Sets the value of a configuration option
* phpinfo() - Outputs information about PHP's configuration
* php_ini_loaded_file() - Retrieve a path to the loaded php.ini file
----------------------------------------------------------------------
----------------------------------------------------------------------
php_logo_guid
(PHP 4, PHP 5)
php_logo_guid - Gets the logo guid
Description
string php_logo_guid ( void )
This function returns the ID which can be used to display the PHP logo
using the built-in image. Logo is displayed only if expose_php is On.
Return Values
Returns PHPE9568F34-D428-11d2-A769-00AA001ACF42.
Examples
Example #1 php_logo_guid() example
';
?>
See Also
* phpinfo() - Outputs information about PHP's configuration
* phpversion() - Gets the current PHP version
* phpcredits() - Prints out the credits for PHP
* zend_logo_guid() - Gets the Zend guid
----------------------------------------------------------------------
----------------------------------------------------------------------
php_sapi_name
(PHP 4 >= 4.0.1, PHP 5)
php_sapi_name - Returns the type of interface between web server and PHP
Description
string php_sapi_name ( void )
Returns a lowercase string that describes the type of interface (the
Server API, SAPI) that PHP is using. For example, in CLI PHP this string
will be "cli" whereas with Apache it may have several different values
depending on the exact SAPI used. Possible values are listed below.
Return Values
Returns the interface type, as a lowercase string.
Although not exhaustive, the possible return values include aolserver,
apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3),
cgi-fcgi, cli, continuity, embed, isapi, litespeed, milter, nsapi, phttpd,
pi3web, roxen, thttpd, tux, and webjames.
Examples
Example #1 php_sapi_name() example
This example checks for the substring cgi because it may also be cgi-fcgi.
Notes
Note: An alternative approach
The PHP constant PHP_SAPI has the same value as php_sapi_name().
Tip
A potential gotcha
The defined SAPI may not be obvious, because for example instead of apache
it may be defined as apache2handler or apache2filter.
See Also
* PHP_SAPI
----------------------------------------------------------------------
----------------------------------------------------------------------
php_uname
(PHP 4 >= 4.0.2, PHP 5)
php_uname - Returns information about the operating system PHP is running
on
Description
string php_uname ([ string $mode = "a" ] )
php_uname() returns a description of the operating system PHP is running
on. This is the same string you see at the very top of the phpinfo()
output. For the name of just the operating system, consider using the
PHP_OS constant, but keep in mind this constant will contain the operating
system PHP was built on.
On some older UNIX platforms, it may not be able to determine the current
OS information in which case it will revert to displaying the OS PHP was
built on. This will only happen if your uname() library call either
doesn't exist or doesn't work.
Parameters
mode
mode is a single character that defines what information is
returned:
* 'a': This is the default. Contains all modes in the sequence
"s n r v m".
* 's': Operating system name. eg. FreeBSD.
* 'n': Host name. eg. localhost.example.com.
* 'r': Release name. eg. 5.1.2-RELEASE.
* 'v': Version information. Varies a lot between operating
systems.
* 'm': Machine type. eg. i386.
Return Values
Returns the description, as a string.
Examples
Example #1 Some php_uname() examples
There are also some related Predefined PHP constants that may come in
handy, for example:
Example #2 A few OS related constant examples
See Also
* phpversion() - Gets the current PHP version
* php_sapi_name() - Returns the type of interface between web server and
PHP
* phpinfo() - Outputs information about PHP's configuration
----------------------------------------------------------------------
----------------------------------------------------------------------
phpcredits
(PHP 4, PHP 5)
phpcredits - Prints out the credits for PHP
Description
bool phpcredits ([ int $flag = CREDITS_ALL ] )
This function prints out the credits listing the PHP developers, modules,
etc. It generates the appropriate HTML codes to insert the information in
a page.
Parameters
flag
To generate a custom credits page, you may want to use the flag
parameter.
Pre-defined phpcredits() flags
name description
All the credits, equivalent to using:
CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP +
CREDITS_ALL CREDITS_MODULES + CREDITS_FULLPAGE. It generates
a complete stand-alone HTML page with the
appropriate tags.
CREDITS_DOCS The credits for the documentation team
Usually used in combination with the other flags.
CREDITS_FULLPAGE Indicates that a complete stand-alone HTML page
needs to be printed including the information
indicated by the other flags.
CREDITS_GENERAL General credits: Language design and concept, PHP
authors and SAPI module.
CREDITS_GROUP A list of the core developers
CREDITS_MODULES A list of the extension modules for PHP, and
their authors
CREDITS_SAPI A list of the server API modules for PHP, and
their authors
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Prints the general credits
Example #2 Prints the core developers and the documentation group
Example #3 Printing all the credits
My credits page
See Also
* phpversion() - Gets the current PHP version
* php_logo_guid() - Gets the logo guid
* phpinfo() - Outputs information about PHP's configuration
----------------------------------------------------------------------
----------------------------------------------------------------------
phpinfo
(PHP 4, PHP 5)
phpinfo - Outputs information about PHP's configuration
Description
bool phpinfo ([ int $what = INFO_ALL ] )
Outputs a large amount of information about the current state of PHP. This
includes information about PHP compilation options and extensions, the PHP
version, server information and environment (if compiled as a module), the
PHP environment, OS version information, paths, master and local values of
configuration options, HTTP headers, and the PHP License.
Because every system is setup differently, phpinfo() is commonly used to
check configuration settings and for available predefined variables on a
given system.
phpinfo() is also a valuable debugging tool as it contains all EGPCS
(Environment, GET, POST, Cookie, Server) data.
Parameters
what
The output may be customized by passing one or more of the
following constants bitwise values summed together in the optional
what parameter. One can also combine the respective constants or
bitwise values together with the or operator.
phpinfo() options
Name (constant) Value Description
INFO_GENERAL 1 The configuration line, php.ini location,
build date, Web Server, System and more.
INFO_CREDITS 2 PHP Credits. See also phpcredits().
INFO_CONFIGURATION 4 Current Local and Master values for PHP
directives. See also ini_get().
Loaded modules and their respective
INFO_MODULES 8 settings. See also
get_loaded_extensions().
INFO_ENVIRONMENT 16 Environment Variable information that's
also available in $_ENV.
INFO_VARIABLES 32 Shows all predefined variables from EGPCS
(Environment, GET, POST, Cookie, Server).
INFO_LICENSE 64 PHP License information. See also the
>> license FAQ.
INFO_ALL -1 Shows all of the above.
Return Values
Returns TRUE on success or FALSE on failure.
Changelog
Version Description
5.2.2 The "Loaded Configuration File" information was added, when before
only "Configuration File (php.ini) Path" existed.
Examples
Example #1 phpinfo() Example
Notes
Note:
Parts of the information displayed are disabled when the expose_php
configuration setting is set to off. This includes the PHP and Zend
logos, and the credits.
Note:
phpinfo() outputs plain text instead of HTML when using the CLI mode.
See Also
* phpversion() - Gets the current PHP version
* phpcredits() - Prints out the credits for PHP
* php_logo_guid() - Gets the logo guid
* ini_get() - Gets the value of a configuration option
* ini_set() - Sets the value of a configuration option
* get_loaded_extensions() - Returns an array with the names of all
modules compiled and loaded
* Predefined Variables
----------------------------------------------------------------------
----------------------------------------------------------------------
phpversion
(PHP 4, PHP 5)
phpversion - Gets the current PHP version
Description
string phpversion ([ string $extension ] )
Returns a string containing the version of the currently running PHP
parser or extension.
Parameters
extension
An optional extension name.
Return Values
If the optional extension parameter is specified, phpversion() returns the
version of that extension, or FALSE if there is no version information
associated or the extension isn't enabled.
Examples
Example #1 phpversion() example
Example #2 PHP_VERSION_ID example and usage
Notes
Note:
This information is also available in the predefined constant
PHP_VERSION. More versioning information is available using the
PHP_VERSION_* constants.
See Also
* PHP_VERSION constants
* version_compare() - Compares two "PHP-standardized" version number
strings
* phpinfo() - Outputs information about PHP's configuration
* phpcredits() - Prints out the credits for PHP
* php_logo_guid() - Gets the logo guid
* zend_version() - Gets the version of the current Zend engine
----------------------------------------------------------------------
----------------------------------------------------------------------
putenv
(PHP 4, PHP 5)
putenv - Sets the value of an environment variable
Description
bool putenv ( string $setting )
Adds setting to the server environment. The environment variable will only
exist for the duration of the current request. At the end of the request
the environment is restored to its original state.
Setting certain environment variables may be a potential security breach.
The safe_mode_allowed_env_vars directive contains a comma-delimited list
of prefixes. In Safe Mode, the user may only alter environment variables
whose names begin with the prefixes supplied by this directive. By
default, users will only be able to set environment variables that begin
with PHP_ (e.g. PHP_FOO=BAR). Note: if this directive is empty, PHP will
let the user modify ANY environment variable!
The safe_mode_protected_env_vars directive contains a comma-delimited list
of environment variables, that the end user won't be able to change using
putenv(). These variables will be protected even if
safe_mode_allowed_env_vars is set to allow to change them.
Parameters
setting
The setting, like "FOO=BAR"
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Setting an environment variable
Notes
Warning
The safe_mode_allowed_env_vars and safe_mode_protected_env_vars directives
only take effect when safe_mode is enabled.
See Also
* getenv() - Gets the value of an environment variable
----------------------------------------------------------------------
----------------------------------------------------------------------
restore_include_path
(PHP 4 >= 4.3.0, PHP 5)
restore_include_path - Restores the value of the include_path
configuration option
Description
void restore_include_path ( void )
Restores the include_path configuration option back to its original master
value as set in php.ini
Return Values
No value is returned.
Examples
Example #1 restore_include_path() example
See Also
* ini_restore() - Restores the value of a configuration option
* get_include_path() - Gets the current include_path configuration
option
* set_include_path() - Sets the include_path configuration option
* include() - include
----------------------------------------------------------------------
----------------------------------------------------------------------
set_include_path
(PHP 4 >= 4.3.0, PHP 5)
set_include_path - Sets the include_path configuration option
Description
string set_include_path ( string $new_include_path )
Sets the include_path configuration option for the duration of the script.
Parameters
new_include_path
The new value for the include_path
Return Values
Returns the old include_path on success or FALSE on failure.
Examples
Example #1 set_include_path() example
Example #2 Adding to the include path
Making use of the PATH_SEPARATOR constant, it is possible to extend the
include path regardless of the operating system.
In this example we add /usr/lib/pear to the end of the existing
include_path.
See Also
* ini_set() - Sets the value of a configuration option
* get_include_path() - Gets the current include_path configuration
option
* restore_include_path() - Restores the value of the include_path
configuration option
* include() - include
----------------------------------------------------------------------
----------------------------------------------------------------------
set_magic_quotes_runtime
(PHP 4, PHP 5)
set_magic_quotes_runtime - Sets the current active configuration setting
of magic_quotes_runtime
Description
bool set_magic_quotes_runtime ( bool $new_setting )
Set the current active configuration setting of magic_quotes_runtime.
Warning
This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature
is highly discouraged.
Parameters
new_setting
FALSE for off, TRUE for on.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 set_magic_quotes_runtime() example
The above example will output:
Without magic_quotes_runtime: 'PHP' is a Recursive acronym
With magic_quotes_runtime: \'PHP\' is a Recursive acronym
See Also
* get_magic_quotes_gpc() - Gets the current configuration setting of
magic_quotes_gpc
* get_magic_quotes_runtime() - Gets the current active configuration
setting of magic_quotes_runtime
----------------------------------------------------------------------
----------------------------------------------------------------------
set_time_limit
(PHP 4, PHP 5)
set_time_limit - Limits the maximum execution time
Description
void set_time_limit ( int $seconds )
Set the number of seconds a script is allowed to run. If this is reached,
the script returns a fatal error. The default limit is 30 seconds or, if
it exists, the max_execution_time value defined in the php.ini.
When called, set_time_limit() restarts the timeout counter from zero. In
other words, if the timeout is the default 30 seconds, and 25 seconds into
script execution a call such as set_time_limit(20) is made, the script
will run for a total of 45 seconds before timing out.
Parameters
seconds
The maximum execution time, in seconds. If set to zero, no time
limit is imposed.
Return Values
No value is returned.
Notes
Warning
This function has no effect when PHP is running in safe mode. There is no
workaround other than turning off safe mode or changing the time limit in
the php.ini.
Note:
The set_time_limit() function and the configuration directive
max_execution_time only affect the execution time of the script itself.
Any time spent on activity that happens outside the execution of the
script such as system calls using system(), stream operations, database
queries, etc. is not included when determining the maximum time that the
script has been running. This is not true on Windows where the measured
time is real.
See Also
* max_execution_time
* max_input_time
----------------------------------------------------------------------
----------------------------------------------------------------------
sys_get_temp_dir
(PHP 5 >= 5.2.1)
sys_get_temp_dir - Returns directory path used for temporary files
Description
string sys_get_temp_dir ( void )
Returns the path of the directory PHP stores temporary files in by
default.
Return Values
Returns the path of the temporary directory.
Examples
Example #1 sys_get_temp_dir() example
The above example will output something similar to:
C:\Windows\Temp\TuxA318.tmp
See Also
* tmpfile() - Creates a temporary file
* tempnam() - Create file with unique file name
----------------------------------------------------------------------
----------------------------------------------------------------------
version_compare
(PHP 4 >= 4.1.0, PHP 5)
version_compare - Compares two "PHP-standardized" version number strings
Description
mixed version_compare ( string $version1 , string $version2 [, string
$operator ] )
version_compare() compares two "PHP-standardized" version number strings.
This is useful if you would like to write programs working only on some
versions of PHP.
The function first replaces _, - and + with a dot . in the version strings
and also inserts dots . before and after any non number so that for
example '4.3.2RC1' becomes '4.3.2.RC.1'. Then it splits the results like
if you were using explode('.', $ver). Then it compares the parts starting
from left to right. If a part contains special version strings these are
handled in the following order: any string not found in this list < dev <
alpha = a < beta = b < RC = rc < # < pl = p. This way not only versions
with different levels like '4.1' and '4.1.2' can be compared but also any
PHP specific version containing development state.
Parameters
version1
First version number.
version2
Second version number.
operator
If you specify the third optional operator argument, you can test
for a particular relationship. The possible operators are: <, lt,
<=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively.
This parameter is case-sensitive, so values should be lowercase.
Return Values
By default, version_compare() returns -1 if the first version is lower
than the second, 0 if they are equal, and 1 if the second is lower.
When using the optional operator argument, the function will return TRUE
if the relationship is the one specified by the operator, FALSE otherwise.
Examples
The examples below use the PHP_VERSION constant, because it contains the
value of the PHP version that is executing the code.
Example #1 version_compare() examples
= 0) {
echo 'I am at least PHP version 6.0.0, my version: ' . PHP_VERSION . "\n";
}
if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
echo 'I am at least PHP version 5.3.0, my version: ' . PHP_VERSION . "\n";
}
if (version_compare(PHP_VERSION, '5.0.0', '>=')) {
echo 'I am using PHP 5, my version: ' . PHP_VERSION . "\n";
}
if (version_compare(PHP_VERSION, '5.0.0', '<')) {
echo 'I am using PHP 4, my version: ' . PHP_VERSION . "\n";
}
?>
Notes
Note:
The PHP_VERSION constant holds current PHP version.
Note:
Note that pre-release versions, such as 5.3.0-dev, are considered lower
than their final release counterparts (like 5.3.0).
See Also
* phpversion() - Gets the current PHP version
* php_uname() - Returns information about the operating system PHP is
running on
* function_exists() - Return TRUE if the given function has been defined
----------------------------------------------------------------------
----------------------------------------------------------------------
zend_logo_guid
(PHP 4, PHP 5)
zend_logo_guid - Gets the Zend guid
Description
string zend_logo_guid ( void )
This function returns the ID which can be used to display the Zend logo
using the built-in image.
Return Values
Returns PHPE9568F35-D428-11d2-A769-00AA001ACF42.
Examples
Example #1 zend_logo_guid() example
';
?>
See Also
* php_logo_guid() - Gets the logo guid
----------------------------------------------------------------------
----------------------------------------------------------------------
zend_thread_id
(PHP 5)
zend_thread_id - Returns a unique identifier for the current thread
Description
int zend_thread_id ( void )
This function returns a unique identifier for the current thread.
Return Values
Returns the thread id as an integer.
Examples
Example #1 zend_thread_id() example
The above example will output something similar to:
Current thread id is: 7864
Notes
Note:
This function is only available if PHP has been built with ZTS (Zend
Thread Safety) support and debug mode (--enable-debug).
----------------------------------------------------------------------
----------------------------------------------------------------------
zend_version
(PHP 4, PHP 5)
zend_version - Gets the version of the current Zend engine
Description
string zend_version ( void )
Returns a string containing the version of the currently running Zend
Engine.
Return Values
Returns the Zend Engine version number, as a string.
Examples
Example #1 zend_version() example
The above example will output something similar to:
Zend engine version: 2.2.0
See Also
* phpinfo() - Outputs information about PHP's configuration
* phpcredits() - Prints out the credits for PHP
* php_logo_guid() - Gets the logo guid
* phpversion() - Gets the current PHP version
----------------------------------------------------------------------
Table of Contents
* assert_options - Set/get the various assert flags
* assert - Checks if assertion is FALSE
* dl - Loads a PHP extension at runtime
* extension_loaded - Find out whether an extension is loaded
* gc_collect_cycles - Forces collection of any existing garbage cycles
* gc_disable - Deactivates the circular reference collector
* gc_enable - Activates the circular reference collector
* gc_enabled - Returns status of the circular reference collector
* get_cfg_var - Gets the value of a PHP configuration option
* get_current_user - Gets the name of the owner of the current PHP
script
* get_defined_constants - Returns an associative array with the names of
all the constants and their values
* get_extension_funcs - Returns an array with the names of the functions
of a module
* get_include_path - Gets the current include_path configuration option
* get_included_files - Returns an array with the names of included or
required files
* get_loaded_extensions - Returns an array with the names of all modules
compiled and loaded
* get_magic_quotes_gpc - Gets the current configuration setting of
magic_quotes_gpc
* get_magic_quotes_runtime - Gets the current active configuration
setting of magic_quotes_runtime
* get_required_files - Alias of get_included_files
* getenv - Gets the value of an environment variable
* getlastmod - Gets time of last page modification
* getmygid - Get PHP script owner's GID
* getmyinode - Gets the inode of the current script
* getmypid - Gets PHP's process ID
* getmyuid - Gets PHP script owner's UID
* getopt - Gets options from the command line argument list
* getrusage - Gets the current resource usages
* ini_alter - Alias of ini_set
* ini_get_all - Gets all configuration options
* ini_get - Gets the value of a configuration option
* ini_restore - Restores the value of a configuration option
* ini_set - Sets the value of a configuration option
* magic_quotes_runtime - Alias of set_magic_quotes_runtime
* main - Dummy for main
* memory_get_peak_usage - Returns the peak of memory allocated by PHP
* memory_get_usage - Returns the amount of memory allocated to PHP
* php_ini_loaded_file - Retrieve a path to the loaded php.ini file
* php_ini_scanned_files - Return a list of .ini files parsed from the
additional ini dir
* php_logo_guid - Gets the logo guid
* php_sapi_name - Returns the type of interface between web server and
PHP
* php_uname - Returns information about the operating system PHP is
running on
* phpcredits - Prints out the credits for PHP
* phpinfo - Outputs information about PHP's configuration
* phpversion - Gets the current PHP version
* putenv - Sets the value of an environment variable
* restore_include_path - Restores the value of the include_path
configuration option
* set_include_path - Sets the include_path configuration option
* set_magic_quotes_runtime - Sets the current active configuration
setting of magic_quotes_runtime
* set_time_limit - Limits the maximum execution time
* sys_get_temp_dir - Returns directory path used for temporary files
* version_compare - Compares two "PHP-standardized" version number
strings
* zend_logo_guid - Gets the Zend guid
* zend_thread_id - Returns a unique identifier for the current thread
* zend_version - Gets the version of the current Zend engine
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* PHP Options/Info Functions
* assert_options - Set/get the various assert flags
* assert - Checks if assertion is FALSE
* dl - Loads a PHP extension at runtime
* extension_loaded - Find out whether an extension is loaded
* gc_collect_cycles - Forces collection of any existing garbage
cycles
* gc_disable - Deactivates the circular reference collector
* gc_enable - Activates the circular reference collector
* gc_enabled - Returns status of the circular reference collector
* get_cfg_var - Gets the value of a PHP configuration option
* get_current_user - Gets the name of the owner of the current PHP
script
* get_defined_constants - Returns an associative array with the
names of all the constants and their values
* get_extension_funcs - Returns an array with the names of the
functions of a module
* get_include_path - Gets the current include_path configuration
option
* get_included_files - Returns an array with the names of included
or required files
* get_loaded_extensions - Returns an array with the names of all
modules compiled and loaded
* get_magic_quotes_gpc - Gets the current configuration setting of
magic_quotes_gpc
* get_magic_quotes_runtime - Gets the current active configuration
setting of magic_quotes_runtime
* get_required_files - Alias of get_included_files
* getenv - Gets the value of an environment variable
* getlastmod - Gets time of last page modification
* getmygid - Get PHP script owner's GID
* getmyinode - Gets the inode of the current script
* getmypid - Gets PHP's process ID
* getmyuid - Gets PHP script owner's UID
* getopt - Gets options from the command line argument list
* getrusage - Gets the current resource usages
* ini_alter - Alias of ini_set
* ini_get_all - Gets all configuration options
* ini_get - Gets the value of a configuration option
* ini_restore - Restores the value of a configuration option
* ini_set - Sets the value of a configuration option
* magic_quotes_runtime - Alias of set_magic_quotes_runtime
* main - Dummy for main
* memory_get_peak_usage - Returns the peak of memory allocated by
PHP
* memory_get_usage - Returns the amount of memory allocated to PHP
* php_ini_loaded_file - Retrieve a path to the loaded php.ini file
* php_ini_scanned_files - Return a list of .ini files parsed from
the additional ini dir
* php_logo_guid - Gets the logo guid
* php_sapi_name - Returns the type of interface between web server
and PHP
* php_uname - Returns information about the operating system PHP is
running on
* phpcredits - Prints out the credits for PHP
* phpinfo - Outputs information about PHP's configuration
* phpversion - Gets the current PHP version
* putenv - Sets the value of an environment variable
* restore_include_path - Restores the value of the include_path
configuration option
* set_include_path - Sets the include_path configuration option
* set_magic_quotes_runtime - Sets the current active configuration
setting of magic_quotes_runtime
* set_time_limit - Limits the maximum execution time
* sys_get_temp_dir - Returns directory path used for temporary
files
* version_compare - Compares two "PHP-standardized" version number
strings
* zend_logo_guid - Gets the Zend guid
* zend_thread_id - Returns a unique identifier for the current
thread
* zend_version - Gets the version of the current Zend engine
----------------------------------------------------------------------
----------------------------------------------------------------------
Memtrack
----------------------------------------------------------------------
Introduction
The purpose of this extension is to detect the most memory hungry scripts
and functions.
memtrack tracks memory consumption in PHP scripts and produces reports
(warnings) when the consumption reaches certain levels set by the user.
This is achieved by replacing default executor function by a special
function which compares memory usage before and after running the original
executor - this way we can tell how much the memory usage has changed
during the execution of the current part of the code.
Zend Engine runs its executor for each opcode array (op_array), which
usually means function, plain script and such, so memtrack doesn't have
any noticeable effect on performance.
memtrack doesn't provide any functions, there are only INI directives
which allow you to configure the way it should work.
Warning
This extension is EXPERIMENTAL. The behaviour of this extension including
the names of its functions and any other documentation surrounding this
extension may change without notice in a future release of PHP. This
extension should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here: >> http://pecl.php.net/package/memtrack
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Memtrack Configuration Options
Name Default Changeable
memtrack.enabled "0" PHP_INI_SYSTEM
memtrack.soft_limit "0" PHP_INI_ALL
memtrack.hard_limit "0" PHP_INI_ALL
memtrack.vm_limit "0" PHP_INI_ALL
memtrack.ignore_functions "" PHP_INI_SYSTEM
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
memtrack.enabled boolean
Disables or enables the extension. Default value is 0, i.e.
disabled.
memtrack.soft_limit int
Soft memory limit.
The extension checks memory consumption before and after executing
an op_array and produces a warning is the difference between the
two values is equal to or greater than the soft limit, but only if
the function is not ignored.
Setting this option to 0 also disables both soft and hard limit
warnings. Default value is 0, i.e. no warnings is produced.
memtrack.hard_limit int
Hard memory limit.
The extension checks memory consumption before and after executing
an op_array and produces a warning is the difference between the
two values is equal to or greater than the hard limit, even if the
function is ignored. Setting this option to 0 disables hard limit
warnings completely. Default value is 0, i.e. no hard limit
warnings is produced.
memtrack.vm_limit int
Virtual memory limit (set on a process).
This limit is checked only on shutdown and a warning is produced
if the value is greater than or equal to the limit.
This option is currently supported only on OSes where mallinfo()
function is available (i.e. Linux).
memtrack.ignore_functions string
A comma or whitespace-separated list of functions which are to be
ignored by soft_limit. The values are case-insensitive, for class
methods use class::method syntax.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
This extension has no constants defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Table of Contents
* Basic usage
----------------------------------------------------------------------
Basic usage
Basic example on using memtrack extension:
Example #1 Creating large array in a function
Run the example with the following command:
php -d memtrack.enabled=1 -d memtrack.soft_limit=1M -d memtrack.vm_limit=3M /tmp/example1.php
The above example will output something similar to:
Warning: [memtrack] [pid 26177] user function foo() executed in /tmp/example1.php on line 10 allocated 4194304 bytes in /tmp/example1.php on line 0
Warning: [memtrack] [pid 26177] virtual memory usage on shutdown: 32911360 bytes in Unknown on line 0
----------------------------------------------------------------------
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* Basic usage
----------------------------------------------------------------------
----------------------------------------------------------------------
Object property and method call overloading
----------------------------------------------------------------------
Introduction
The purpose of this extension is to allow overloading of object property
access and method calls. Only one function is defined in this extension,
overload() which takes the name of the class that should have this
functionality enabled. The class named has to define appropriate methods
if it wants to have this functionality: __get(), __set() and __call()
respectively for getting/setting a property, or calling a method. This way
overloading can be selective. Inside these handler functions the
overloading is disabled so you can access object properties normally.
Warning
This extension is EXPERIMENTAL. The behaviour of this extension including
the names of its functions and any other documentation surrounding this
extension may change without notice in a future release of PHP. This
extension should be used at your own risk.
Warning
This extension is not a part of PHP 5. PHP 5 supports __get(), __set() and
__call() natively. See the Overloading in PHP 5 page for more information.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
In order to use these functions, you must compile PHP with the
--enable-overload option. Starting with PHP 4.3.0 this extension is
enabled by default. You can disable overload support with
--disable--overload .
The Windows version of PHP has built-in support for this extension. You do
not need to load any additional extensions in order to use these
functions.
Note: Builtin support for overload is available with PHP 4.3.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
This extension has no constants defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Table of Contents
* Basic usage
----------------------------------------------------------------------
Basic usage
Some simple examples on using the overload() function:
Example #1 Overloading a PHP class
9, 'c' => 42);
// Callback method for getting a property
function __get($prop_name, &$prop_value)
{
if (isset($this->elem[$prop_name])) {
$prop_value = $this->elem[$prop_name];
return true;
} else {
return false;
}
}
// Callback method for setting a property
function __set($prop_name, $prop_value)
{
$this->elem[$prop_name] = $prop_value;
return true;
}
}
// Here we overload the OO object
overload('OO');
$o = new OO;
echo "\$o->a: $o->a\n"; // print: $o->a: 111
echo "\$o->b: $o->b\n"; // print: $o->b: 9
echo "\$o->c: $o->c\n"; // print: $o->c: 42
echo "\$o->d: $o->d\n"; // print: $o->d:
// add a new item to the $elem array in OO
$o->x = 56;
// instantiate stdclass (it is built-in PHP 4)
// $val is not overloaded!
$val = new stdclass;
$val->prop = 555;
// Set "a" to be an array with the $val object in it
// But __set() will put this in the $elem array
$o->a = array($val);
var_dump($o->a[0]->prop);
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Object overloading Functions
----------------------------------------------------------------------
overload
(PHP 4 >= 4.3.0)
overload - Enable property and method call overloading for a class
Description
void overload ( string $class_name )
The overload() function will enable property and method call overloading
for a class identified by class_name.
Parameters
class_name
The overloaded class name, as a string
Return Values
No value is returned.
Examples
See an example in the introductory section of this part.
----------------------------------------------------------------------
Table of Contents
* overload - Enable property and method call overloading for a class
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* Basic usage
* Object overloading Functions
* overload - Enable property and method call overloading for a
class
----------------------------------------------------------------------
----------------------------------------------------------------------
Output Buffering Control
----------------------------------------------------------------------
Introduction
The Output Control functions allow you to control when output is sent from
the script. This can be useful in several different situations, especially
if you need to send headers to the browser after your script has began
outputting data. The Output Control functions do not affect headers sent
using header() or setcookie(), only functions such as echo() and data
between blocks of PHP code.
Note:
When upgrading from PHP 4.1.x (and 4.2.x) to 4.3.x due to a bug in
earlier versions you must ensure that implicit_flush is OFF in your
php.ini, otherwise any output with ob_start() will not be hidden from
output.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
There is no installation needed to use these functions; they are part of
the PHP core.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Output Control configuration options
Name Default Changeable Changelog
output_buffering "0" PHP_INI_PERDIR
output_handler NULL PHP_INI_PERDIR Available since PHP 4.0.4.
implicit_flush "0" PHP_INI_ALL PHP_INI_PERDIR in PHP <= 4.2.3.
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
output_buffering boolean/integer
You can enable output buffering for all files by setting this
directive to 'On'. If you wish to limit the size of the buffer to
a certain size - you can use a maximum number of bytes instead of
'On', as a value for this directive (e.g., output_buffering=4096).
As of PHP 4.3.5, this directive is always Off in PHP-CLI.
output_handler string
You can redirect all of the output of your scripts to a function.
For example, if you set output_handler to mb_output_handler(),
character encoding will be transparently converted to the
specified encoding. Setting any output handler automatically turns
on output buffering.
Note:
You cannot use both mb_output_handler() with ob_iconv_handler()
and you cannot use both ob_gzhandler() and
zlib.output_compression.
Note:
Only built-in functions can be used with this directive. For
user defined functions, use ob_start().
implicit_flush boolean
FALSE by default. Changing this to TRUE tells PHP to tell the
output layer to flush itself automatically after every output
block. This is equivalent to calling the PHP function flush()
after each and every call to print() or echo() and each and every
HTML block.
When using PHP within an web environment, turning this option on
has serious performance implications and is generally recommended
for debugging purposes only. This value defaults to TRUE when
operating under the CLI SAPI.
See also ob_implicit_flush().
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
This extension has no constants defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Table of Contents
* Basic usage
----------------------------------------------------------------------
Basic usage
Example #1 Output Control example
In the above example, the output from echo() would be stored in the output
buffer until ob_end_flush() was called. In the mean time, the call to
setcookie() successfully stored a cookie without causing an error. (You
can not normally send headers to the browser after data has already been
sent.)
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Output Control Functions
See Also
See also header() and setcookie().
----------------------------------------------------------------------
flush
(PHP 4, PHP 5)
flush - Flush the output buffer
Description
void flush ( void )
Flushes the write buffers of PHP and whatever backend PHP is using (CGI, a
web server, etc). This attempts to push current output all the way to the
browser with a few caveats.
flush() may not be able to override the buffering scheme of your web
server and it has no effect on any client-side buffering in the browser.
It also doesn't affect PHP's userspace output buffering mechanism. This
means you will have to call both ob_flush() and flush() to flush the ob
output buffers if you are using those.
Several servers, especially on Win32, will still buffer the output from
your script until it terminates before transmitting the results to the
browser.
Server modules for Apache like mod_gzip may do buffering of their own that
will cause flush() to not result in data being sent immediately to the
client.
Even the browser may buffer its input before displaying it. Netscape, for
example, buffers text until it receives an end-of-line or the beginning of
a tag, and it won't render tables until the tag of the outermost
table is seen.
Some versions of Microsoft Internet Explorer will only start to display
the page after they have received 256 bytes of output, so you may need to
send extra whitespace before flushing to get those browsers to display the
page.
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
ob_clean
(PHP 4 >= 4.2.0, PHP 5)
ob_clean - Clean (erase) the output buffer
Description
void ob_clean ( void )
This function discards the contents of the output buffer.
This function does not destroy the output buffer like ob_end_clean() does.
Return Values
No value is returned.
See Also
* ob_flush() - Flush (send) the output buffer
* ob_end_flush() - Flush (send) the output buffer and turn off output
buffering
* ob_end_clean() - Clean (erase) the output buffer and turn off output
buffering
----------------------------------------------------------------------
----------------------------------------------------------------------
ob_end_clean
(PHP 4, PHP 5)
ob_end_clean - Clean (erase) the output buffer and turn off output
buffering
Description
bool ob_end_clean ( void )
This function discards the contents of the topmost output buffer and turns
off this output buffering. If you want to further process the buffer's
contents you have to call ob_get_contents() before ob_end_clean() as the
buffer contents are discarded when ob_end_clean() is called.
Return Values
Returns TRUE on success or FALSE on failure. Reasons for failure are first
that you called the function without an active buffer or that for some
reason a buffer could not be deleted (possible for special buffer).
Errors/Exceptions
If the function fails it generates an E_NOTICE.
Changelog
Version Description
4.2.0 The boolean return value was added.
Examples
The following example shows an easy way to get rid of all output buffers:
Example #1 ob_end_clean() example
See Also
* ob_start() - Turn on output buffering
* ob_get_contents() - Return the contents of the output buffer
* ob_flush() - Flush (send) the output buffer
----------------------------------------------------------------------
----------------------------------------------------------------------
ob_end_flush
(PHP 4, PHP 5)
ob_end_flush - Flush (send) the output buffer and turn off output
buffering
Description
bool ob_end_flush ( void )
This function will send the contents of the topmost output buffer (if any)
and turn this output buffer off. If you want to further process the
buffer's contents you have to call ob_get_contents() before ob_end_flush()
as the buffer contents are discarded after ob_end_flush() is called.
Note: This function is similar to ob_get_flush(), except that
ob_get_flush() returns the buffer as a string.
Return Values
Returns TRUE on success or FALSE on failure. Reasons for failure are first
that you called the function without an active buffer or that for some
reason a buffer could not be deleted (possible for special buffer).
Errors/Exceptions
If the function fails it generates an E_NOTICE.
Changelog
Version Description
4.2.0 The boolean return value was added.
Examples
Example #1 ob_end_flush() example
The following example shows an easy way to flush and end all output
buffers:
See Also
* ob_start() - Turn on output buffering
* ob_get_contents() - Return the contents of the output buffer
* ob_get_flush() - Flush the output buffer, return it as a string and
turn off output buffering
* ob_flush() - Flush (send) the output buffer
* ob_end_clean() - Clean (erase) the output buffer and turn off output
buffering
----------------------------------------------------------------------
----------------------------------------------------------------------
ob_flush
(PHP 4 >= 4.2.0, PHP 5)
ob_flush - Flush (send) the output buffer
Description
void ob_flush ( void )
This function will send the contents of the output buffer (if any). If you
want to further process the buffer's contents you have to call
ob_get_contents() before ob_flush() as the buffer contents are discarded
after ob_flush() is called.
This function does not destroy the output buffer like ob_end_flush() does.
Return Values
No value is returned.
See Also
* ob_get_contents() - Return the contents of the output buffer
* ob_clean() - Clean (erase) the output buffer
* ob_end_flush() - Flush (send) the output buffer and turn off output
buffering
* ob_end_clean() - Clean (erase) the output buffer and turn off output
buffering
----------------------------------------------------------------------
----------------------------------------------------------------------
ob_get_clean
(PHP 4 >= 4.3.0, PHP 5)
ob_get_clean - Get current buffer contents and delete current output
buffer
Description
string ob_get_clean ( void )
Gets the current buffer contents and delete current output buffer.
ob_get_clean() essentially executes both ob_get_contents() and
ob_end_clean().
Return Values
Returns the contents of the output buffer and end output buffering. If
output buffering isn't active then FALSE is returned.
Examples
Example #1 A simple ob_get_clean() example
The above example will output:
string(11) "hello world"
See Also
* ob_get_contents() - Return the contents of the output buffer
* ob_start() - Turn on output buffering
----------------------------------------------------------------------
----------------------------------------------------------------------
ob_get_contents
(PHP 4, PHP 5)
ob_get_contents - Return the contents of the output buffer
Description
string ob_get_contents ( void )
Gets the contents of the output buffer without clearing it.
Return Values
This will return the contents of the output buffer or FALSE, if output
buffering isn't active.
Examples
Example #1 A simple ob_get_contents() example
The above example will output:
string(6) "Hello "
string(11) "Hello World"
See Also
* ob_start() - Turn on output buffering
* ob_get_length() - Return the length of the output buffer
----------------------------------------------------------------------
----------------------------------------------------------------------
ob_get_flush
(PHP 4 >= 4.3.0, PHP 5)
ob_get_flush - Flush the output buffer, return it as a string and turn off
output buffering
Description
string ob_get_flush ( void )
ob_get_flush() flushes the output buffer, return it as a string and turns
off output buffering.
Note: This function is similar to ob_end_flush(), except that this
function returns the buffer as a string.
Return Values
Returns the output buffer or FALSE if no buffering is active.
Examples
Example #1 ob_get_flush() example
The above example will output:
Array
(
[0] => default output handler
)
Array
(
)
See Also
* ob_end_clean() - Clean (erase) the output buffer and turn off output
buffering
* ob_end_flush() - Flush (send) the output buffer and turn off output
buffering
* ob_list_handlers() - List all output handlers in use
----------------------------------------------------------------------
----------------------------------------------------------------------
ob_get_length
(PHP 4 >= 4.0.2, PHP 5)
ob_get_length - Return the length of the output buffer
Description
int ob_get_length ( void )
This will return the length of the contents in the output buffer.
Return Values
Returns the length of the output buffer contents or FALSE if no buffering
is active.
Examples
Example #1 A simple ob_get_length() example
The above example will output:
6, 11
See Also
* ob_start() - Turn on output buffering
* ob_get_contents() - Return the contents of the output buffer
----------------------------------------------------------------------
----------------------------------------------------------------------
ob_get_level
(PHP 4 >= 4.2.0, PHP 5)
ob_get_level - Return the nesting level of the output buffering mechanism
Description
int ob_get_level ( void )
Returns the nesting level of the output buffering mechanism.
Return Values
Returns the level of nested output buffering handlers or zero if output
buffering is not active.
See Also
* ob_start() - Turn on output buffering
* ob_get_contents() - Return the contents of the output buffer
----------------------------------------------------------------------
----------------------------------------------------------------------
ob_get_status
(PHP 4 >= 4.2.0, PHP 5)
ob_get_status - Get status of output buffers
Description
array ob_get_status ([ bool $full_status = FALSE ] )
ob_get_status() returns status information on either the top level output
buffer or all active output buffer levels if full_status is set to TRUE.
Parameters
full_status
TRUE to return all active output buffer levels. If FALSE or not
set, only the top level output buffer is returned.
Return Values
If called without the full_status parameter or with full_status = FALSE a
simple array with the following elements is returned:
Array
(
[level] => 2
[type] => 0
[status] => 0
[name] => URL-Rewriter
[del] => 1
)
Simple ob_get_status() results
Key:level
Value:Output nesting level
Key:type
Value:PHP_OUTPUT_HANDLER_INTERNAL (0) or PHP_OUTPUT_HANDLER_USER (1)
Key:status
Value:One of PHP_OUTPUT_HANDLER_START (0), PHP_OUTPUT_HANDLER_CONT (1) or
PHP_OUTPUT_HANDLER_END (2)
Key:name
Value:Name of active output handler or ' default output handler' if none
is set
Key:del
Value:Erase-flag as set by ob_start()
If called with full_status = TRUE an array with one element for each
active output buffer level is returned. The output level is used as key of
the top level array and each array element itself is another array holding
status information on one active output level.
Array
(
[0] => Array
(
[chunk_size] => 0
[size] => 40960
[block_size] => 10240
[type] => 1
[status] => 0
[name] => default output handler
[del] => 1
)
[1] => Array
(
[chunk_size] => 0
[size] => 40960
[block_size] => 10240
[type] => 0
[buffer_size] => 0
[status] => 0
[name] => URL-Rewriter
[del] => 1
)
)
The full output contains these additional elements:
Full ob_get_status() results
Key:chunk_size
Value:Chunk size as set by ob_start()
Key:size
Value:...
Key:blocksize
Value:...
See Also
* ob_get_level() - Return the nesting level of the output buffering
mechanism
* ob_list_handlers() - List all output handlers in use
----------------------------------------------------------------------
----------------------------------------------------------------------
ob_gzhandler
(PHP 4 >= 4.0.4, PHP 5)
ob_gzhandler - ob_start callback function to gzip output buffer
Description
string ob_gzhandler ( string $buffer , int $mode )
ob_gzhandler() is intended to be used as a callback function for
ob_start() to help facilitate sending gz-encoded data to web browsers that
support compressed web pages. Before ob_gzhandler() actually sends
compressed data, it determines what type of content encoding the browser
will accept ("gzip", "deflate" or none at all) and will return its output
accordingly. All browsers are supported since it's up to the browser to
send the correct header saying that it accepts compressed web pages. If a
browser doesn't support compressed pages this function returns FALSE.
Parameters
buffer
mode
Return Values
Changelog
Version Description
4.0.5 The mode parameter was added.
Examples
Example #1 ob_gzhandler() example
This should be a compressed page.
Notes
Note:
ob_gzhandler() requires the zlib extension.
Note:
You cannot use both ob_gzhandler() and zlib.output_compression. Also
note that using zlib.output_compression is preferred over
ob_gzhandler().
See Also
* ob_start() - Turn on output buffering
* ob_end_flush() - Flush (send) the output buffer and turn off output
buffering
----------------------------------------------------------------------
----------------------------------------------------------------------
ob_implicit_flush
(PHP 4, PHP 5)
ob_implicit_flush - Turn implicit flush on/off
Description
void ob_implicit_flush ([ int $flag = true ] )
ob_implicit_flush() will turn implicit flushing on or off. Implicit
flushing will result in a flush operation after every output call, so that
explicit calls to flush() will no longer be needed.
Parameters
flag
TRUE to turn implicit flushing on, FALSE otherwise.
Return Values
No value is returned.
See Also
* flush() - Flush the output buffer
* ob_start() - Turn on output buffering
* ob_end_flush() - Flush (send) the output buffer and turn off output
buffering
----------------------------------------------------------------------
----------------------------------------------------------------------
ob_list_handlers
(PHP 4 >= 4.3.0, PHP 5)
ob_list_handlers - List all output handlers in use
Description
array ob_list_handlers ( void )
Lists all output handlers in use.
Return Values
This will return an array with the output handlers in use (if any). If
output_buffering is enabled or an anonymous function was used with
ob_start(), ob_list_handlers() will return "default output handler".
Examples
Example #1 ob_list_handlers() example
The above example will output:
Array
(
[0] => default output handler
)
Array
(
[0] => ob_gzhandler
)
Array
(
[0] => default output handler
)
See Also
* ob_end_clean() - Clean (erase) the output buffer and turn off output
buffering
* ob_end_flush() - Flush (send) the output buffer and turn off output
buffering
* ob_get_flush() - Flush the output buffer, return it as a string and
turn off output buffering
* ob_start() - Turn on output buffering
----------------------------------------------------------------------
----------------------------------------------------------------------
ob_start
(PHP 4, PHP 5)
ob_start - Turn on output buffering
Description
bool ob_start ([ callback $output_callback [, int $chunk_size = 0 [, bool
$erase = true ]]] )
This function will turn output buffering on. While output buffering is
active no output is sent from the script (other than headers), instead the
output is stored in an internal buffer.
The contents of this internal buffer may be copied into a string variable
using ob_get_contents(). To output what is stored in the internal buffer,
use ob_end_flush(). Alternatively, ob_end_clean() will silently discard
the buffer contents.
Warning
Some web servers (e.g. Apache) change the working directory of a script
when calling the callback function. You can change it back by e.g.
chdir(dirname($_SERVER['SCRIPT_FILENAME'])) in the callback function.
Output buffers are stackable, that is, you may call ob_start() while
another ob_start() is active. Just make sure that you call ob_end_flush()
the appropriate number of times. If multiple output callback functions are
active, output is being filtered sequentially through each of them in
nesting order.
Parameters
output_callback
An optional output_callback function may be specified. This
function takes a string as a parameter and should return a string.
The function will be called when the output buffer is flushed
(sent) or cleaned (with ob_flush(), ob_clean() or similar
function) or when the output buffer is flushed to the browser at
the end of the request. When output_callback is called, it will
receive the contents of the output buffer as its parameter and is
expected to return a new output buffer as a result, which will be
sent to the browser. If the output_callback is not a callable
function, this function will return FALSE.
If the callback function has two parameters, the second parameter
is filled with a bit-field consisting of PHP_OUTPUT_HANDLER_START,
PHP_OUTPUT_HANDLER_CONT and PHP_OUTPUT_HANDLER_END.
If output_callback returns FALSE original input is sent to the
browser.
The output_callback parameter may be bypassed by passing a NULL
value.
ob_end_clean(), ob_end_flush(), ob_clean(), ob_flush() and
ob_start() may not be called from a callback function. If you call
them from callback function, the behavior is undefined. If you
would like to delete the contents of a buffer, return "" (a null
string) from callback function. You can't even call functions
using the output buffering functions like print_r($expression,
true) or highlight_file($filename, true) from a callback function.
Note:
In PHP 4.0.4, ob_gzhandler() was introduced to facilitate
sending gz-encoded data to web browsers that support compressed
web pages. ob_gzhandler() determines what type of content
encoding the browser will accept and will return its output
accordingly.
chunk_size
If the optional parameter chunk_size is passed, the buffer will be
flushed after any output call which causes the buffer's length to
equal or exceed chunk_size. Default value 0 means that the
function is called only in the end, other special value 1 sets
chunk_size to 4096.
erase
If the optional parameter erase is set to FALSE, the buffer will
not be deleted until the script finishes. This causes that
flushing and cleaning functions would issue a notice and return
FALSE if called.
Return Values
Returns TRUE on success or FALSE on failure.
Changelog
Version Description
4.3.2 This function was changed to return FALSE in case the passed
output_callback can not be executed.
4.2.0 Added the erase parameter.
Examples
Example #1 User defined callback function example
It's like comparing apples to oranges.
The above example will output:
It's like comparing oranges to oranges.
See Also
* ob_get_contents() - Return the contents of the output buffer
* ob_end_clean() - Clean (erase) the output buffer and turn off output
buffering
* ob_end_flush() - Flush (send) the output buffer and turn off output
buffering
* ob_implicit_flush() - Turn implicit flush on/off
* ob_gzhandler() - ob_start callback function to gzip output buffer
* ob_iconv_handler() - Convert character encoding as output buffer
handler
* mb_output_handler() - Callback function converts character encoding in
output buffer
* ob_tidyhandler() - ob_start callback function to repair the buffer
----------------------------------------------------------------------
----------------------------------------------------------------------
output_add_rewrite_var
(PHP 4 >= 4.3.0, PHP 5)
output_add_rewrite_var - Add URL rewriter values
Description
bool output_add_rewrite_var ( string $name , string $value )
This function adds another name/value pair to the URL rewrite mechanism.
The name and value will be added to URLs (as GET parameter) and forms (as
hidden input fields) the same way as the session ID when transparent URL
rewriting is enabled with session.use_trans_sid. Please note that absolute
URLs (http://example.com/..) aren't rewritten.
This function's behavior is controlled by the url_rewriter.tags php.ini
parameter.
Note: Calling this function will implicitly start output buffering if it
is not active already.
Parameters
name
The variable name.
value
The variable value.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 output_add_rewrite_var() example
link
link2 ';
// a form
echo '';
print_r(ob_list_handlers());
?>
The above example will output:
link
link2
Array
(
[0] => URL-Rewriter
)
See Also
* output_reset_rewrite_vars() - Reset URL rewriter values
* ob_flush() - Flush (send) the output buffer
* ob_list_handlers() - List all output handlers in use
----------------------------------------------------------------------
----------------------------------------------------------------------
output_reset_rewrite_vars
(PHP 4 >= 4.3.0, PHP 5)
output_reset_rewrite_vars - Reset URL rewriter values
Description
bool output_reset_rewrite_vars ( void )
This function resets the URL rewriter and removes all rewrite variables
previously set by the output_add_rewrite_var() function or the session
mechanism (if session.use_trans_sid was set on session_start()).
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 output_reset_rewrite_vars() example
link';
ob_flush();
output_reset_rewrite_vars();
echo 'link ';
?>
The above example will output:
link
link
See Also
* output_add_rewrite_var() - Add URL rewriter values
* ob_flush() - Flush (send) the output buffer
* ob_list_handlers() - List all output handlers in use
* session_start() - Initialize session data
----------------------------------------------------------------------
Table of Contents
* flush - Flush the output buffer
* ob_clean - Clean (erase) the output buffer
* ob_end_clean - Clean (erase) the output buffer and turn off output
buffering
* ob_end_flush - Flush (send) the output buffer and turn off output
buffering
* ob_flush - Flush (send) the output buffer
* ob_get_clean - Get current buffer contents and delete current output
buffer
* ob_get_contents - Return the contents of the output buffer
* ob_get_flush - Flush the output buffer, return it as a string and turn
off output buffering
* ob_get_length - Return the length of the output buffer
* ob_get_level - Return the nesting level of the output buffering
mechanism
* ob_get_status - Get status of output buffers
* ob_gzhandler - ob_start callback function to gzip output buffer
* ob_implicit_flush - Turn implicit flush on/off
* ob_list_handlers - List all output handlers in use
* ob_start - Turn on output buffering
* output_add_rewrite_var - Add URL rewriter values
* output_reset_rewrite_vars - Reset URL rewriter values
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* Basic usage
* Output Control Functions
* flush - Flush the output buffer
* ob_clean - Clean (erase) the output buffer
* ob_end_clean - Clean (erase) the output buffer and turn off
output buffering
* ob_end_flush - Flush (send) the output buffer and turn off output
buffering
* ob_flush - Flush (send) the output buffer
* ob_get_clean - Get current buffer contents and delete current
output buffer
* ob_get_contents - Return the contents of the output buffer
* ob_get_flush - Flush the output buffer, return it as a string and
turn off output buffering
* ob_get_length - Return the length of the output buffer
* ob_get_level - Return the nesting level of the output buffering
mechanism
* ob_get_status - Get status of output buffers
* ob_gzhandler - ob_start callback function to gzip output buffer
* ob_implicit_flush - Turn implicit flush on/off
* ob_list_handlers - List all output handlers in use
* ob_start - Turn on output buffering
* output_add_rewrite_var - Add URL rewriter values
* output_reset_rewrite_vars - Reset URL rewriter values
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit
----------------------------------------------------------------------
Introduction
The runkit extension provides means to modify constants, user-defined
functions, and user-defined classes. It also provides for custom
superglobal variables and embeddable sub-interpreters via sandboxing.
This package is meant as a feature added replacement for the >> classkit
package. When compiled with the --enable-runkit=classkit option to
./configure, it will export classkit compatible function definitions and
constants.
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
RUNKIT_IMPORT_FUNCTIONS (integer)
runkit_import() flag indicating that normal functions should be
imported from the specified file.
RUNKIT_IMPORT_CLASS_METHODS (integer)
runkit_import() flag indicating that class methods should be
imported from the specified file.
RUNKIT_IMPORT_CLASS_CONSTS (integer)
runkit_import() flag indicating that class constants should be
imported from the specified file. Note that this flag is only
meaningful in PHP versions 5.1.0 and above.
RUNKIT_IMPORT_CLASS_PROPS (integer)
runkit_import() flag indicating that class standard properties
should be imported from the specified file.
RUNKIT_IMPORT_CLASSES (integer)
runkit_import() flag representing a bitwise OR of the
RUNKIT_IMPORT_CLASS_* constants.
RUNKIT_IMPORT_OVERRIDE (integer)
runkit_import() flag indicating that if any of the imported
functions, methods, constants, or properties already exist, they
should be replaced with the new definitions. If this flag is not
set, then any imported definitions which already exist will be
discarded.
RUNKIT_ACC_PUBLIC (integer)
PHP 5 specific flag to runkit_method_add()
RUNKIT_ACC_PROTECTED (integer)
PHP 5 specific flag to runkit_method_add()
RUNKIT_ACC_PRIVATE (integer)
PHP 5 specific flag to runkit_method_add()
CLASSKIT_ACC_PUBLIC (integer)
PHP 5 specific flag to classkit_method_add() Only defined when
classkit compatibility is enabled.
CLASSKIT_ACC_PROTECTED (integer)
PHP 5 specific flag to classkit_method_add() Only defined when
classkit compatibility is enabled.
CLASSKIT_ACC_PRIVATE (integer)
PHP 5 specific flag to classkit_method_add() Only defined when
classkit compatibility is enabled.
CLASSKIT_AGGREGATE_OVERRIDE (integer)
PHP 5 specific flag to classkit_import() Only defined when
classkit compatibility is enabled.
RUNKIT_VERSION (string)
Defined to the current version of the runkit package.
CLASSKIT_VERSION (string)
Defined to the current version of the runkit package. Only defined
when classkit compatibility is enabled.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
Modifying Constants, Functions, Classes, and Methods works with all
releases of PHP 4 and PHP 5. No special requirements are necessary.
Custom Superglobals are only available in PHP 4.2.0 or later.
Sandboxing requires PHP 5.1.0 or later, or PHP 5.0.0 with a special TSRM
patch applied. Regardless of which version of PHP is in use it must be
compiled with the --enable-maintainer-zts option. See the README file in
the runkit package for additional information.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
This >> PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here: >> http://pecl.php.net/package/runkit.
A DLL for this PECL extension is currently unavailable. See also the
building on Windows section.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Runkit Configuration Options
Name Default Changeable Changelog
runkit.superglobal "" PHP_INI_PERDIR
runkit.internal_override "0" PHP_INI_SYSTEM
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
runkit.superglobal string
Comma-separated list of variable names to be treated as
superglobals. This value should be set in the systemwide php.ini
file, but may work in perdir configuration contexts depending on
your SAPI.
Example #1 Custom Superglobals with runkit.superglobal=_FOO,_BAR
in php.ini
runkit.internal_override boolean
Enables ability to modify/rename/remove internal functions.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit Functions
----------------------------------------------------------------------
Runkit_Sandbox
(PECL runkit >= 0.7.0)
Runkit_Sandbox - Runkit Sandbox Class -- PHP Virtual Machine
Description
Instantiating the Runkit_Sandbox class creates a new thread with its own
scope and program stack. Using a set of options passed to the constructor,
this environment may be restricted to a subset of what the primary
interpreter can do and provide a safer environment for executing user
supplied code.
Note: Sandbox support (required for runkit_lint(), runkit_lint_file(),
and the Runkit_Sandbox class) is only available as of PHP 5.1.0 or
specially patched versions of PHP 5.0, and requires that thread safety
be enabled. See the README file included in the runkit package for more
information.
Constructor
void Runkit_Sandbox::__construct ([ array $options ] )
options is an associative array containing any combination of the special
ini options listed below.
safe_mode
If the outer script which is instantiating the Runkit_Sandbox
class is configured with safe_mode = off, then safe_mode may be
turned on for the sandbox environment. This setting can not be
used to disable safe_mode when it's already enabled in the outer
script.
safe_mode_gid
If the outer script which is instantiating the Runkit_Sandbox
class is configured with safe_mode_gid = on, then safe_mode_gid
may be turned off for the sandbox environment. This setting can
not be used to enable safe_mode_gid when it's already disabled in
the outer script.
safe_mode_include_dir
If the outer script which is instantiating the Runkit_Sandbox
class is configured with a safe_mode_include_dir, then a new
safe_mode_include_dir may be set for sandbox environments below
the currently defined value. safe_mode_include_dir may also be
cleared to indicate that the bypass feature is disabled. If
safe_mode_include_dir was blank in the outer script, but safe_mode
was not enabled, then any arbitrary safe_mode_include_dir may be
set while turning safe_mode on.
open_basedir
open_basedir may be set to any path below the current setting of
open_basedir. If open_basedir is not set within the global scope,
then it is assumed to be the root directory and may be set to any
location.
allow_url_fopen
Like safe_mode, this setting can only be made more restrictive, in
this case by setting it to FALSE when it is previously set to TRUE
disable_functions
Comma separated list of functions to disable within the sandbox
sub-interpreter. This list need not contain the names of the
currently disabled functions, they will remain disabled whether
listed here or not.
disable_classes
Comma separated list of classes to disable within the sandbox
sub-interpreter. This list need not contain the names of the
currently disabled classes, they will remain disabled whether
listed here or not.
runkit.superglobal
Comma separated list of variables to be treated as superglobals
within the sandbox sub-interpreter. These variables will be used
in addition to any variables defined internally or through the
global runkit.superglobal setting.
runkit.internal_override
Ini option runkit.internal_override may be disabled (but not
re-enabled) within sandboxes.
Example #1 Instantiating a restricted sandbox
true,
'open_basedir'=>'/var/www/users/jdoe/',
'allow_url_fopen'=>'false',
'disable_functions'=>'exec,shell_exec,passthru,system',
'disable_classes'=>'myAppClass');
$sandbox = new Runkit_Sandbox($options);
/* Non-protected ini settings may set normally */
$sandbox->ini_set('html_errors',true);
?>
Accessing Variables
All variables in the global scope of the sandbox environment are
accessible as properties of the sandbox object. The first thing to note is
that because of the way memory between these two threads is managed,
object and resource variables can not currently be exchanged between
interpreters. Additionally, all arrays are deep copied and any references
will be lost. This also means that references between interpreters are not
possible.
Example #2 Working with variables in a sandbox
foo = 'bar';
$sandbox->eval('echo "$foo\n"; $bar = $foo . "baz";');
echo "{$sandbox->bar}\n";
if (isset($sandbox->foo)) unset($sandbox->foo);
$sandbox->eval('var_dump(isset($foo));');
?>
The above example will output:
bar
barbaz
bool(false)
Calling PHP Functions
Any function defined within the sandbox may be called as a method on the
sandbox object. This also includes a few pseudo-function language
constructs: eval(), include(), include_once(), require(), require_once(),
echo(), print(), die(), and exit().
Example #3 Calling sandbox functions
str_replace('a','f','abc');
?>
The above example will output:
fbc
When passing arguments to a sandbox function, the arguments are taken from
the outer instance of PHP. If you wish to pass arguments from the
sandbox's scope, be sure to access them as properties of the sandbox
object as illustrated above.
Example #4 Passing arguments to sandbox functions
foo = 'baz';
echo $sandbox->str_replace('a',$foo,'a');
echo $sandbox->str_replace('a',$sandbox->foo,'a');
?>
The above example will output:
bar
baz
Changing Sandbox Settings
As of runkit version 0.5, certain Sandbox settings may be modified on the
fly using ArrayAccess syntax. Some settings, such as active are read-only
and meant to provide status information. Other settings, such as
output_handler may be set and read much like a normal array offset. Future
settings may be write-only, however no such settings currently exist.
Sandbox Settings / Status Indicators
Setting Type Purpose Default
TRUE if the Sandbox is still in a
Boolean usable state, FALSE if the request TRUE
active (Read Only) is in bailout due to a call to (Initial)
die(), exit(), or because of a fatal
error condition.
When set to a valid callback, all
output generated by the Sandbox
instance will be processed through
output_handler Callback the named function. Sandbox output None
handlers follow the same calling
conventions as the system-wide
output handler.
May the sandbox use instances of the
Runkit_Sandbox_Parent class? Must be
parent_access Boolean enabled for other FALSE
Runkit_Sandbox_Parent related
settings to work.
parent_read Boolean May the sandbox read variables in FALSE
its parent's context?
parent_write Boolean May the sandbox modify variables in FALSE
its parent's context?
May the sandbox evaluate arbitrary
parent_eval Boolean code in its parent's context? FALSE
DANGEROUS
May the sandbox include php code
parent_include Boolean files in its parent's context? FALSE
DANGEROUS
May the sandbox echo data in its
parent_echo Boolean parent's context effectively FALSE
bypassing its own output_handler?
parent_call Boolean May the sandbox call functions in FALSE
its parent's context?
parent_die Boolean May the sandbox kill its own parent? FALSE
(And thus itself)
What scope will parental property
access look at? 0 == Global scope, 1
parent_scope Integer == Calling scope, 2 == Scope 0 (Global)
preceeding calling scope, 3 == The
scope before that, etc..., etc...
When parent_scope is set to a string
value, it refers to a named array
variable in the global scope. If the
named variable does not exist at the
parent_scope String time of access it will be created as
an empty array. If the variable
exists but it not an array, a dummy
array will be created containing a
reference to the named global
variable.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runkit_Sandbox_Parent
(PECL runkit >= 0.7.0)
Runkit_Sandbox_Parent - Runkit Anti-Sandbox Class
Description
void Runkit_Sandbox_Parent::__construct ( void )
Instantiating the Runkit_Sandbox_Parent class from within a sandbox
environment created from the Runkit_Sandbox class provides some
(controlled) means for a sandbox child to access its parent.
Note: Sandbox support (required for runkit_lint(), runkit_lint_file(),
and the Runkit_Sandbox class) is only available as of PHP 5.1.0 or
specially patched versions of PHP 5.0, and requires that thread safety
be enabled. See the README file included in the runkit package for more
information.
In order for any of the Runkit_Sandbox_Parent features to function.
Support must be enabled on a per-sandbox basis by enabling the
parent_access flag from the parent's context.
Example #1 Working with variables in a sandbox
Accessing the Parent's Variables
Just as with sandbox variable access, a sandbox parent's variables may be
read from and written to as properties of the Runkit_Sandbox_Parent class.
Read access to parental variables may be enabled with the parent_read
setting (in addition to the base parent_access setting). Write access, in
turn, is enabled through the parent_write setting.
Unlike sandbox child variable access, the variable scope is not limited to
globals only. By setting the parent_scope setting to an appropriate
integer value, other scopes in the active call stack may be inspected
instead. A value of 0 (Default) will direct variable access at the global
scope. 1 will point variable access at whatever variable scope was active
at the time the current block of sandbox code was executed. Higher values
progress back through the functions that called the functions that led to
the sandbox executing code that tried to access its own parent's
variables.
Example #2 Accessing parental variables
eval('$PARENT = new Runkit_Sandbox_Parent;');
$php['parent_scope'] = 0;
one();
$php['parent_scope'] = 1;
one();
$php['parent_scope'] = 2;
one();
$php['parent_scope'] = 3;
one();
$php['parent_scope'] = 4;
one();
$php['parent_scope'] = 5;
one();
function one() {
$test = "one()";
two();
}
function two() {
$test = "two()";
three();
}
function three() {
$test = "three()";
$GLOBALS['php']->eval('var_dump($PARENT->test);');
}
?>
The above example will output:
string(6) "Global"
string(7) "three()"
string(5) "two()"
string(5) "one()"
string(6) "Global"
string(6) "Global"
Calling the Parent's Functions
Just as with sandbox access, a sandbox may access its parents functions
providing that the proper settings have been enabled. Enabling parent_call
will allow the sandbox to call all functions available to the parent
scope. Language constructs are each controlled by their own setting:
print() and echo() are enabled with parent_echo. die() and exit() are
enabled with parent_die. eval() is enabled with parent_eval while
include(), include_once(), require(), and require_once() are enabled
through parent_include.
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit_class_adopt
(PECL runkit >= 0.7.0)
runkit_class_adopt - Convert a base class to an inherited class, add
ancestral methods when appropriate
Description
bool runkit_class_adopt ( string $classname , string $parentname )
Parameters
classname
Name of class to be adopted
parentname
Parent class which child class is extending
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 A runkit_class_adopt() example
The above example will output:
Parent Function Output
See Also
* runkit_class_emancipate() - Convert an inherited class to a base
class, removes any method whose scope is ancestral
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit_class_emancipate
(PECL runkit >= 0.7.0)
runkit_class_emancipate - Convert an inherited class to a base class,
removes any method whose scope is ancestral
Description
bool runkit_class_emancipate ( string $classname )
Parameters
classname
Name of class to emancipate
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 A runkit_class_emancipate() example
The above example will output:
Parent Function Output
Fatal error: Call to undefined function: parentFunc() in example.php on line 12
See Also
* runkit_class_adopt() - Convert a base class to an inherited class, add
ancestral methods when appropriate
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit_constant_add
(PECL runkit >= 0.7.0)
runkit_constant_add - Similar to define(), but allows defining in class
definitions as well
Description
bool runkit_constant_add ( string $constname , mixed $value )
Parameters
constname
Name of constant to declare. Either a string to indicate a global
constant, or classname::constname to indicate a class constant.
value
NULL, Bool, Long, Double, String, or Resource value to store in
the new constant.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* define() - Defines a named constant
* runkit_constant_redefine() - Redefine an already defined constant
* runkit_constant_remove() - Remove/Delete an already defined constant
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit_constant_redefine
(PECL runkit >= 0.7.0)
runkit_constant_redefine - Redefine an already defined constant
Description
bool runkit_constant_redefine ( string $constname , mixed $newvalue )
Parameters
constname
Constant to redefine. Either string indicating global constant, or
classname::constname indicating class constant.
newvalue
New value to assign to constant.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* runkit_constant_add() - Similar to define(), but allows defining in
class definitions as well
* runkit_constant_remove() - Remove/Delete an already defined constant
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit_constant_remove
(PECL runkit >= 0.7.0)
runkit_constant_remove - Remove/Delete an already defined constant
Description
bool runkit_constant_remove ( string $constname )
Parameters
constname
Name of constant to remove. Either a string indicating a global
constant, or classname::constname indicating a class constant.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* define() - Defines a named constant
* runkit_constant_add() - Similar to define(), but allows defining in
class definitions as well
* runkit_constant_redefine() - Redefine an already defined constant
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit_function_add
(PECL runkit >= 0.7.0)
runkit_function_add - Add a new function, similar to create_function()
Description
bool runkit_function_add ( string $funcname , string $arglist , string
$code )
Parameters
funcname
Name of function to be created
arglist
Comma separated argument list
code
Code making up the function
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 A runkit_function_add() example
The above example will output:
The value of a is 1
The value of b is 2
See Also
* create_function() - Create an anonymous (lambda-style) function
* runkit_function_redefine() - Replace a function definition with a new
implementation
* runkit_function_copy() - Copy a function to a new function name
* runkit_function_rename() - Change a function's name
* runkit_function_remove() - Remove a function definition
* runkit_method_add() - Dynamically adds a new method to a given class
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit_function_copy
(PECL runkit >= 0.7.0)
runkit_function_copy - Copy a function to a new function name
Description
bool runkit_function_copy ( string $funcname , string $targetname )
Parameters
funcname
Name of existing function
targetname
Name of new function to copy definition to
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 A runkit_function_copy() example
The above example will output:
In a function
In a function
See Also
* runkit_function_add() - Add a new function, similar to create_function
* runkit_function_redefine() - Replace a function definition with a new
implementation
* runkit_function_rename() - Change a function's name
* runkit_function_remove() - Remove a function definition
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit_function_redefine
(PECL runkit >= 0.7.0)
runkit_function_redefine - Replace a function definition with a new
implementation
Description
bool runkit_function_redefine ( string $funcname , string $arglist ,
string $code )
Note: By default, only userspace functions may be removed, renamed, or
modified. In order to override internal functions, you must enable the
runkit.internal_override setting in php.ini.
Parameters
funcname
Name of function to redefine
arglist
New list of arguments to be accepted by function
code
New code implementation
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 A runkit_function_redefine() example
The above example will output:
Original Testme Implementation
New Testme Implementation
See Also
* runkit_function_add() - Add a new function, similar to create_function
* runkit_function_copy() - Copy a function to a new function name
* runkit_function_rename() - Change a function's name
* runkit_function_remove() - Remove a function definition
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit_function_remove
(PECL runkit >= 0.7.0)
runkit_function_remove - Remove a function definition
Description
bool runkit_function_remove ( string $funcname )
Note: By default, only userspace functions may be removed, renamed, or
modified. In order to override internal functions, you must enable the
runkit.internal_override setting in php.ini.
Parameters
funcname
Name of function to be deleted
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* runkit_function_add() - Add a new function, similar to create_function
* runkit_function_copy() - Copy a function to a new function name
* runkit_function_redefine() - Replace a function definition with a new
implementation
* runkit_function_rename() - Change a function's name
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit_function_rename
(PECL runkit >= 0.7.0)
runkit_function_rename - Change a function's name
Description
bool runkit_function_rename ( string $funcname , string $newname )
Note: By default, only userspace functions may be removed, renamed, or
modified. In order to override internal functions, you must enable the
runkit.internal_override setting in php.ini.
Parameters
funcname
Current function name
newname
New function name
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* runkit_function_add() - Add a new function, similar to create_function
* runkit_function_copy() - Copy a function to a new function name
* runkit_function_redefine() - Replace a function definition with a new
implementation
* runkit_function_remove() - Remove a function definition
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit_import
(PECL runkit >= 0.7.0)
runkit_import - Process a PHP file importing function and class
definitions, overwriting where appropriate
Description
bool runkit_import ( string $filename [, int $flags =
RUNKIT_IMPORT_CLASS_METHODS ] )
Similar to include() however any code residing outside of a function or
class is simply ignored. Additionally, depending on the value of flags,
any functions or classes which already exist in the currently running
environment will be automatically overwritten by their new definitions.
Parameters
filename
Filename to import function and class definitions from
flags
Bitwise OR of the RUNKIT_IMPORT_* family of constants.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit_lint_file
(PECL runkit >= 0.7.0)
runkit_lint_file - Check the PHP syntax of the specified file
Description
bool runkit_lint_file ( string $filename )
The runkit_lint_file() function performs a syntax (lint) check on the
specified filename testing for scripting errors. This is similar to using
php -l from the commandline.
Note: Sandbox support (required for runkit_lint(), runkit_lint_file(),
and the Runkit_Sandbox class) is only available as of PHP 5.1.0 or
specially patched versions of PHP 5.0, and requires that thread safety
be enabled. See the README file included in the runkit package for more
information.
Parameters
filename
File containing PHP Code to be lint checked
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* runkit_lint() - Check the PHP syntax of the specified php code
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit_lint
(PECL runkit >= 0.7.0)
runkit_lint - Check the PHP syntax of the specified php code
Description
bool runkit_lint ( string $code )
The runkit_lint() function performs a syntax (lint) check on the specified
php code testing for scripting errors. This is similar to using php -l
from the command line except runkit_lint() accepts actual code rather than
a filename.
Note: Sandbox support (required for runkit_lint(), runkit_lint_file(),
and the Runkit_Sandbox class) is only available as of PHP 5.1.0 or
specially patched versions of PHP 5.0, and requires that thread safety
be enabled. See the README file included in the runkit package for more
information.
Parameters
code
PHP Code to be lint checked
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* runkit_lint_file() - Check the PHP syntax of the specified file
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit_method_add
(PECL runkit >= 0.7.0)
runkit_method_add - Dynamically adds a new method to a given class
Description
bool runkit_method_add ( string $classname , string $methodname , string
$args , string $code [, int $flags = RUNKIT_ACC_PUBLIC ] )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Parameters
classname
The class to which this method will be added
methodname
The name of the method to add
args
Comma-delimited list of arguments for the newly-created method
code
The code to be evaluated when methodname is called
flags
The type of method to create, can be RUNKIT_ACC_PUBLIC,
RUNKIT_ACC_PROTECTED or RUNKIT_ACC_PRIVATE
Note:
This parameter is only used as of PHP 5, because, prior to this,
all methods were public.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 runkit_method_add() example
add(12, 4);
?>
The above example will output:
16
See Also
* runkit_method_copy() - Copies a method from class to another
* runkit_method_redefine() - Dynamically changes the code of the given
method
* runkit_method_remove() - Dynamically removes the given method
* runkit_method_rename() - Dynamically changes the name of the given
method
* runkit_function_add() - Add a new function, similar to create_function
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit_method_copy
(PECL runkit >= 0.7.0)
runkit_method_copy - Copies a method from class to another
Description
bool runkit_method_copy ( string $dClass , string $dMethod , string
$sClass [, string $sMethod ] )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Parameters
dClass
Destination class for copied method
dMethod
Destination method name
sClass
Source class of the method to copy
sMethod
Name of the method to copy from the source class. If this
parameter is omitted, the value of dMethod is assumed.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 runkit_method_copy() example
The above example will output:
foo!
See Also
* runkit_method_add() - Dynamically adds a new method to a given class
* runkit_method_redefine() - Dynamically changes the code of the given
method
* runkit_method_remove() - Dynamically removes the given method
* runkit_method_rename() - Dynamically changes the name of the given
method
* runkit_function_copy() - Copy a function to a new function name
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit_method_redefine
(PECL runkit >= 0.7.0)
runkit_method_redefine - Dynamically changes the code of the given method
Description
bool runkit_method_redefine ( string $classname , string $methodname ,
string $args , string $code [, int $flags = RUNKIT_ACC_PUBLIC ] )
Note: This function cannot be used to manipulate the currently running
(or chained) method.
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Parameters
classname
The class in which to redefine the method
methodname
The name of the method to redefine
args
Comma-delimited list of arguments for the redefined method
code
The new code to be evaluated when methodname is called
flags
The redefined method can be RUNKIT_ACC_PUBLIC,
RUNKIT_ACC_PROTECTED or RUNKIT_ACC_PRIVATE
Note:
This parameter is only used as of PHP 5, because, prior to this,
all methods were public.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 runkit_method_redefine() example
foo();
// Redefine the 'foo' method
runkit_method_redefine(
'Example',
'foo',
'',
'return "bar!\n";',
RUNKIT_ACC_PUBLIC
);
// output Example::foo() (after redefine)
echo "After: " . $e->foo();
?>
The above example will output:
Before: foo!
After: bar!
See Also
* runkit_method_add() - Dynamically adds a new method to a given class
* runkit_method_copy() - Copies a method from class to another
* runkit_method_remove() - Dynamically removes the given method
* runkit_method_rename() - Dynamically changes the name of the given
method
* runkit_function_redefine() - Replace a function definition with a new
implementation
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit_method_remove
(PECL runkit >= 0.7.0)
runkit_method_remove - Dynamically removes the given method
Description
bool runkit_method_remove ( string $classname , string $methodname )
Note: This function cannot be used to manipulate the currently running
(or chained) method.
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Parameters
classname
The class in which to remove the method
methodname
The name of the method to remove
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 runkit_method_remove() example
The above example will output:
bar
See Also
* runkit_method_add() - Dynamically adds a new method to a given class
* runkit_method_copy() - Copies a method from class to another
* runkit_method_redefine() - Dynamically changes the code of the given
method
* runkit_method_rename() - Dynamically changes the name of the given
method
* runkit_function_remove() - Remove a function definition
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit_method_rename
(PECL runkit >= 0.7.0)
runkit_method_rename - Dynamically changes the name of the given method
Description
bool runkit_method_rename ( string $classname , string $methodname ,
string $newname )
Note: This function cannot be used to manipulate the currently running
(or chained) method.
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Parameters
classname
The class in which to rename the method
methodname
The name of the method to rename
newname
The new name to give to the renamed method
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 runkit_method_rename() example
The above example will output:
foo!
See Also
* runkit_method_add() - Dynamically adds a new method to a given class
* runkit_method_copy() - Copies a method from class to another
* runkit_method_redefine() - Dynamically changes the code of the given
method
* runkit_method_remove() - Dynamically removes the given method
* runkit_function_rename() - Change a function's name
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit_return_value_used
(PECL runkit >= 0.8.0)
runkit_return_value_used - Determines if the current functions return
value will be used
Description
bool runkit_return_value_used ( void )
Return Values
Returns TRUE if the function's return value is used by the calling scope,
otherwise FALSE
Examples
Example #1 runkit_return_value_used() example
The above example will output:
bool(false)
bool(true)
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit_sandbox_output_handler
(PECL runkit >= 0.7.0)
runkit_sandbox_output_handler - Specify a function to capture and/or
process output from a runkit sandbox
Description
mixed runkit_sandbox_output_handler ( object $sandbox [, mixed $callback ]
)
Ordinarily, anything output (such as with echo() or print()) will be
output as though it were printed from the parent's scope. Using
runkit_sandbox_output_handler() however, output generated by the sandbox
(including errors), can be captured by a function outside of the sandbox.
Note: Sandbox support (required for runkit_lint(), runkit_lint_file(),
and the Runkit_Sandbox class) is only available as of PHP 5.1.0 or
specially patched versions of PHP 5.0, and requires that thread safety
be enabled. See the README file included in the runkit package for more
information.
Note: Deprecated
As of runkit version 0.5, this function is deprecated and is scheduled
to be removed from the package prior to a 1.0 release. The output
handler for a given Runkit_Sandbox instance may be read/set using the
array offset syntax shown on the Runkit_Sandbox class definition page.
Parameters
sandbox
Object instance of Runkit_Sandbox class on which to set output
handling.
callback
Name of a function which expects one parameter. Output generated
by sandbox will be passed to this callback. Anything returned by
the callback will be displayed normally. If this parameter is not
passed then output handling will not be changed. If a non-truth
value is passed, output handling will be disabled and will revert
to direct display.
Return Values
Returns the name of the previously defined output handler callback, or
FALSE if no handler was previously defined.
Examples
Example #1 Feeding output to a variable
echo("Hello\n");
$php->eval('var_dump("Excuse me");');
$php->die("I lost myself.");
unset($php);
echo "Sandbox Complete\n\n";
echo $sandbox_output;
?>
The above example will output:
Sandbox Complete
Hello
string(9) "Excuse me"
I lost myself.
----------------------------------------------------------------------
----------------------------------------------------------------------
runkit_superglobals
(PECL runkit >= 0.7.0)
runkit_superglobals - Return numerically indexed array of registered
superglobals
Description
array runkit_superglobals ( void )
Return Values
Returns a numerically indexed array of the currently registered
superglobals. i.e. _GET, _POST, _REQUEST, _COOKIE, _SESSION, _SERVER,
_ENV, _FILES
See Also
* Variable Scope
----------------------------------------------------------------------
Table of Contents
* Runkit_Sandbox - Runkit Sandbox Class -- PHP Virtual Machine
* Runkit_Sandbox_Parent - Runkit Anti-Sandbox Class
* runkit_class_adopt - Convert a base class to an inherited class, add
ancestral methods when appropriate
* runkit_class_emancipate - Convert an inherited class to a base class,
removes any method whose scope is ancestral
* runkit_constant_add - Similar to define(), but allows defining in
class definitions as well
* runkit_constant_redefine - Redefine an already defined constant
* runkit_constant_remove - Remove/Delete an already defined constant
* runkit_function_add - Add a new function, similar to create_function
* runkit_function_copy - Copy a function to a new function name
* runkit_function_redefine - Replace a function definition with a new
implementation
* runkit_function_remove - Remove a function definition
* runkit_function_rename - Change a function's name
* runkit_import - Process a PHP file importing function and class
definitions, overwriting where appropriate
* runkit_lint_file - Check the PHP syntax of the specified file
* runkit_lint - Check the PHP syntax of the specified php code
* runkit_method_add - Dynamically adds a new method to a given class
* runkit_method_copy - Copies a method from class to another
* runkit_method_redefine - Dynamically changes the code of the given
method
* runkit_method_remove - Dynamically removes the given method
* runkit_method_rename - Dynamically changes the name of the given
method
* runkit_return_value_used - Determines if the current functions return
value will be used
* runkit_sandbox_output_handler - Specify a function to capture and/or
process output from a runkit sandbox
* runkit_superglobals - Return numerically indexed array of registered
superglobals
----------------------------------------------------------------------
* Introduction
* Predefined Constants
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* runkit Functions
* Runkit_Sandbox - Runkit Sandbox Class -- PHP Virtual Machine
* Runkit_Sandbox_Parent - Runkit Anti-Sandbox Class
* runkit_class_adopt - Convert a base class to an inherited class,
add ancestral methods when appropriate
* runkit_class_emancipate - Convert an inherited class to a base
class, removes any method whose scope is ancestral
* runkit_constant_add - Similar to define(), but allows defining in
class definitions as well
* runkit_constant_redefine - Redefine an already defined constant
* runkit_constant_remove - Remove/Delete an already defined
constant
* runkit_function_add - Add a new function, similar to
create_function
* runkit_function_copy - Copy a function to a new function name
* runkit_function_redefine - Replace a function definition with a
new implementation
* runkit_function_remove - Remove a function definition
* runkit_function_rename - Change a function's name
* runkit_import - Process a PHP file importing function and class
definitions, overwriting where appropriate
* runkit_lint_file - Check the PHP syntax of the specified file
* runkit_lint - Check the PHP syntax of the specified php code
* runkit_method_add - Dynamically adds a new method to a given
class
* runkit_method_copy - Copies a method from class to another
* runkit_method_redefine - Dynamically changes the code of the
given method
* runkit_method_remove - Dynamically removes the given method
* runkit_method_rename - Dynamically changes the name of the given
method
* runkit_return_value_used - Determines if the current functions
return value will be used
* runkit_sandbox_output_handler - Specify a function to capture
and/or process output from a runkit sandbox
* runkit_superglobals - Return numerically indexed array of
registered superglobals
----------------------------------------------------------------------
----------------------------------------------------------------------
Break the silence operator
----------------------------------------------------------------------
Introduction
The scream extension gives the possibility to disable the silencing error
control operator so all errors are being reported. This feature is
controlled by an ini setting.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
PHP version 5.2.0 or greater.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here: >> http://pecl.php.net/package/scream
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
scream Configure Options
Name Default Changeable Changelog
scream.enabled Off PHP_INI_ALL
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
scream.enabled int
Whether or not to enable scream.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Table of Contents
* Example that shows the effect of scream
----------------------------------------------------------------------
Example that shows the effect of scream
This example demonstrates how scream affects the behaviour of PHP's error
handler.
Example #1 Enabling and disabling scream at runtime
The above example will output something similar to:
Opening http://example.com/not-existing-file
Opening http://example.com/not-existing-file
Warning: fopen(http://example.com/another-not-existing-file): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in example.php on line 14
Note: Usually one would set this in the php.ini configuration file
instead of changing the code.
----------------------------------------------------------------------
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Examples
* Example that shows the effect of scream
----------------------------------------------------------------------
----------------------------------------------------------------------
Windows Cache for PHP
----------------------------------------------------------------------
Introduction
Windows Cache Extension for PHP is a PHP accelerator that is used to
increase the speed of PHP applications running on Windows and Windows
Server. Once the Windows Cache Extension for PHP is enabled and loaded by
the PHP engine, PHP applications can take advantage of the functionality
without any code modifications.
The Windows Cache Extension includes 5 different types of caches. The
following describes the purpose of each cache type and the benefits it
provides.
* PHP Opcode Cache - PHP is a script processing engine, which reads an
input stream of data that contains text and/or PHP instructions and
produces another stream of data, most commonly in the HTML format.
This means that on a web server the PHP engine reads, parses, compiles
and executes a PHP script each time that it is requested by a Web
client. The reading, parsing and compilation operations put additional
load on the web server's CPU and file system and thus affect the
overall performance of a PHP web application. The PHP bytecode
(opcode) cache is used to store the compiled script bytecode in shared
memory so that it can be re-used by PHP engine for subsequent
executions of the same script.
* File Cache - Even with the PHP opcode cache enabled, the PHP engine
has to accesses the script files on a file system. When PHP scripts
are stored on a remote UNC file share, the file operations introduce a
significant performance overhead. The Windows Cache Extension for PHP
includes a file cache that is used to store the content of the PHP
script files in shared memory, which reduces the amount of file system
operations performed by PHP engine.
* Resolve File Path Cache - PHP scripts very often include or operate
with files by using relative file paths. Every file path has to be
normalized to an absolute file path by the PHP engine. When a PHP
application uses many PHP files and accesses them by relative paths,
the operation of resolving the paths may negatively impact the
application's performance. The Windows Cache Extension for PHP
provides a Resolve File Path cache, which is used to store the
mappings between relative and absolute file paths, thereby reducing
the number of path resolutions that the PHP engine has to perform.
* User Cache (available since version 1.1.0) - PHP scripts can take
advantage of the shared memory cache by using the user cache API's.
PHP objects and variables can be stored in the user cache and then
re-used on subsequent requests. This can be used to improve
performance of PHP scripts and to share the data across multiple PHP
processes.
* Session Handler (available since version 1.1.0) - The WinCache session
handler can be used to store the PHP session data in the shared memory
cache. This avoids file system operations for reading and writing
session data, which improves performance when large amount of data is
stored in PHP session.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* WinCache Statistics Script
* WinCache Session Handler
* WinCache Functions Reroutes
* Resource Types
----------------------------------------------------------------------
Requirements
The extension is currently supported only on the following configurations:
Windows OS:
* Windows XP SP3 with IIS 5.1 and >> FastCGI Extension
* Windows Server 2003 with IIS 6.0 and >> FastCGI Extension
* Windows Vista SP1 with IIS 7.0 and FastCGI Module
* Windows Server 2008 with IIS 7.0 and FastCGI Module
* Windows 7 with IIS 7.5 and FastCGI Module
* Windows Server 2008 R2 with IIS 7.5 and FastCGI Module
PHP:
* PHP 5.2.X, Non-thread-safe build
* PHP 5.3 X86, Non-thread-safe VC9 build
Note: The WinCache Extension can only be used when IIS is configured to
run PHP via FastCGI.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
This >> PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here: >> http://pecl.php.net/package/wincache.
There are two packages for this extension: one package is for PHP versions
5.2.X, and the other package is for PHP 5.3.X. Select the package that is
appropriate for the PHP version being used.
To install and enable the extension, follow these steps:
1. Unpack the package into some temporary location.
2. Copy the php_wincache.dll file into the PHP extensions folder.
Typically this folder is called "ext" and it is located in the same
folder with all PHP binary files. For example: C:\Program
Files\PHP\ext.
3. Using a text editor, open the php.ini file, which is usually located
in the same folder where all PHP binary files are. For example:
C:\Program Files\PHP\php.ini.
4. Add the following line at the end of the php.ini file: extension =
php_wincache.dll.
5. Save and close the php.ini file.
6. Recycle the IIS Application Pools for PHP to pick up the configuration
changes. To check that the extension has been enabled, create a file
called phpinfo.php with a PHP code that calls phpinfo function.
7. Save the phpinfo.php file in the root folder of a IIS web site that
uses PHP, then open a browser and make a request to
http://localhost/phpinfo.php. Search within the returned web page for
a section called wincache. If the extension is enabled, then the
phpinfo output will list the configuration settings provided by the
WinCache.
Note: Do not forget to remove phpinfo.php file from the web site's root
folder after verifying that extension has been enabled.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
The following table lists and explains the configuration settings provided
by the WinCache extension:
WinCache configuration options
Name Default Minimum Maximum Changeable Changelog
Available
wincache.fcenabled "1" "0" "1" PHP_INI_ALL since
WinCache
1.0.0
Available
wincache.fcenabledfilter "NULL" "NULL" "NULL" PHP_INI_SYSTEM since
WinCache
1.0.0
Available
wincache.fcachesize "24" "5" "255" PHP_INI_SYSTEM since
WinCache
1.0.0
Available
wincache.fcndetect "1" "0" "1" PHP_INI_SYSTEM since
WinCache
1.1.0
Available
wincache.maxfilesize "256" "10" "2048" PHP_INI_SYSTEM since
WinCache
1.0.0
Available
wincache.ocenabled "1" "0" "1" PHP_INI_ALL since
WinCache
1.0.0
Available
wincache.ocenabledfilter "NULL" "NULL" "NULL" PHP_INI_SYSTEM since
WinCache
1.0.0
Available
wincache.ocachesize "96" "15" "255" PHP_INI_SYSTEM since
WinCache
1.0.0
Available
wincache.filecount "4096" "1024" "16384" PHP_INI_SYSTEM since
WinCache
1.0.0
Available
wincache.chkinterval "30" "0" "300" PHP_INI_SYSTEM since
WinCache
1.0.0
Available
wincache.ttlmax "1200" "0" "7200" PHP_INI_SYSTEM since
WinCache
1.0.0
Available
wincache.enablecli 0 0 1 PHP_INI_SYSTEM since
WinCache
1.0.0
Available
wincache.ignorelist NULL NULL NULL PHP_INI_ALL since
WinCache
1.0.0
Available
wincache.namesalt NULL NULL NULL PHP_INI_SYSTEM since
WinCache
1.0.0
Available
wincache.ucenabled 1 0 1 PHP_INI_SYSTEM since
WinCache
1.1.0
Available
wincache.ucachesize 8 5 85 PHP_INI_SYSTEM since
WinCache
1.1.0
Available
wincache.scachesize 8 5 85 PHP_INI_SYSTEM since
WinCache
1.1.0
Available
wincache.rerouteini NULL NULL NULL PHP_INI_SYSTEM since
WinCache
1.2.0
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
wincache.fcenabled boolean
Enables or disables the file cache functionality.
wincache.fcenabledfilter string
Defines a comma-separated list of IIS web site identifiers where
file cache should be enabled or disabled. This setting works in
conjunction with wincache.fcenabled: if wincache.fcenabled is set
to 1, then the sites listed in the wincache.fcenabledfilter will
have the file cache turned off; if wincache.fcenabled is set to 0,
then the sites listed in the wincache.fcenabledfilter will have
the file cache turned on.
wincache.fcachesize integer
Defines the maximum memory size (in megabytes) that is allocated
for the file cache. If the total size of all the cached files
exceeds the value specified in this setting, then most stale files
will be removed from the file cache.
wincache.fcndetect boolean
Enables or disables the file change notification detection
functionality. If file change notification is supported then it
will be used to refresh the opcode and file cache entries as soon
as the corresponding files are modified on a file system. If file
change notification is not supported, for example when using
network file shares, then wincache will poll for file changes at
regular time intervals specified by wincache.chkinterval.
wincache.maxfilesize integer
Defines the maximum allowed size (in kilobytes) for a single file
to be cached. If a file size exceeds the specified value, the file
will not be cached. This setting applies to the file cache only.
wincache.ocenabled boolean
Enables or disables the opcode cache functionality
wincache.ocenabledfilter string
Defines a comma-separated list of IIS web site identifiers where
opcode cache should be enabled or disabled. This setting works in
conjunction with wincache.ocenabled: if wincache.ocenabled is set
to 1, then the sites listed in the wincache.ocenabledfilter will
have the opcode cache turned off; if wincache.ocenabled is set to
0, then the sites listed in the wincache.ocenabledfilter will have
the opcode cache turned on.
wincache.ocachesize integer
Defines the maximum memory size (in megabytes) that is allocated
for the opcode cache. If the cached opcode size exceeds the
specified value, then most stale opcode will be removed from the
cache. Note that the opcode cache size must be at least 3 times
bigger than file cache size. If that is not the case the opcode
cache size will be automatically increased.
wincache.filecount integer
Defines how many files are expected to be cached by the extension,
so that appropriate memory size is allocated at the startup time.
If the number of files exceeds the specified value, the WinCache
will re-allocate more memory as needed.
wincache.chkinterval integer
Defines how often (in seconds) the extension checks for file
changes in order to refresh the cache. Setting it to 0 will
disable the refreshing of the cache. The file changes will not be
reflected in the cache unless the cache entry for that file is
removed by scavenger or IIS application pool is recycled or
wincache_refresh_if_changed function is called.
wincache.ttlmax integer
Defines the maximum time to live (in seconds) for a cached entry
without being used. Setting it to 0 will disable the cache
scavenger, so the cached entries will never be removed from the
cache during the lifetime of the IIS worker process.
wincache.enablecli boolean
Defines if caching is enabled when PHP is running in command line
(CLI) mode.
wincache.ignorelist string
Defines a list of files that should not be cached by the
extension. The files list is specified by using file names only,
separated by the pipe symbol - "|".
Example #1 wincache.ignorelist example
wincache.ignorelist = "index.php|misc.php|admin.php"
wincache.namesalt string
Defines a string that will be used when naming the extension
specific objects that are stored in shared memory. This is used to
avoid conflicts that may be caused if other applications within an
IIS worker process tries to access shared memory. The length of
the namesalt string cannot exceed 8 characters.
wincache.ucenabled boolean
Enables or disables the user cache functionality.
wincache.ucachesize integer
Defines the maximum memory size in megabytes that is allocated for
the user cache. If the total size of variables stored in the user
cache exceeds the specified value, then the most stale variables
will be removed from the cache.
wincache.scachesize integer
Defines the maximum memory size in megabytes that is allocated for
the session cache. If the total size of data stored in the session
cache exceeds the specified value, then the most stale data will
be removed from the cache.
wincache.rerouteini string
Specifies an absolute or a relateve path to the reroute.ini file
that contains the list of PHP functions whose implementation
should be replaced with the WinCache function equivalents. If a
relative path is specified then it is assumed to be relative to
the location of php-cgi.exe file.
----------------------------------------------------------------------
----------------------------------------------------------------------
WinCache Statistics Script
The installation package for WinCache includes a PHP script, wincache.php,
that can be used to obtain cache information and statistics.
If the WinCache extension was installed via the Microsoft Web Platform
Installer, then this script is located in %SystemDrive%\Program
Files\IIS\Windows Cache for PHP\. On a 64-bit version of the Windows
Server operating system, the script is located in %SystemDrive%\Program
Files (x86)\IIS\Windows Cache for PHP. If the extension was installed
manually, then the wincache.php will be located in the same folder from
which the content of the installation package was extracted.
To use wincache.php, copy it into a root folder of a Web site or into any
subfolder. To protect the script, open it in any text editor and replace
the values for USERNAME and PASSWORD constants. If any other IIS
authentication is enabled on the server, then follow the instructions in
the comments:
Example #1 Authentication configuration for wincache.php
Note: Always protect the wincache.php script by using either the
built-in authentication or the server's authentication mechanism.
Leaving this script unprotected may compromise the security of your web
application and web server.
----------------------------------------------------------------------
----------------------------------------------------------------------
WinCache Session Handler
The WinCache session handler (available since WinCache 1.1.0) can be used
to configure PHP to store the session data in shared memory session cache.
Using shared memory instead of the default file session storage helps
improve performance of PHP applications that store large amount of data in
session objects. Wincache session cache uses file-backed shared memory,
which ensures that the session data is not lost during recycling of IIS
application pools.
To configure PHP to use WinCache session handler set the php.ini setting
session.save_handler to wincache. By default the Windows temporary file
location is used for storing the session data. To change the location of
the session file use session.save_path directive.
Example #1 Enabling WinCache session handler
session.save_handler = wincache
session.save_path = C:\inetpub\temp\session\
----------------------------------------------------------------------
----------------------------------------------------------------------
WinCache Functions Reroutes
The WinCache functions reroutes (available since WinCache 1.2.0) can be
used to replace built-in PHP functions with their equivalents that are
optimized for a particular purpose. WinCache extension includes
Windows-optimized implementation of PHP file functions that may improve
performance of PHP applications in cases when PHP has to access files on
network shares. The optimized implementation is provided for the following
functions:
* file_exists
* file_get_contents
* readfile
* is_readable
* is_writable
* is_dir
* realpath
* filesize
To configure WinCache to use the functions reroutes use the file
reroute.ini that is included in WinCache installation package. Copy this
file into the same directory where php.ini file is located. After that add
the wincache.rerouteini setting in php.ini and specify an absolute or
relative path to the reroute.ini file.
Example #1 Enabling WinCache functions reroutes
wincache.rerouteini = C:\PHP\reroute.ini
Note: If WinCache functions reroutes are enabled it is recommended to
increase the WinCache file cache size. This can be done by using
wincache.fcachesize setting.
The reroute.ini file contains the mappings between the native PHP
functions and their equivalents in WinCache. Each line in the file defines
a mapping by using the following syntax:
:[]=
The example of the file is shown below. In this example the calls to PHP
function file_get_contents() will be replaced with calls to
wincache_file_get_contents() only if the number of parameters passed to
the function is less than or equals to 2. Specifying the number of
parameters is useful when replacement function does not handle all the
function's parameters.
Example #2 Reroute.ini file content
[FunctionRerouteList]
file_exists=wincache_file_exists
file_get_contents:2=wincache_file_get_contents
readfile:2=wincache_readfile
is_readable=wincache_is_readable
is_writable=wincache_is_writable
is_writeable=wincache_is_writable
is_file=wincache_is_file
is_dir=wincache_is_dir
realpath=wincache_realpath
filesize=wincache_filesize
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
This extension has no constants defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
WinCache Functions
----------------------------------------------------------------------
wincache_fcache_fileinfo
(PECL wincache >= 1.0.0)
wincache_fcache_fileinfo - Retrieves information about files cached in the
file cache
Description
array wincache_fcache_fileinfo ([ bool $summaryonly = false ] )
Retrieves information about file cache content and its usage.
Parameters
summaryonly
Controls whether the returned array will contain information about
individual cache entries along with the file cache summary.
Return Values
Array of meta data about file cache or FALSE on failure
The array returned by this function contains the following elements:
* total_cache_uptime - total time in seconds that the file cache has
been active
* total_file_count - total number of files that are currently in the
file cache
* total_hit_count - number of times the files have been served from the
file cache
* total_miss_count - number of times the files have not been found in
the file cache
* file_entries - an array that contains the information about all the
cached files:
* file_name - absolute file name of the cached file
* add_time - time in seconds since the file has been added to the
file cache
* use_time - time in seconds since the file has been accessed in
the file cache
* last_check - time in seconds since the file has been checked for
modifications
* hit_count - number of times the file has been served from the
cache
* file_size - size of the cached file in bytes
Examples
Example #1 A wincache_fcache_fileinfo() example
The above example will output:
Array
( [total_cache_uptime] => 3234
[total_file_count] => 5
[total_hit_count] => 0
[total_miss_count] => 1
[file_entries] => Array
(
[1] => Array
(
[file_name] => c:\inetpub\wwwroot\checkcache.php
[add_time] => 1
[use_time] => 0
[last_check] => 1
[hit_count] => 1
[file_size] => 2435
)
[2] => Array (...iterates for each cached file)
)
)
See Also
* wincache_fcache_meminfo() - Retrieves information about file cache
memory usage
* wincache_ocache_fileinfo() - Retrieves information about files cached
in the opcode cache
* wincache_ocache_meminfo() - Retrieves information about opcode cache
memory usage
* wincache_rplist_fileinfo() - Retrieves information about resolve file
path cache
* wincache_rplist_meminfo() - Retrieves information about memory usage
by the resolve file path cache
* wincache_refresh_if_changed() - Refreshes the cache entries for the
cached files
* wincache_ucache_meminfo() - Retrieves information about user cache
memory usage
* wincache_ucache_info() - Retrieves information about data stored in
the user cache
* wincache_scache_info() - Retrieves information about files cached in
the session cache
* wincache_scache_meminfo() - Retrieves information about session cache
memory usage
----------------------------------------------------------------------
----------------------------------------------------------------------
wincache_fcache_meminfo
(PECL wincache >= 1.0.0)
wincache_fcache_meminfo - Retrieves information about file cache memory
usage
Description
array wincache_fcache_meminfo ( void )
Retrieves information about memory usage by file cache.
Return Values
Array of meta data about file cache memory usage or FALSE on failure
The array returned by this function contains the following elements:
* memory_total - amount of memory in bytes allocated for the file cache
* memory_free - amount of free memory in bytes available for the file
cache
* num_used_blks - number of memory blocks used by the file cache
* num_free_blks - number of free memory blocks available for the file
cache
* memory_overhead - amount of memory in bytes used for the file cache
internal structures
Examples
Example #1 A wincache_fcache_meminfo() example
The above example will output:
Array
(
[memory_total] => 134217728
[memory_free] => 131339120
[num_used_blks] => 361
[num_free_blks] => 3
[memory_overhead] => 5856
)
See Also
* wincache_fcache_fileinfo() - Retrieves information about files cached
in the file cache
* wincache_ocache_fileinfo() - Retrieves information about files cached
in the opcode cache
* wincache_ocache_meminfo() - Retrieves information about opcode cache
memory usage
* wincache_rplist_fileinfo() - Retrieves information about resolve file
path cache
* wincache_rplist_meminfo() - Retrieves information about memory usage
by the resolve file path cache
* wincache_refresh_if_changed() - Refreshes the cache entries for the
cached files
* wincache_ucache_meminfo() - Retrieves information about user cache
memory usage
* wincache_ucache_info() - Retrieves information about data stored in
the user cache
* wincache_scache_info() - Retrieves information about files cached in
the session cache
* wincache_scache_meminfo() - Retrieves information about session cache
memory usage
----------------------------------------------------------------------
----------------------------------------------------------------------
wincache_lock
(PECL wincache >= 1.1.0)
wincache_lock - Acquires an exclusive lock on a given key
Description
bool wincache_lock ( string $key [, bool $isglobal = false ] )
Obtains an exclusive lock on a given key. The execution of the current
script will be blocked until the lock can be obtained. Once the lock is
obtained, the other scripts that try to request the lock by using the same
key will be blocked, until the current script releases the lock by using
wincache_unlock().
Warning
Using of the wincache_lock() and wincache_unlock() can cause deadlocks
when executing PHP scripts in a multi-process environment like FastCGI. Do
not use these functions unless you are absolutely sure you need to use
them. For the majority of the operations on the user cache it is not
necessary to use these functions.
Parameters
key
Name of the key in the cache to get the lock on.
isglobal
Controls whether the scope of the lock is system-wide or local.
Local locks are scoped to the application pool in IIS FastCGI case
or to all php processes that have the same parent process
identifier.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Using wincache_lock()
See Also
* wincache_unlock() - Releases an exclusive lock on a given key
* wincache_ucache_set() - Adds a variable in user cache and overwrites a
variable if it already exists in the cache
* wincache_ucache_get() - Gets a variable stored in the user cache
* wincache_ucache_delete() - Deletes variables from the user cache
* wincache_ucache_clear() - Deletes entire content of the user cache
* wincache_ucache_exists() - Checks if a variable exists in the user
cache
* wincache_ucache_meminfo() - Retrieves information about user cache
memory usage
* wincache_ucache_info() - Retrieves information about data stored in
the user cache
* wincache_scache_info() - Retrieves information about files cached in
the session cache
----------------------------------------------------------------------
----------------------------------------------------------------------
wincache_ocache_fileinfo
(PECL wincache >= 1.0.0)
wincache_ocache_fileinfo - Retrieves information about files cached in the
opcode cache
Description
array wincache_ocache_fileinfo ([ bool $summaryonly = false ] )
Retrieves information about opcode cache content and its usage.
Parameters
summaryonly
Controls whether the returned array will contain information about
individual cache entries along with the opcode cache summary.
Return Values
Array of meta data about opcode cache or FALSE on failure
The array returned by this function contains the following elements:
* total_cache_uptime - total time in seconds that the opcode cache has
been active
* total_file_count - total number of files that are currently in the
opcode cache
* total_hit_count - number of times the compiled opcode have been served
from the cache
* total_miss_count - number of times the compiled opcode have not been
found in the cache
* is_local_cache - true is the cache metadata is for a local cache
instance, false if the metadata is for the global cache
* file_entries - an array that contains the information about all the
cached files:
* file_name - absolute file name of the cached file
* add_time - time in seconds since the file has been added to the
opcode cache
* use_time - time in seconds since the file has been accessed in
the opcode cache
* last_check - time in seconds since the file has been checked for
modifications
* hit_count - number of times the file has been served from the
cache
* function_count - number of functions in the cached file
* class_count - number of classes in the cached file
Examples
Example #1 A wincache_ocache_fileinfo() example
The above example will output:
Array
(
[total_cache_uptime] => 17357
[total_file_count] => 121
[total_hit_count] => 36562
[total_miss_count] => 201
[file_entries] => Array
(
[1] => Array
(
[file_name] => c:\inetpub\wwwroot\checkcache.php
[add_time] => 17356
[use_time] => 7
[last_check] => 10
[hit_count] => 454
[function_count] => 0
[class_count] => 1
)
[2] => Array (...iterates for each cached file)
)
)
See Also
* wincache_fcache_fileinfo() - Retrieves information about files cached
in the file cache
* wincache_fcache_meminfo() - Retrieves information about file cache
memory usage
* wincache_ocache_meminfo() - Retrieves information about opcode cache
memory usage
* wincache_rplist_fileinfo() - Retrieves information about resolve file
path cache
* wincache_rplist_meminfo() - Retrieves information about memory usage
by the resolve file path cache
* wincache_refresh_if_changed() - Refreshes the cache entries for the
cached files
* wincache_ucache_meminfo() - Retrieves information about user cache
memory usage
* wincache_ucache_info() - Retrieves information about data stored in
the user cache
* wincache_scache_info() - Retrieves information about files cached in
the session cache
* wincache_scache_meminfo() - Retrieves information about session cache
memory usage
----------------------------------------------------------------------
----------------------------------------------------------------------
wincache_ocache_meminfo
(PECL wincache >= 1.0.0)
wincache_ocache_meminfo - Retrieves information about opcode cache memory
usage
Description
array wincache_ocache_meminfo ( void )
Retrieves information about memory usage by opcode cache.
Return Values
Array of meta data about opcode cache memory usage or FALSE on failure
The array returned by this function contains the following elements:
* memory_total - amount of memory in bytes allocated for the opcode
cache
* memory_free - amount of free memory in bytes available for the opcode
cache
* num_used_blks - number of memory blocks used by the opcode cache
* num_free_blks - number of free memory blocks available for the opcode
cache
* memory_overhead - amount of memory in bytes used for the opcode cache
internal structures
Examples
Example #1 A wincache_ocache_meminfo() example
The above example will output:
Array
(
[memory_total] => 134217728
[memory_free] => 112106972
[num_used_blks] => 15469
[num_free_blks] => 4
[memory_overhead] => 247600
)
See Also
* wincache_fcache_fileinfo() - Retrieves information about files cached
in the file cache
* wincache_fcache_meminfo() - Retrieves information about file cache
memory usage
* wincache_ocache_fileinfo() - Retrieves information about files cached
in the opcode cache
* wincache_rplist_fileinfo() - Retrieves information about resolve file
path cache
* wincache_rplist_meminfo() - Retrieves information about memory usage
by the resolve file path cache
* wincache_refresh_if_changed() - Refreshes the cache entries for the
cached files
* wincache_ucache_meminfo() - Retrieves information about user cache
memory usage
* wincache_ucache_info() - Retrieves information about data stored in
the user cache
* wincache_scache_info() - Retrieves information about files cached in
the session cache
* wincache_scache_meminfo() - Retrieves information about session cache
memory usage
----------------------------------------------------------------------
----------------------------------------------------------------------
wincache_refresh_if_changed
(PECL wincache >= 1.0.0)
wincache_refresh_if_changed - Refreshes the cache entries for the cached
files
Description
bool wincache_refresh_if_changed ([ array $files ] )
Refreshes the cache entries for the files, whose names were passed in the
input argument. If no argument is specified then refreshes all the entries
in the cache.
Parameters
files
An array of file names for files that need to be refreshed. An
absolute or relative file paths can be used.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
WinCache performs regular checks on the cached files to ensure that if any
file has changed then the corresponding entry in the cache is updated. By
default this check is performed every 30 seconds. If, for example, a PHP
script updates another PHP script where the application's configuration
settings are stored, then it may happen that after the configuration
settings have been saved to a file, the application is still using old
settings for some time until the cache is refreshed. In those cases it may
be preferrable to refresh the cache right after the file has been changed.
The following example shows how this can be done.
Example #1 A wincache_refresh_if_changed() example
');
fclose($handle);
wincache_refresh_if_changed(array($filename));
?>
See Also
* wincache_fcache_fileinfo() - Retrieves information about files cached
in the file cache
* wincache_fcache_meminfo() - Retrieves information about file cache
memory usage
* wincache_ocache_fileinfo() - Retrieves information about files cached
in the opcode cache
* wincache_ocache_meminfo() - Retrieves information about opcode cache
memory usage
* wincache_rplist_fileinfo() - Retrieves information about resolve file
path cache
* wincache_rplist_meminfo() - Retrieves information about memory usage
by the resolve file path cache
* wincache_ucache_meminfo() - Retrieves information about user cache
memory usage
* wincache_ucache_info() - Retrieves information about data stored in
the user cache
----------------------------------------------------------------------
----------------------------------------------------------------------
wincache_rplist_fileinfo
(PECL wincache >= 1.0.0)
wincache_rplist_fileinfo - Retrieves information about resolve file path
cache
Description
array wincache_rplist_fileinfo ([ bool $summaryonly = false ] )
Retrieves information about cached mappings between relative file paths
and corresponding absolute file paths.
Return Values
Array of meta data about the resolve file path cache or FALSE on failure
The array returned by this function contains the following elements:
* total_file_count - total number of file path mappings stored in the
cache
* rplist_entries - an array that contains the information about all the
cached file paths:
* resolve_path - path to a file
* subkey_data - corresponding absolute path to a file
Examples
Example #1 A wincache_rplist_fileinfo() example
The above example will output:
Array
(
[total_file_count] => 5
[rplist_entries] => Array
(
[1] => Array
(
[resolve_path] => checkcache.php
[subkey_data] => c:\inetpub\wwwroot|c:\inetpub\wwwroot\checkcache.php
)
[2] => Array (...iterates for each cached file)
)
)
See Also
* wincache_fcache_meminfo() - Retrieves information about file cache
memory usage
* wincache_fcache_fileinfo() - Retrieves information about files cached
in the file cache
* wincache_ocache_fileinfo() - Retrieves information about files cached
in the opcode cache
* wincache_ocache_meminfo() - Retrieves information about opcode cache
memory usage
* wincache_rplist_meminfo() - Retrieves information about memory usage
by the resolve file path cache
* wincache_refresh_if_changed() - Refreshes the cache entries for the
cached files
* wincache_ucache_meminfo() - Retrieves information about user cache
memory usage
* wincache_ucache_info() - Retrieves information about data stored in
the user cache
* wincache_scache_info() - Retrieves information about files cached in
the session cache
* wincache_scache_meminfo() - Retrieves information about session cache
memory usage
----------------------------------------------------------------------
----------------------------------------------------------------------
wincache_rplist_meminfo
(PECL wincache >= 1.0.0)
wincache_rplist_meminfo - Retrieves information about memory usage by the
resolve file path cache
Description
array wincache_rplist_meminfo ( void )
Retrieves information about memory usage by resolve file path cache.
Return Values
Array of meta data that describes memory usage by resolve file path cache.
or FALSE on failure
The array returned by this function contains the following elements:
* memory_total - amount of memory in bytes allocated for the resolve
file path cache
* memory_free - amount of free memory in bytes available for the resolve
file path cache
* num_used_blks - number of memory blocks used by the resolve file path
cache
* num_free_blks - number of free memory blocks available for the resolve
file path cache
* memory_overhead - amount of memory in bytes used for the internal
structures of resolve file path cache
Examples
Example #1 A wincache_rplist_meminfo() example
The above example will output:
Array
(
[memory_total] => 9437184
[memory_free] => 9416744
[num_used_blks] => 23
[num_free_blks] => 1
[memory_overhead] => 416
)
See Also
* wincache_fcache_fileinfo() - Retrieves information about files cached
in the file cache
* wincache_fcache_meminfo() - Retrieves information about file cache
memory usage
* wincache_ocache_fileinfo() - Retrieves information about files cached
in the opcode cache
* wincache_ocache_meminfo() - Retrieves information about opcode cache
memory usage
* wincache_rplist_fileinfo() - Retrieves information about resolve file
path cache
* wincache_refresh_if_changed() - Refreshes the cache entries for the
cached files
* wincache_ucache_meminfo() - Retrieves information about user cache
memory usage
* wincache_ucache_info() - Retrieves information about data stored in
the user cache
* wincache_scache_info() - Retrieves information about files cached in
the session cache
* wincache_scache_meminfo() - Retrieves information about session cache
memory usage
----------------------------------------------------------------------
----------------------------------------------------------------------
wincache_scache_info
(PECL wincache >= 1.1.0)
wincache_scache_info - Retrieves information about files cached in the
session cache
Description
array wincache_scache_info ([ bool $summaryonly = false ] )
Retrieves information about session cache content and its usage.
Parameters
summaryonly
Controls whether the returned array will contain information about
individual cache entries along with the session cache summary.
Return Values
Array of meta data about session cache or FALSE on failure
The array returned by this function contains the following elements:
* total_cache_uptime - total time in seconds that the session cache has
been active
* total_item_count - total number of elements that are currently in the
session cache
* is_local_cache - true is the cache metadata is for a local cache
instance, false if the metadata is for the global cache
* total_hit_count - number of times the data has been served from the
cache
* total_miss_count - number of times the data has not been found in the
cache
* scache_entries - an array that contains the information about all the
cached items:
* key_name - name of the key which is used to store the data
* value_type - type of value stored by the key
* use_time - time in seconds since the file has been accessed in
the opcode cache
* last_check - time in seconds since the file has been checked for
modifications
* ttl_seconds - time remaining for the data to live in the cache, 0
meaning infinite
* age_seconds - time elapsed from the time data has been added in
the cache
* hitcount - number of times data has been served from the cache
Examples
Example #1 A wincache_scache_info() example
The above example will output:
Array
(
[total_cache_uptime] => 17357
[total_file_count] => 121
[total_hit_count] => 36562
[total_miss_count] => 201
[scache_entries] => Array
(
[1] => Array
(
[file_name] => c:\inetpub\wwwroot\checkcache.php
[add_time] => 17356
[use_time] => 7
[last_check] => 10
[hit_count] => 454
[function_count] => 0
[class_count] => 1
)
[2] => Array (...iterates for each cached file)
)
)
See Also
* wincache_fcache_fileinfo() - Retrieves information about files cached
in the file cache
* wincache_fcache_meminfo() - Retrieves information about file cache
memory usage
* wincache_ocache_meminfo() - Retrieves information about opcode cache
memory usage
* wincache_rplist_fileinfo() - Retrieves information about resolve file
path cache
* wincache_rplist_meminfo() - Retrieves information about memory usage
by the resolve file path cache
* wincache_refresh_if_changed() - Refreshes the cache entries for the
cached files
* wincache_ucache_meminfo() - Retrieves information about user cache
memory usage
* wincache_ucache_info() - Retrieves information about data stored in
the user cache
* wincache_scache_meminfo() - Retrieves information about session cache
memory usage
----------------------------------------------------------------------
----------------------------------------------------------------------
wincache_scache_meminfo
(PECL wincache >= 1.1.0)
wincache_scache_meminfo - Retrieves information about session cache memory
usage
Description
array wincache_scache_meminfo ( void )
Retrieves information about memory usage by session cache.
Return Values
Array of meta data about session cache memory usage or FALSE on failure
The array returned by this function contains the following elements:
* memory_total - amount of memory in bytes allocated for the session
cache
* memory_free - amount of free memory in bytes available for the session
cache
* num_used_blks - number of memory blocks used by the session cache
* num_free_blks - number of free memory blocks available for the session
cache
* memory_overhead - amount of memory in bytes used for the session cache
internal structures
Examples
Example #1 A wincache_scache_meminfo() example
The above example will output:
Array
(
[memory_total] => 5242880
[memory_free] => 5215056
[num_used_blks] => 6
[num_free_blks] => 3
[memory_overhead] => 176
)
See Also
* wincache_fcache_fileinfo() - Retrieves information about files cached
in the file cache
* wincache_fcache_meminfo() - Retrieves information about file cache
memory usage
* wincache_ocache_fileinfo() - Retrieves information about files cached
in the opcode cache
* wincache_rplist_fileinfo() - Retrieves information about resolve file
path cache
* wincache_rplist_meminfo() - Retrieves information about memory usage
by the resolve file path cache
* wincache_refresh_if_changed() - Refreshes the cache entries for the
cached files
* wincache_ucache_info() - Retrieves information about data stored in
the user cache
* wincache_scache_info() - Retrieves information about files cached in
the session cache
----------------------------------------------------------------------
----------------------------------------------------------------------
wincache_ucache_add
(PECL wincache >= 1.1.0)
wincache_ucache_add - Adds a variable in user cache only if variable does
not already exist in the cache
Description
bool wincache_ucache_add ( string $key , mixed $value [, int $ttl = 0 ] )
bool wincache_ucache_add ( array $values [, mixed $unused [, int $ttl = 0
]] )
Adds a variable in user cache, only if this variable doesn't already exist
in the cache. The added variable remains in the user cache unless its time
to live expires or it is deleted by using wincache_ucache_delete() or
wincache_ucache_clear() functions.
Parameters
key
Store the variable using this key name. If a variable with same
key is already present the function will fail and return FALSE.
key is case sensitive. To override the value even if key is
present use wincache_ucache_set() function instad. key can also
take array of name => value pairs where names will be used as
keys. This can be used to add multiple values in the cache in one
operation, thus avoiding race condition.
value
Value of a variable to store. Value supports all data types except
resources, such as file handles. This paramter is ignored if first
argument is an array. A general guidance is to pass NULL as value
while using array as key. If value is an object, or an array
containing objects, then the objects will be serialized. See
__sleep() for details on serializing objects.
values
Associative array of keys and values.
ttl
Time for the variable to live in the cache in seconds. After the
value specified in ttl has passed the stored variable will be
deleted from the cache. This parameter takes a default value of 0
which means the variable will stay in the cache unless explicitly
deleted by using wincache_ucache_delete() or
wincache_ucache_clear() functions.
Return Values
If key is string, the function returns TRUE on success and FALSE on
failure.
If key is an array, the function returns:
* If all the name => value pairs in the array can be set, function
returns an empty array;
* If all the name => value pairs in the array cannot be set, function
returns FALSE;
* If some can be set while others cannot, function returns an array with
name=>value pair for which the addition failed in the user cache.
Examples
Example #1 wincache_ucache_add() with key as a string
The above example will output:
bool(true)
bool(false)
string(3) "BAR"
Example #2 wincache_ucache_add() with key as an array
'5', 'Blue' => '6', 'yellow' => '7', 'cyan' => '8');
var_dump(wincache_ucache_add($colors_array));
var_dump(wincache_ucache_add($colors_array));
var_dump(wincache_ucache_get('Blue'));
?>
The above example will output:
array(0) { }
array(4) {
["green"]=> int(-1)
["Blue"]=> int(-1)
["yellow"]=> int(-1)
["cyan"]=> int(-1)
}
string(1) "6"
See Also
* wincache_ucache_set() - Adds a variable in user cache and overwrites a
variable if it already exists in the cache
* wincache_ucache_get() - Gets a variable stored in the user cache
* wincache_ucache_delete() - Deletes variables from the user cache
* wincache_ucache_clear() - Deletes entire content of the user cache
* wincache_ucache_exists() - Checks if a variable exists in the user
cache
* wincache_ucache_meminfo() - Retrieves information about user cache
memory usage
* wincache_ucache_info() - Retrieves information about data stored in
the user cache
* __sleep()
----------------------------------------------------------------------
----------------------------------------------------------------------
wincache_ucache_cas
(PECL wincache >= 1.1.0)
wincache_ucache_cas - Compares the variable with old value and assigns new
value to it
Description
bool wincache_ucache_cas ( string $key , int $old_value , int $new_value )
Compares the variable associated with the key with old_value and if it
matches then assigns the new_value to it.
Parameters
key
The key that is used to store the variable in the cache. key is
case sensitive.
old_value
Old value of the variable pointed by key in the user cache. The
value should be of type long, otherwise the function returns
FALSE.
new_value
New value which will get assigned to variable pointer by key if a
match is found. The value should be of type long, otherwise the
function returns FALSE.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Using wincache_ucache_cas()
The above example will output:
bool(true)
int(1)
See Also
* wincache_ucache_inc() - Increments the value associated with the key
* wincache_ucache_dec() - Decrements the value associated with the key
----------------------------------------------------------------------
----------------------------------------------------------------------
wincache_ucache_clear
(PECL wincache >= 1.1.0)
wincache_ucache_clear - Deletes entire content of the user cache
Description
bool wincache_ucache_clear ( void )
Clears/deletes all the values stored in the user cache.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 using wincache_ucache_clear()
The above example will output:
array(5) { ["green"]=> int(1)
["red"]=> int(2)
["orange"]=> int(4)
["blue"]=> int(8)
["cyan"]=> int(16) }
bool(true)
bool(false)
See Also
* wincache_ucache_set() - Adds a variable in user cache and overwrites a
variable if it already exists in the cache
* wincache_ucache_add() - Adds a variable in user cache only if variable
does not already exist in the cache
* wincache_ucache_delete() - Deletes variables from the user cache
* wincache_ucache_get() - Gets a variable stored in the user cache
* wincache_ucache_exists() - Checks if a variable exists in the user
cache
* wincache_ucache_meminfo() - Retrieves information about user cache
memory usage
* wincache_ucache_info() - Retrieves information about data stored in
the user cache
----------------------------------------------------------------------
----------------------------------------------------------------------
wincache_ucache_dec
(PECL wincache >= 1.1.0)
wincache_ucache_dec - Decrements the value associated with the key
Description
mixed wincache_ucache_dec ( string $key [, int $dec_by = 1 [, bool
&$success ]] )
Decrements the value associated with the key by 1 or as specified by
dec_by.
Parameters
key
The key that was used to store the variable in the cache. key is
case sensitive.
dec_by
The value by which the variable associated with the key will get
decremented. If the argument is a floating point number it will be
truncated to nearest integer. The variable associated with the key
should be of type long, otherwise the function fails and returns
FALSE.
success
Will be set to TRUE on success and FALSE on failure.
Return Values
Returns the decremented value on success and FALSE on failure.
Examples
Example #1 Using wincache_ucache_dec()
The above example will output:
int(2922)
bool(true)
See Also
* wincache_ucache_inc() - Increments the value associated with the key
* wincache_ucache_cas() - Compares the variable with old value and
assigns new value to it
----------------------------------------------------------------------
----------------------------------------------------------------------
wincache_ucache_delete
(PECL wincache >= 1.1.0)
wincache_ucache_delete - Deletes variables from the user cache
Description
bool wincache_ucache_delete ( mixed $key )
Deletes the elements in the user cache pointed by key.
Parameters
key
The key that was used to store the variable in the cache. key is
case sensitive. key can be an array of keys.
Return Values
Returns TRUE on success or FALSE on failure.
If key is an array then the function returns FALSE if every element of the
array fails to get deleted from the user cache, otherwise returns an array
which consists of all the keys that are deleted.
Examples
Example #1 Using wincache_ucache_delete() with key as a string
The above example will output:
bool(true)
bool(false)
Example #2 Usingwincache_ucache_delete() with key as an array
'5', 'blue' => '6', 'yellow' => '7', 'cyan' => '8');
wincache_ucache_set($array1);
$array2 = array('green', 'blue', 'yellow', 'cyan');
var_dump(wincache_ucache_delete($array2));
?>
The above example will output:
array(4) { [0]=> string(5) "green"
[1]=> string(4) "Blue"
[2]=> string(6) "yellow"
[3]=> string(4) "cyan" }
Example #3 Using wincache_ucache_delete() with key as an array where some
elements cannot be deleted
'5', 'blue' => '6', 'yellow' => '7', 'cyan' => '8');
wincache_ucache_set($array1);
$array2 = array('orange', 'red', 'yellow', 'cyan');
var_dump(wincache_ucache_delete($array2));
?>
The above example will output:
array(2) { [0]=> string(6) "yellow"
[1]=> string(4) "cyan" }
See Also
* wincache_ucache_set() - Adds a variable in user cache and overwrites a
variable if it already exists in the cache
* wincache_ucache_add() - Adds a variable in user cache only if variable
does not already exist in the cache
* wincache_ucache_get() - Gets a variable stored in the user cache
* wincache_ucache_clear() - Deletes entire content of the user cache
* wincache_ucache_exists() - Checks if a variable exists in the user
cache
* wincache_ucache_meminfo() - Retrieves information about user cache
memory usage
* wincache_ucache_info() - Retrieves information about data stored in
the user cache
----------------------------------------------------------------------
----------------------------------------------------------------------
wincache_ucache_exists
(PECL wincache >= 1.1.0)
wincache_ucache_exists - Checks if a variable exists in the user cache
Description
bool wincache_ucache_exists ( string $key )
Checks if a variable with the key exists in the user cache or not.
Parameters
key
The key that was used to store the variable in the cache. key is
case sensitive.
Return Values
Returns TRUE if variable with the key exitsts, otherwise returns FALSE.
Examples
Example #1 Using wincache_ucache_exists()
The above example will output:
bool(true)
See Also
* wincache_ucache_set() - Adds a variable in user cache and overwrites a
variable if it already exists in the cache
* wincache_ucache_add() - Adds a variable in user cache only if variable
does not already exist in the cache
* wincache_ucache_get() - Gets a variable stored in the user cache
* wincache_ucache_clear() - Deletes entire content of the user cache
* wincache_ucache_delete() - Deletes variables from the user cache
* wincache_ucache_meminfo() - Retrieves information about user cache
memory usage
* wincache_ucache_info() - Retrieves information about data stored in
the user cache
----------------------------------------------------------------------
----------------------------------------------------------------------
wincache_ucache_get
(PECL wincache >= 1.1.0)
wincache_ucache_get - Gets a variable stored in the user cache
Description
mixed wincache_ucache_get ( mixed $key [, bool &$success ] )
Gets a variable stored in the user cache.
Parameters
key
The key that was used to store the variable in the cache. key is
case sensitive. key can be an array of keys. In this case the
return value will be an array of values of each element in the key
array. If an object, or an array containing objects, is returned,
then the objects will be unserialized. See __wakeup() for details
on unserializing objects.
success
Will be set to TRUE on success and FALSE on failure.
Return Values
If key is a string, the function returns the value of the variable stored
with that key. The success is set to TRUE on success and to FALSE on
failure.
The key is an array, the parameter success is always set to TRUE. The
returned array (name => value pairs) will contain only those name => value
pairs for which the get operation in user cache was successful. If none of
the keys in the key array finds a match in the user cache an empty array
will be returned.
Examples
Example #1 wincache_ucache_get() with key as a string
The above example will output:
string(4) "blue"
bool(true)
Example #2 wincache_ucache_get() with key as an array
'5', 'Blue' => '6', 'yellow' => '7', 'cyan' => '8');
wincache_ucache_set($array1);
$array2 = array('green', 'Blue', 'yellow', 'cyan');
var_dump(wincache_ucache_get($array2, $success));
var_dump($success);
?>
The above example will output:
array(4) { ["green"]=> string(1) "5"
["Blue"]=> string(1) "6"
["yellow"]=> string(1) "7"
["cyan"]=> string(1) "8" }
bool(true)
See Also
* wincache_ucache_add() - Adds a variable in user cache only if variable
does not already exist in the cache
* wincache_ucache_set() - Adds a variable in user cache and overwrites a
variable if it already exists in the cache
* wincache_ucache_delete() - Deletes variables from the user cache
* wincache_ucache_clear() - Deletes entire content of the user cache
* wincache_ucache_exists() - Checks if a variable exists in the user
cache
* wincache_ucache_meminfo() - Retrieves information about user cache
memory usage
* wincache_ucache_info() - Retrieves information about data stored in
the user cache
* __wakeup()
----------------------------------------------------------------------
----------------------------------------------------------------------
wincache_ucache_inc
(PECL wincache >= 1.1.0)
wincache_ucache_inc - Increments the value associated with the key
Description
mixed wincache_ucache_inc ( string $key [, int $inc_by = 1 [, bool
&$success ]] )
Increments the value associated with the key by 1 or as specified by
inc_by.
Parameters
key
The key that was used to store the variable in the cache. key is
case sensitive.
inc_by
The value by which the variable associated with the key will get
incremented. If the argument is a floating point number it will be
truncated to nearest integer. The variable associated with the key
should be of type long, otherwise the function fails and returns
FALSE.
success
Will be set to TRUE on success and FALSE on failure.
Return Values
Returns the incremented value on success and FALSE on failure.
Examples
Example #1 Using wincache_ucache_inc()
The above example will output:
int(2922)
bool(true)
See Also
* wincache_ucache_dec() - Decrements the value associated with the key
* wincache_ucache_cas() - Compares the variable with old value and
assigns new value to it
----------------------------------------------------------------------
----------------------------------------------------------------------
wincache_ucache_info
(PECL wincache >= 1.1.0)
wincache_ucache_info - Retrieves information about data stored in the user
cache
Description
array wincache_ucache_info ([ bool $summaryonly = false [, string $key ]]
)
Retrieves information about data stored in the user cache.
Parameters
summaryonly
Controls whether the returned array will contain information about
individual cache entries along with the user cache summary.
key
The key of an entry in the user cache. If specified then the
returned array will contain information only about that cache
entry. If not specified and summaryonly is set to false then the
returned array will contain information about all entries in the
cache.
Return Values
Array of meta data about user cache or FALSE on failure
The array returned by this function contains the following elements:
* total_cache_uptime - total time in seconds that the user cache has
been active
* total_item_count - total number of elements that are currently in the
user cache
* is_local_cache - true is the cache metadata is for a local cache
instance, false if the metadata is for the global cache
* total_hit_count - number of times the data has been served from the
cache
* total_miss_count - number of times the data has not been found in the
cache
* ucache_entries - an array that contains the information about all the
cached items:
* key_name - name of the key which is used to store the data
* value_type - type of value stored by the key
* use_time - time in seconds since the file has been accessed in
the opcode cache
* last_check - time in seconds since the file has been checked for
modifications
* is_session - indicates if the data is a session variable
* ttl_seconds - time remaining for the data to live in the cache, 0
meaning infinite
* age_seconds - time elapsed from the time data has been added in
the cache
* hitcount - number of times data has been served from the cache
Examples
Example #1 Using wincache_ucache_info()
The above example will output:
Array
( ["total_cache_uptime"] => int(0)
["is_local_cache"] => bool(false)
["total_item_count"] => int(1)
["total_hit_count"] => int(3)
["total_miss_count"] => int(1)
["ucache_entries"] => Array(1)
( [1] => Array(6)
(
["key_name"] => string(5) "green"
["value_type"] => string(4) "long"
["is_session"] => int(0)
["ttl_seconds"] => int(0)
["age_seconds"] => int(0)
["hitcount"] => int(3)
)
)
)
See Also
* wincache_fcache_meminfo() - Retrieves information about file cache
memory usage
* wincache_ocache_fileinfo() - Retrieves information about files cached
in the opcode cache
* wincache_ocache_meminfo() - Retrieves information about opcode cache
memory usage
* wincache_rplist_meminfo() - Retrieves information about memory usage
by the resolve file path cache
* wincache_rplist_fileinfo() - Retrieves information about resolve file
path cache
* wincache_refresh_if_changed() - Refreshes the cache entries for the
cached files
* wincache_ucache_meminfo() - Retrieves information about user cache
memory usage
* wincache_scache_info() - Retrieves information about files cached in
the session cache
* wincache_scache_meminfo() - Retrieves information about session cache
memory usage
----------------------------------------------------------------------
----------------------------------------------------------------------
wincache_ucache_meminfo
(PECL wincache >= 1.1.0)
wincache_ucache_meminfo - Retrieves information about user cache memory
usage
Description
array wincache_ucache_meminfo ( void )
Retrieves information about memory usage by user cache.
Return Values
Array of meta data about user cache memory usage or FALSE on failure
The array returned by this function contains the following elements:
* memory_total - amount of memory in bytes allocated for the user cache
* memory_free - amount of free memory in bytes available for the user
cache
* num_used_blks - number of memory blocks used by the user cache
* num_free_blks - number of free memory blocks available for the user
cache
* memory_overhead - amount of memory in bytes used for the user cache
internal structures
Examples
Example #1 A wincache_ucache_meminfo() example
The above example will output:
Array
(
[memory_total] => 5242880
[memory_free] => 5215056
[num_used_blks] => 6
[num_free_blks] => 3
[memory_overhead] => 176
)
See Also
* wincache_fcache_fileinfo() - Retrieves information about files cached
in the file cache
* wincache_fcache_meminfo() - Retrieves information about file cache
memory usage
* wincache_ocache_fileinfo() - Retrieves information about files cached
in the opcode cache
* wincache_rplist_fileinfo() - Retrieves information about resolve file
path cache
* wincache_rplist_meminfo() - Retrieves information about memory usage
by the resolve file path cache
* wincache_refresh_if_changed() - Refreshes the cache entries for the
cached files
* wincache_ucache_info() - Retrieves information about data stored in
the user cache
* wincache_scache_info() - Retrieves information about files cached in
the session cache
* wincache_scache_meminfo() - Retrieves information about session cache
memory usage
----------------------------------------------------------------------
----------------------------------------------------------------------
wincache_ucache_set
(PECL wincache >= 1.1.0)
wincache_ucache_set - Adds a variable in user cache and overwrites a
variable if it already exists in the cache
Description
bool wincache_ucache_set ( mixed $key , mixed $value [, int $ttl = 0 ] )
bool wincache_ucache_set ( array $values [, mixed $unused [, int $ttl = 0
]] )
Adds a variable in user cache. Overwrites a variable if it already exists
in the cache. The added or updated variable remains in the user cache
unless its time to live expires or it is deleted by using
wincache_ucache_delete() or wincache_ucache_clear() functions.
Parameters
key
Store the variable using this key name. If a variable with same
key is already present the function will overwrite the previous
value with the new one. key is case sensitive. key can also take
array of name => value pairs where names will be used as keys.
This can be used to add multiple values in the cache in one
operation, thus avoiding race condition.
value
Value of a variable to store. Value supports all data types except
resources, such as file handles. This paramter is ignored if first
argument is an array. A general guidance is to pass NULL as value
while using array as key. If value is an object, or an array
containing objects, then the objects will be serialized. See
__sleep() for details on serializing objects.
values
Associative array of keys and values.
ttl
Time for the variable to live in the cache in seconds. After the
value specified in ttl has passed the stored variable will be
deleted from the cache. This parameter takes a default value of 0
which means the variable will stay in the cache unless explicitly
deleted by using wincache_ucache_delete() or
wincache_ucache_clear() functions.
Return Values
If key is string, the function returns TRUE on success and FALSE on
failure.
If key is an array, the function returns:
* If all the name => value pairs in the array can be set, function
returns an empty array;
* If all the name => value pairs in the array cannot be set, function
returns FALSE;
* If some can be set while others cannot, function returns an array with
name=>value pair for which the addition failed in the user cache.
Examples
Example #1 wincache_ucache_set() with key as a string
The above example will output:
bool(true)
string(3) "BAR"
bool(true)
string(3) "BAR1"
Example #2 wincache_ucache_set() with key as an array
'5', 'Blue' => '6', 'yellow' => '7', 'cyan' => '8');
var_dump(wincache_ucache_set($colors_array));
var_dump(wincache_ucache_set($colors_array));
var_dump(wincache_ucache_get('Blue'));
?>
The above example will output:
array(0) {}
array(0) {}
string(1) "6"
See Also
* wincache_ucache_add() - Adds a variable in user cache only if variable
does not already exist in the cache
* wincache_ucache_get() - Gets a variable stored in the user cache
* wincache_ucache_delete() - Deletes variables from the user cache
* wincache_ucache_clear() - Deletes entire content of the user cache
* wincache_ucache_exists() - Checks if a variable exists in the user
cache
* wincache_ucache_meminfo() - Retrieves information about user cache
memory usage
* wincache_ucache_info() - Retrieves information about data stored in
the user cache
* __sleep()
----------------------------------------------------------------------
----------------------------------------------------------------------
wincache_unlock
(PECL wincache >= 1.1.0)
wincache_unlock - Releases an exclusive lock on a given key
Description
bool wincache_unlock ( string $key )
Releases an exclusive lock that was obtained on a given key by using
wincache_lock(). If any other process was blocked waiting for the lock on
this key, that process will be able to obtain the lock.
Warning
Using of the wincache_lock() and wincache_unlock() can cause deadlocks
when executing PHP scripts in a multi-process environment like FastCGI. Do
not use these functions unless you are absolutely sure you need to use
them. For the majority of the operations on the user cache it is not
necessary to use these functions.
Parameters
key
Name of the key in the cache to release the lock on.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Using wincache_unlock()
See Also
* wincache_lock() - Acquires an exclusive lock on a given key
* wincache_ucache_set() - Adds a variable in user cache and overwrites a
variable if it already exists in the cache
* wincache_ucache_get() - Gets a variable stored in the user cache
* wincache_ucache_delete() - Deletes variables from the user cache
* wincache_ucache_clear() - Deletes entire content of the user cache
* wincache_ucache_exists() - Checks if a variable exists in the user
cache
* wincache_ucache_meminfo() - Retrieves information about user cache
memory usage
* wincache_ucache_info() - Retrieves information about data stored in
the user cache
* wincache_scache_info() - Retrieves information about files cached in
the session cache
----------------------------------------------------------------------
Table of Contents
* wincache_fcache_fileinfo - Retrieves information about files cached in
the file cache
* wincache_fcache_meminfo - Retrieves information about file cache
memory usage
* wincache_lock - Acquires an exclusive lock on a given key
* wincache_ocache_fileinfo - Retrieves information about files cached in
the opcode cache
* wincache_ocache_meminfo - Retrieves information about opcode cache
memory usage
* wincache_refresh_if_changed - Refreshes the cache entries for the
cached files
* wincache_rplist_fileinfo - Retrieves information about resolve file
path cache
* wincache_rplist_meminfo - Retrieves information about memory usage by
the resolve file path cache
* wincache_scache_info - Retrieves information about files cached in the
session cache
* wincache_scache_meminfo - Retrieves information about session cache
memory usage
* wincache_ucache_add - Adds a variable in user cache only if variable
does not already exist in the cache
* wincache_ucache_cas - Compares the variable with old value and assigns
new value to it
* wincache_ucache_clear - Deletes entire content of the user cache
* wincache_ucache_dec - Decrements the value associated with the key
* wincache_ucache_delete - Deletes variables from the user cache
* wincache_ucache_exists - Checks if a variable exists in the user cache
* wincache_ucache_get - Gets a variable stored in the user cache
* wincache_ucache_inc - Increments the value associated with the key
* wincache_ucache_info - Retrieves information about data stored in the
user cache
* wincache_ucache_meminfo - Retrieves information about user cache
memory usage
* wincache_ucache_set - Adds a variable in user cache and overwrites a
variable if it already exists in the cache
* wincache_unlock - Releases an exclusive lock on a given key
----------------------------------------------------------------------
----------------------------------------------------------------------
Building for Windows
Table of Contents
* Prerequisites
* Compiling and building
* Verifying the build
----------------------------------------------------------------------
Prerequisites
Building WinCache extension will require:
1. PHP source code
2. PHP build environment
3. WinCache source code
For completing first two steps, follow the step-by-step guide for how to
>> build PHP on Windows.
For getting the WinCache source code follow the instructions described in
Downloading PECL extensions.
----------------------------------------------------------------------
----------------------------------------------------------------------
Compiling and building
The following steps describe how to compile and build WinCache on Windows
OS:
1. Open a command prompt which is used to build PHP
2. Go to the root folder where PHP sources are present
3. Run the command:
cscript.exe win32\build\buildconf.js
4. Run the command:
configure.bat --help
The output will contain a new flag --enable-wincache.
5. Run the command:
configure.js [all options used to build PHP] --enable-wincache
--enable-wincache is the only extra option which is required to ensure
that WinCache extension gets built properly. This option will build
WinCache and will statically link it with PHP dll. To build WinCache
extension as a stand-alone DLL use the option
--enable-wincache=shared.
6. Run the command:
nmake
----------------------------------------------------------------------
----------------------------------------------------------------------
Verifying the build
The following steps describe how to verify that WinCache has been built
correctly:
1. Go to the folder where the PHP binaries are built
2. Run the command:
php.exe -n -d extension=php_wincache.dll -re wincache
If WinCache has been built properly, the output of this command will
list the INI directives and functions supported by WinCache.
----------------------------------------------------------------------
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* WinCache Statistics Script
* WinCache Session Handler
* WinCache Functions Reroutes
* Resource Types
* Predefined Constants
* WinCache Functions
* wincache_fcache_fileinfo - Retrieves information about files
cached in the file cache
* wincache_fcache_meminfo - Retrieves information about file cache
memory usage
* wincache_lock - Acquires an exclusive lock on a given key
* wincache_ocache_fileinfo - Retrieves information about files
cached in the opcode cache
* wincache_ocache_meminfo - Retrieves information about opcode
cache memory usage
* wincache_refresh_if_changed - Refreshes the cache entries for the
cached files
* wincache_rplist_fileinfo - Retrieves information about resolve
file path cache
* wincache_rplist_meminfo - Retrieves information about memory
usage by the resolve file path cache
* wincache_scache_info - Retrieves information about files cached
in the session cache
* wincache_scache_meminfo - Retrieves information about session
cache memory usage
* wincache_ucache_add - Adds a variable in user cache only if
variable does not already exist in the cache
* wincache_ucache_cas - Compares the variable with old value and
assigns new value to it
* wincache_ucache_clear - Deletes entire content of the user cache
* wincache_ucache_dec - Decrements the value associated with the
key
* wincache_ucache_delete - Deletes variables from the user cache
* wincache_ucache_exists - Checks if a variable exists in the user
cache
* wincache_ucache_get - Gets a variable stored in the user cache
* wincache_ucache_inc - Increments the value associated with the
key
* wincache_ucache_info - Retrieves information about data stored in
the user cache
* wincache_ucache_meminfo - Retrieves information about user cache
memory usage
* wincache_ucache_set - Adds a variable in user cache and
overwrites a variable if it already exists in the cache
* wincache_unlock - Releases an exclusive lock on a given key
* Building for Windows
* Prerequisites
* Compiling and building
* Verifying the build
----------------------------------------------------------------------
----------------------------------------------------------------------
Hierarchical Profiler
----------------------------------------------------------------------
Introduction
XHProf is a light-weight hierarchical and instrumentation based profiler.
During the data collection phase, it keeps track of call counts and
inclusive metrics for arcs in the dynamic callgraph of a program. It
computes exclusive metrics in the reporting/post processing phase, such as
wall (elapsed) time, CPU time and memory usage. A functions profile can be
broken down by callers or callees. XHProf handles recursive functions by
detecting cycles in the callgraph at data collection time itself and
avoiding the cycles by giving unique depth qualified names for the
recursive invocations.
XHProf includes a simple HTML based user interface (written in PHP). The
browser based UI for viewing profiler results makes it easy to view
results or to share results with peers. A callgraph image view is also
supported.
XHProf reports can often be helpful in understanding the structure of the
code being executed. The hierarchical nature of the reports can be used to
determine, for example, what chain of calls led to a particular function
getting called.
XHProf supports ability to compare two runs (a.k.a. "diff" reports) or
aggregate data from multiple runs. Diff and aggregate reports, much like
single run reports, offer "flat" as well as "hierarchical" views of the
profile.
Additional documentation can be found via the >> facebook xhprof website.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
Although not required, xhprof includes an interface that's written in PHP.
It's used to save and display the profiled data in a usable way, where
viewing is done via a web browser. So, a PHP enabled web server will
likely make the xhprof experience more useful.
There's also a fork of the GUI interface at
>> http://github.com/preinheimer/xhprof
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here: >> http://pecl.php.net/package/xhprof
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Xhprof Configure Options
Name Default Changeable Changelog
xhprof.output_dir "" PHP_INI_ALL
Here's a short explanation of the configuration directives.
xhprof.output_dir string
Directory used by the default implementation of the iXHProfRuns
interface (namely, the XHProfRuns_Default class) for storing
XHProf runs.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
XHPROF_FLAGS_NO_BUILTINS (integer)
Used to skip all built-in (internal) functions.
XHPROF_FLAGS_CPU (integer)
Used to add CPU profiling information to the output.
XHPROF_FLAGS_MEMORY (integer)
Used to add memory profiling information to the output.
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Example #1 Xhprof example with the optional GUI
This example starts and stops the profiler, then uses the bundled GUI
interface to save and parse the results. In other words, the code from the
extension itself ends at the call to xhprof_disable().
save_run($xhprof_data, "xhprof_testing");
echo "http://localhost/xhprof/xhprof_html/index.php?run={$run_id}&source=xhprof_testing\n";
?>
The above example will output something similar to:
http://localhost/xhprof/xhprof_html/index.php?run=t11_4bdf44d21121f&source=xhprof_testing
----------------------------------------------------------------------
----------------------------------------------------------------------
Xhprof Functions
----------------------------------------------------------------------
xhprof_disable
(PECL xhprof >= 0.9.0)
xhprof_disable - Stops xhprof profiler
Description
array xhprof_disable ( void )
Stops the profiler, and returns xhprof data from the run.
Parameters
This function has no parameters.
Return Values
An array of xhprof data, from the run.
Examples
Example #1 xhprof_disable() example
The above example will output something similar to:
Array
(
[main()==>strlen] => Array
(
[ct] => 1
[wt] => 279
)
[main()==>xhprof_disable] => Array
(
[ct] => 1
[wt] => 9
)
[main()] => Array
(
[ct] => 1
[wt] => 610
)
)
----------------------------------------------------------------------
----------------------------------------------------------------------
xhprof_enable
(PECL xhprof >= 0.9.0)
xhprof_enable - Start xhprof profiler
Description
void xhprof_enable ([ int $flags = 0 [, array $options ]] )
Start xhprof profiling.
Parameters
flags
Optional flags to add additional information to the profiling. See
the XHprof constants for further information about these flags,
e.g., XHPROF_FLAGS_MEMORY to enable memory profiling.
options
An array of optional options, namely, the 'ignored_functions'
option to pass in functions to be ignored during profiling.
Return Values
NULL
Changelog
Version Description
0.9.2 The optional options parameter was added.
Examples
Example #1 xhprof_enable() examples
array('call_user_func',
'call_user_func_array')));
// 3. elapsed time + memory profiling; ignore call_user_func* during profiling
xhprof_enable(
XHPROF_FLAGS_MEMORY,
array('ignored_functions' => array('call_user_func',
'call_user_func_array')));
?>
See Also
* xhprof_disable() - Stops xhprof profiler
* xhprof_sample_enable() - Description
* memory_get_usage() - Returns the amount of memory allocated to PHP
* getrusage() - Gets the current resource usages
----------------------------------------------------------------------
----------------------------------------------------------------------
xhprof_sample_disable
(PECL xhprof >= 0.9.0)
xhprof_sample_disable - Stops xhprof sample profiler
Description
NULL xhprof_sample_disable ( void )
Stops the sample mode xhprof profiler, and
Warning
This function is currently not documented; only its argument list is
available.
Parameters
This function has no parameters.
Return Values
An array of xhprof sample data, from the run.
Examples
Example #1 xhprof_sample_disable() example
The above example will output something similar to:
Array
(
[1272935300.800000] => main()
[1272935300.900000] => main()
)
----------------------------------------------------------------------
----------------------------------------------------------------------
xhprof_sample_enable
(PECL xhprof >= 0.9.0)
xhprof_sample_enable - Description
Description
void xhprof_sample_enable ( void )
Starts profiling in sample mode, which is a lighter weight version of
xhprof_enable(). The sampling interval is 0.1 seconds, and samples record
the full function call stack. The main use case is when lower overhead is
required when doing performance monitoring and diagnostics.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
This function has no parameters.
Return Values
NULL
See Also
* xhprof_sample_disable() - Stops xhprof sample profiler
* xhprof_enable() - Start xhprof profiler
* memory_get_usage() - Returns the amount of memory allocated to PHP
* getrusage() - Gets the current resource usages
----------------------------------------------------------------------
Table of Contents
* xhprof_disable - Stops xhprof profiler
* xhprof_enable - Start xhprof profiler
* xhprof_sample_disable - Stops xhprof sample profiler
* xhprof_sample_enable - Description
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* Xhprof Functions
* xhprof_disable - Stops xhprof profiler
* xhprof_enable - Start xhprof profiler
* xhprof_sample_disable - Stops xhprof sample profiler
* xhprof_sample_enable - Description
----------------------------------------------------------------------
* APC - Alternative PHP Cache
* Introduction
* Installing/Configuring
* Predefined Constants
* APC Functions
* APCIterator - The APCIterator class
* APD - Advanced PHP debugger
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* APD Functions
* bcompiler - PHP bytecode Compiler
* Introduction
* Installing/Configuring
* Predefined Constants
* bcompiler Functions
* Error Handling - Error Handling and Logging
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* Error Handling Functions
* htscanner - htaccess-like support for all SAPIs
* Introduction
* Installing/Configuring
* inclued - Inclusion hierarchy viewer
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* inclued Functions
* PHP Options/Info - PHP Options and Information
* Introduction
* Installing/Configuring
* Predefined Constants
* PHP Options/Info Functions
* Memtrack
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* Object overloading - Object property and method call overloading
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* Object overloading Functions
* Output Control - Output Buffering Control
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* Output Control Functions
* runkit
* Introduction
* Predefined Constants
* Installing/Configuring
* runkit Functions
* scream - Break the silence operator
* Introduction
* Installing/Configuring
* Examples
* WinCache - Windows Cache for PHP
* Introduction
* Installing/Configuring
* Predefined Constants
* WinCache Functions
* Building for Windows
* Xhprof - Hierarchical Profiler
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* Xhprof Functions
----------------------------------------------------------------------
----------------------------------------------------------------------
Audio Formats Manipulation
----------------------------------------------------------------------
ID3 Tags
----------------------------------------------------------------------
Introduction
These functions let you read and manipulate ID3 tags. ID3 tags are used in
MP3 files to store title of the song, as well as information about the
artist, album, genre, year and track number.
Since version 0.2 it is also possible to extract text frames from ID3
v2.2+ tags.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here: >> http://pecl.php.net/package/id3.
A DLL for this PECL extension is currently unavailable. See also the
building on Windows section.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
Most of the id3 functions either let you specify or return a tag version.
In order to specify the version please use on of these constants.
ID3_V1_0 (integer)
ID3_V1_0 is used if you are working with ID3 V1.0 tags. These tags
may contain the fields title, artist, album, genre, year and
comment.
ID3_V1_1 (integer)
ID3_V1_1 is used if you are working with ID3 V1.1 tags. These tags
may all information contained in v1.0 tags plus the track number.
ID3_V2_1 (integer)
ID3_V2_1 is used if you are working with ID3 V2.1 tags.
ID3_V2_2 (integer)
ID3_V2_2 is used if you are working with ID3 V2.2 tags.
ID3_V2_3 (integer)
ID3_V2_3 is used if you are working with ID3 V2.3 tags.
ID3_V2_4 (integer)
ID3_V2_4 is used if you are working with ID3 V2.4 tags.
ID3_BEST (integer)
ID3_BEST is used if would like to let the id3 functions determine
which tag version should be used.
----------------------------------------------------------------------
----------------------------------------------------------------------
ID3 Functions
----------------------------------------------------------------------
id3_get_frame_long_name
(PECL id3 >= 0.2)
id3_get_frame_long_name - Get the long name of an ID3v2 frame
Description
string id3_get_frame_long_name ( string $frameId )
id3_get_frame_long_name() returns the long name for an ID3v2 frame.
Parameters
frameId
An ID3v2 frame
Return Values
Returns the frame long name or FALSE on errors.
Examples
Example #1 id3_get_frame_long_name() example
The above example will output:
Original lyricist(s)/text writer(s)
See Also
* id3_get_frame_short_name() - Get the short name of an ID3v2 frame
----------------------------------------------------------------------
----------------------------------------------------------------------
id3_get_frame_short_name
(PECL id3 >= 0.2)
id3_get_frame_short_name - Get the short name of an ID3v2 frame
Description
string id3_get_frame_short_name ( string $frameId )
id3_get_frame_short_name() returns the short name for an ID3v2 frame.
Parameters
frameId
An ID3v2 frame
Return Values
Returns the frame short name or FALSE on errors.
The values returned by id3_get_frame_short_name() are used in the array
returned by id3_get_tag().
Examples
Example #1 id3_get_frame_short_name() example
The above example will output:
originalLyricist
See Also
* id3_get_frame_long_name() - Get the long name of an ID3v2 frame
----------------------------------------------------------------------
----------------------------------------------------------------------
id3_get_genre_id
(PECL id3 >= 0.1)
id3_get_genre_id - Get the id for a genre
Description
int id3_get_genre_id ( string $genre )
id3_get_genre_id() returns the id for a genre.
Parameters
genre
An integer ranging from 0 to 147
Return Values
The genre id or FALSE on errors.
Examples
Example #1 id3_get_genre_id() example
The above example will output:
20
See Also
* id3_get_genre_name() - Get the name for a genre id
* id3_get_genre_list() - Get all possible genre values
----------------------------------------------------------------------
----------------------------------------------------------------------
id3_get_genre_list
(PECL id3 >= 0.1)
id3_get_genre_list - Get all possible genre values
Description
array id3_get_genre_list ( void )
id3_get_genre_list() returns an array containing all possible genres that
may be stored in an ID3 tag. This list has been created by Eric Kemp and
later extended by WinAmp.
This function is useful to provide you users a list of genres from which
they may choose one. When updating the ID3 tag you will always have to
specify the genre as an integer ranging from 0 to 147.
Return Values
Returns an array containing all possible genres that may be stored in an
ID3 tag.
Examples
Example #1 id3_get_genre_list() example
The above example will output:
Array
(
[0] => Blues
[1] => Classic Rock
[2] => Country
[3] => Dance
[4] => Disco
[5] => Funk
[6] => Grunge
[7] => Hip-Hop
[8] => Jazz
[9] => Metal
[10] => New Age
[11] => Oldies
[12] => Other
[13] => Pop
[14] => R&B
[15] => Rap
[16] => Reggae
[17] => Rock
[18] => Techno
[19] => Industrial
[20] => Alternative
[21] => Ska
[22] => Death Metal
[23] => Pranks
[24] => Soundtrack
[25] => Euro-Techno
[26] => Ambient
[27] => Trip-Hop
[28] => Vocal
[29] => Jazz+Funk
[30] => Fusion
[31] => Trance
[32] => Classical
[33] => Instrumental
[34] => Acid
[35] => House
[36] => Game
[37] => Sound Clip
[38] => Gospel
[39] => Noise
[40] => Alternative Rock
[41] => Bass
[42] => Soul
[43] => Punk
[44] => Space
[45] => Meditative
[46] => Instrumental Pop
[47] => Instrumental Rock
[48] => Ethnic
[49] => Gothic
[50] => Darkwave
[51] => Techno-Industrial
[52] => Electronic
[53] => Pop-Folk
[54] => Eurodance
[55] => Dream
[56] => Southern Rock
[57] => Comedy
[58] => Cult
[59] => Gangsta
[60] => Top 40
[61] => Christian Rap
[62] => Pop/Funk
[63] => Jungle
[64] => Native US
[65] => Cabaret
[66] => New Wave
[67] => Psychadelic
[68] => Rave
[69] => Showtunes
[70] => Trailer
[71] => Lo-Fi
[72] => Tribal
[73] => Acid Punk
[74] => Acid Jazz
[75] => Polka
[76] => Retro
[77] => Musical
[78] => Rock & Roll
[79] => Hard Rock
[80] => Folk
[81] => Folk-Rock
[82] => National Folk
[83] => Swing
[84] => Fast Fusion
[85] => Bebob
[86] => Latin
[87] => Revival
[88] => Celtic
[89] => Bluegrass
[90] => Avantgarde
[91] => Gothic Rock
[92] => Progressive Rock
[93] => Psychedelic Rock
[94] => Symphonic Rock
[95] => Slow Rock
[96] => Big Band
[97] => Chorus
[98] => Easy Listening
[99] => Acoustic
[100] => Humour
[101] => Speech
[102] => Chanson
[103] => Opera
[104] => Chamber Music
[105] => Sonata
[106] => Symphony
[107] => Booty Bass
[108] => Primus
[109] => Porn Groove
[110] => Satire
[111] => Slow Jam
[112] => Club
[113] => Tango
[114] => Samba
[115] => Folklore
[116] => Ballad
[117] => Power Ballad
[118] => Rhytmic Soul
[119] => Freestyle
[120] => Duet
[121] => Punk Rock
[122] => Drum Solo
[123] => Acapella
[124] => Euro-House
[125] => Dance Hall
[126] => Goa
[127] => Drum & Bass
[128] => Club-House
[129] => Hardcore
[130] => Terror
[131] => Indie
[132] => BritPop
[133] => Negerpunk
[134] => Polsk Punk
[135] => Beat
[136] => Christian Gangsta
[137] => Heavy Metal
[138] => Black Metal
[139] => Crossover
[140] => Contemporary C
[141] => Christian Rock
[142] => Merengue
[143] => Salsa
[144] => Thrash Metal
[145] => Anime
[146] => JPop
[147] => SynthPop
)
See Also
* id3_get_genre_name() - Get the name for a genre id
* id3_get_genre_id() - Get the id for a genre
----------------------------------------------------------------------
----------------------------------------------------------------------
id3_get_genre_name
(PECL id3 >= 0.1)
id3_get_genre_name - Get the name for a genre id
Description
string id3_get_genre_name ( int $genre_id )
id3_get_genre_name() returns the name for a genre id.
Parameters
genre_id
An integer ranging from 0 to 147
Return Values
Returns the name as a string.
Examples
Example #1 id3_get_genre_name() example
The above example will output:
Alternative
See Also
* id3_get_genre_list() - Get all possible genre values
* id3_get_genre_id() - Get the id for a genre
----------------------------------------------------------------------
----------------------------------------------------------------------
id3_get_tag
(PECL id3 >= 0.1)
id3_get_tag - Get all information stored in an ID3 tag
Description
array id3_get_tag ( string $filename [, int $version = ID3_BEST ] )
id3_get_tag() is used to get all information stored in the id3 tag of the
specified file.
Parameters
filename
The path to the MP3 file
Instead of a filename you may also pass a valid stream resource
version
Allows you to specify the version of the tag as MP3 files may
contain both, version 1.x and version 2.x tags
Since version 0.2 id3_get_tag() also supports ID3 tags of version
2.2, 2.3 and 2.4. To extract information from these tags, pass one
of the constants ID3_V2_2, ID3_V2_3 or ID3_V2_4 as the second
parameter. ID3 v2.x tags can contain a lot more information about
the MP3 file than ID3 v1.x tags.
Return Values
Returns an associative array with various keys like: title, artist, ..
The key genre will contain an integer between 0 and 147. You may use
id3_get_genre_name() to convert it to a human readable string.
Examples
Example #1 id3_get_tag() example
The above example will output something similar to:
Array
(
[title] => DN-38416
[artist] => Re:\Legion
[album] => Reflections
[year] => 2004
[genre] => 19
)
Example #2 id3_get_tag() example
The above example will output something similar to:
Array
(
[copyright] => Dirty Mac
[originalArtist] => Dirty Mac
[composer] => Marcus Go:tze
[artist] => Dirty Mac
[title] => Little Big Man
[album] => Demo-Tape
[track] => 5/12
[genre] => (17)Rock
[year] => 2001
)
See Also
* id3_set_tag() - Update information stored in an ID3 tag
* id3_remove_tag() - Remove an existing ID3 tag
* id3_get_version() - Get version of an ID3 tag
----------------------------------------------------------------------
----------------------------------------------------------------------
id3_get_version
(PECL id3 >= 0.1)
id3_get_version - Get version of an ID3 tag
Description
int id3_get_version ( string $filename )
id3_get_version() retrieves the version(s) of the ID3 tag(s) in the MP3
file.
If a file contains an ID3 v1.1 tag, it always contains a 1.0 tag, as
version 1.1 is just an extension of 1.0.
Parameters
filename
The path to the MP3 file
Instead of a filename you may also pass a valid stream resource
Return Values
Returns the version number of the ID3 tag of the file. As a tag can
contain ID3 v1.x and v2.x tags, the return value of this function should
be bitwise compared with the predefined constants ID3_V1_0, ID3_V1_1 and
ID3_V2.
Examples
Example #1 id3_get_version() example
The above example will output something similar to:
Contains a 1.x tag
Contains a 1.1 tag
See Also
* id3_set_tag() - Update information stored in an ID3 tag
* id3_get_tag() - Get all information stored in an ID3 tag
* id3_remove_tag() - Remove an existing ID3 tag
----------------------------------------------------------------------
----------------------------------------------------------------------
id3_remove_tag
(PECL id3 >= 0.1)
id3_remove_tag - Remove an existing ID3 tag
Description
bool id3_remove_tag ( string $filename [, int $version = ID3_V1_0 ] )
id3_remove_tag() is used to remove the information stored of an ID3 tag.
Parameters
filename
The path to the MP3 file
Instead of a filename you may also pass a valid stream resource
version
Allows you to specify the version of the tag as MP3 files may
contain both, version 1.x and version 2.x tags.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 id3_remove_tag() example
If the file is writable and contained a 1.0 tag, this will output:
Tag succesfully removed
Notes
Note: Currently id3_remove_tag() only supports version 1.0 and 1.1. If
you choose to remove a 1.0 tag and the file contains a 1.1 tag, this tag
will be removed, as v1.1 is only an extension of 1.0.
See Also
* id3_set_tag() - Update information stored in an ID3 tag
* id3_get_tag() - Get all information stored in an ID3 tag
* id3_get_version() - Get version of an ID3 tag
----------------------------------------------------------------------
----------------------------------------------------------------------
id3_set_tag
(PECL id3 >= 0.1)
id3_set_tag - Update information stored in an ID3 tag
Description
bool id3_set_tag ( string $filename , array $tag [, int $version =
ID3_V1_0 ] )
id3_set_tag() is used to change the information stored of an ID3 tag. If
no tag has been present, it will be added to the file.
Parameters
filename
The path to the MP3 file
Instead of a filename you may also pass a valid stream resource
tag
An associative array of tag keys and values
The following keys may be used in the associative array:
Keys in the associative array
key possible value available in version
title string with maximum of 30 characters v1.0, v1.1
artist string with maximum of 30 characters v1.0, v1.1
album string with maximum of 30 characters v1.0, v1.1
year 4 digits v1.0, v1.1
genre integer value between 0 and 147 v1.0, v1.1
comment string with maximum of 30 characters v1.0, v1.1
(28 in v1.1)
track integer between 0 and 255 v1.1
version
Allows you to specify the version of the tag as MP3 files may
contain both, version 1.x and version 2.x tags
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 id3_set_tag() example
"Re:Start",
"artist" => "Re:\Legion",
"comment" => "A nice track"
);
$result = id3_set_tag( "path/to/example.mp3", $data, ID3_V1_0 );
if ($result === true) {
echo "Tag succesfully updated\n";
}
?>
If the file is writable, this will output:
Tag succesfully updated
Notes
Note: Currently id3_remove_tag() only supports version 1.0 and 1.1.
See Also
* id3_remove_tag() - Remove an existing ID3 tag
* id3_get_tag() - Get all information stored in an ID3 tag
* id3_get_version() - Get version of an ID3 tag
----------------------------------------------------------------------
Table of Contents
* id3_get_frame_long_name - Get the long name of an ID3v2 frame
* id3_get_frame_short_name - Get the short name of an ID3v2 frame
* id3_get_genre_id - Get the id for a genre
* id3_get_genre_list - Get all possible genre values
* id3_get_genre_name - Get the name for a genre id
* id3_get_tag - Get all information stored in an ID3 tag
* id3_get_version - Get version of an ID3 tag
* id3_remove_tag - Remove an existing ID3 tag
* id3_set_tag - Update information stored in an ID3 tag
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* ID3 Functions
* id3_get_frame_long_name - Get the long name of an ID3v2 frame
* id3_get_frame_short_name - Get the short name of an ID3v2 frame
* id3_get_genre_id - Get the id for a genre
* id3_get_genre_list - Get all possible genre values
* id3_get_genre_name - Get the name for a genre id
* id3_get_tag - Get all information stored in an ID3 tag
* id3_get_version - Get version of an ID3 tag
* id3_remove_tag - Remove an existing ID3 tag
* id3_set_tag - Update information stored in an ID3 tag
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib
----------------------------------------------------------------------
Introduction
KTaglib is an object oriented binding to the taglib library from the KDE
project used in projects like Amarok to read and write ID3 and Ogg tags.
The library also provides access to audio information. The bindings are
designed usually follow the underlying C++ API, but were changed whenever
there is a more PHP-like way.
Note:
At the moment ktaglib is able to read and write ID3v1 and ID3v2 tags.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
----------------------------------------------------------------------
Requirements
If you want to build ktaglib you need at least taglib 1.5 installed. To
obtain the taglib see the >> taglib project page. Windows DLL's are build
static against taglib, therefore there is no need to have taglib
installed.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here: >> http://pecl.php.net/package/ktaglib.
A DLL for this PECL extension is currently unavailable. See also the
building on Windows section.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
KTaglib uses class constants. Most of the constants are mappings to the
according Taglib enums and constants.
KTaglib_MPEG_Header::Version1 (integer)
ID3 version is 1.0
KTaglib_MPEG_Header::Version2 (integer)
ID3 version is 2.0
KTaglib_MPEG_Header::Version2_5 (integer)
ID3 version is 2.5
KTaglib_ID3v2_AttachedPictureFrame::Other (integer)
Picture type Other
KTaglib_ID3v2_AttachedPictureFrame::FileIcon (integer)
Picture type FileIcon
KTaglib_ID3v2_AttachedPictureFrame::OtherFileIcon (integer)
Picture type OtherFileIcon
KTaglib_ID3v2_AttachedPictureFrame::FrontCover (integer)
Picture type FrontCover
KTaglib_ID3v2_AttachedPictureFrame::BackCover (integer)
Picture type BackCover
KTaglib_ID3v2_AttachedPictureFrame::LeafletPage (integer)
Picture type LeafletPage
KTaglib_ID3v2_AttachedPictureFrame::Media (integer)
Picture type Media
KTaglib_ID3v2_AttachedPictureFrame::LeadArtist (integer)
Picture type LeadArtist
KTaglib_ID3v2_AttachedPictureFrame::Artist (integer)
Picture type Artist
KTaglib_ID3v2_AttachedPictureFrame::Conductor (integer)
Picture type Condutor
KTaglib_ID3v2_AttachedPictureFrame::Band (integer)
Picture type Band
KTaglib_ID3v2_AttachedPictureFrame::Composer (integer)
Picture type Composer
KTaglib_ID3v2_AttachedPictureFrame::Lyricist (integer)
Picture type Lyricist
KTaglib_ID3v2_AttachedPictureFrame::RecordingLocation (integer)
Picture type RecordingLocation
KTaglib_ID3v2_AttachedPictureFrame::DuringRecording (integer)
Picture type DuringRecording
KTaglib_ID3v2_AttachedPictureFrame::DuringPerformance (integer)
Picture type DuringPerformance
KTaglib_ID3v2_AttachedPictureFrame::MovieScreenCapture (integer)
Picture type MovieScreenCapture
KTaglib_ID3v2_AttachedPictureFrame::ColouredFish (integer)
Picture type ColouredFish
KTaglib_ID3v2_AttachedPictureFrame::Illustration (integer)
Picture type Illustration
KTaglib_ID3v2_AttachedPictureFrame::BandLogo (integer)
Picture type BandLogo
----------------------------------------------------------------------
----------------------------------------------------------------------
The KTagLib_MPEG_File class
Introduction
Represents an MPEG file. MPEG files can have ID3v1, ID3v2 tags and audio
properties.
Class synopsis
KTagLib_MPEG_File {
}
----------------------------------------------------------------------
KTaglib_MPEG_File::__construct
(0.0.1)
KTaglib_MPEG_File::__construct - Opens a new file
Description
KTaglib_MPEG_File::__construct() ( string $filename )
Opens a new MPEG file.
Parameters
filename
The file to read
Examples
Example #1 Opens a new MP3 file and read the title
getID3v1Tag()->getTitle();
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_MPEG_File::getAudioProperties
(0.0.1)
KTaglib_MPEG_File::getAudioProperties - Returns an object that provides
access to the audio properties
Description
public KTaglib_MPEG_File: KTaglib_MPEG_File::getAudioProperties ( void )
Returns an object that provides access to the audio properties of the mpeg
file.
Return Values
Returns an KTaglib_MPEG_AudioProperties object or false.
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_MPEG_File::getID3v1Tag
(0.0.1)
KTaglib_MPEG_File::getID3v1Tag - Returns an object representing an ID3v1
tag
Description
public KTaglib_ID3v1_Tag KTaglib_MPEG_File::getID3v1Tag ([ bool $create =
false ] )
Returns an object that represents an ID3v1 tag, which can be used to get
information about the ID3v1 tag.
Return Values
Returns an KTaglib_MPEG_ID3v1Tag object or false if there is no ID3v1 tag.
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_MPEG_File::getID3v2Tag
(0.0.1)
KTaglib_MPEG_File::getID3v2Tag - Returns a ID3v2 object
Description
public KTaglib_ID3v2_Tag KTaglib_MPEG_File::getID3v2Tag ([ bool $create =
false ] )
Returns a ID3v2 object for the mpeg file. If no ID3v2 Tag is present, an
KTaglib_TagNotFoundException is thrown.
Return Values
Returns the KTaglib_ID3v2_Tag object of the MPEG file or false if there is
no ID3v2 tag
----------------------------------------------------------------------
Table of Contents
* KTaglib_MPEG_File::__construct - Opens a new file
* KTaglib_MPEG_File::getAudioProperties - Returns an object that
provides access to the audio properties
* KTaglib_MPEG_File::getID3v1Tag - Returns an object representing an
ID3v1 tag
* KTaglib_MPEG_File::getID3v2Tag - Returns a ID3v2 object
----------------------------------------------------------------------
----------------------------------------------------------------------
The KTaglib_MPEG_AudioProperties class
Introduction
Represents the audio properties of a MPEG file, like length, bitrate or
samplerate.
Class synopsis
KTaglib_MPEG_AudioProperties {
}
----------------------------------------------------------------------
KTaglib_MPEG_AudioProperties::getBitrate
(0.0.1)
KTaglib_MPEG_AudioProperties::getBitrate - Returns the bitrate of the MPEG
file
Description
public int KTaglib_MPEG_AudioProperties::getBitrate ( void )
Returns the bitrate of the MPEG file
Return Values
Returns the bitrate as an integer
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_MPEG_AudioProperties::getChannels
(0.0.1)
KTaglib_MPEG_AudioProperties::getChannels - Returns the amount of channels
of a MPEG file
Description
public int KTaglib_MPEG_AudioProperties::getChannels ( void )
Returns the amount of channels of the MPEG file
Return Values
Returns the channel count as an integer
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_MPEG_AudioProperties::getLayer
(0.0.1)
KTaglib_MPEG_AudioProperties::getLayer - Returns the layer of a MPEG file
Description
public int KTaglib_MPEG_AudioProperties::getLayer ( void )
Returns the layer of the MPEG file (usually 3 for MP3).
Return Values
Returns the layer as an integer
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_MPEG_AudioProperties::getLength
(0.0.1)
KTaglib_MPEG_AudioProperties::getLength - Returns the length of a MPEG
file
Description
public int KTaglib_MPEG_AudioProperties::getLength ( void )
Returns the length of the MPEG file
Return Values
Returns the length as an integer
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_MPEG_AudioProperties::getSampleBitrate
(0.0.1)
KTaglib_MPEG_AudioProperties::getSampleBitrate - Returns the sample
bitrate of a MPEG file
Description
public int KTaglib_MPEG_AudioProperties::getSampleBitrate ( void )
Returns the sample bitrate of the MPEG file
Return Values
Returns the sample bitrate as an integer
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_MPEG_AudioProperties::getVersion
(0.0.1)
KTaglib_MPEG_AudioProperties::getVersion - Returns the version of a MPEG
file
Description
public int KTaglib_MPEG_AudioProperties::getVersion ( void )
Returns the version of the MPEG file header. The possible versions are
defined in Tag_MPEG_Header (Version1, Version2, Version2.5).
Return Values
Returns the version
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_MPEG_AudioProperties::isCopyrighted
(0.0.1)
KTaglib_MPEG_AudioProperties::isCopyrighted - Returns the length of a MPEG
file
Description
public bool KTaglib_MPEG_AudioProperties::isCopyrighted ( void )
Returns true if the MPEG file is copyrighted
Return Values
Returns true if the MPEG file is copyrighted
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_MPEG_AudioProperties::isOriginal
(0.0.1)
KTaglib_MPEG_AudioProperties::isOriginal - Returns the length of a MPEG
file
Description
public bool KTaglib_MPEG_AudioProperties::isOriginal ( void )
Returns true if the file is marked as the original file
Return Values
Returns true if the file is marked as the original file
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_MPEG_AudioProperties::isProtectionEnabled
(0.0.1)
KTaglib_MPEG_AudioProperties::isProtectionEnabled - Returns the length of
a MPEG file
Description
public bool KTaglib_MPEG_AudioProperties::isProtectionEnabled ( void )
Returns true if protection mechanism (like DRM) are enabled for this file
Return Values
Returns true if protection mechanism (like DRM) are enabled for this file
----------------------------------------------------------------------
Table of Contents
* KTaglib_MPEG_AudioProperties::getBitrate - Returns the bitrate of the
MPEG file
* KTaglib_MPEG_AudioProperties::getChannels - Returns the amount of
channels of a MPEG file
* KTaglib_MPEG_AudioProperties::getLayer - Returns the layer of a MPEG
file
* KTaglib_MPEG_AudioProperties::getLength - Returns the length of a MPEG
file
* KTaglib_MPEG_AudioProperties::getSampleBitrate - Returns the sample
bitrate of a MPEG file
* KTaglib_MPEG_AudioProperties::getVersion - Returns the version of a
MPEG file
* KTaglib_MPEG_AudioProperties::isCopyrighted - Returns the length of a
MPEG file
* KTaglib_MPEG_AudioProperties::isOriginal - Returns the length of a
MPEG file
* KTaglib_MPEG_AudioProperties::isProtectionEnabled - Returns the length
of a MPEG file
----------------------------------------------------------------------
----------------------------------------------------------------------
The KTaglib_Tag class
Introduction
Base class for ID3v1 or ID3v2 tags
Class synopsis
KTaglib_Tag {
}
----------------------------------------------------------------------
KTaglib_Tag::getAlbum
(0.0.1)
KTaglib_Tag::getAlbum - Returns the title string from a ID3 tag
Description
public string KTaglib_Tag::getAlbum ( void )
Returns the album string of an ID3 tag. This method is implemented in
ID3v1 and ID3v2 tags.
Return Values
Returns the album string
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_Tag::getArtist
(0.0.1)
KTaglib_Tag::getArtist - Returns the artist string from a ID3 tag
Description
public string KTaglib_Tag::getArtist ( void )
Returns the artist string of an ID3 tag. This method is implemented in
ID3v1 and ID3v2 tags.
Return Values
Returns the artist string
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_Tag::getComment
(0.0.1)
KTaglib_Tag::getComment - Returns the comment from a ID3 tag
Description
public string KTaglib_Tag::getComment ( void )
Returns the comment of an ID3 tag. This method is implemented in ID3v1 and
ID3v2 tags.
Return Values
Returns the comment string
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_Tag::getGenre
(0.0.1)
KTaglib_Tag::getGenre - Returns the genre from a ID3 tag
Description
public string KTaglib_Tag::getGenre ( void )
Returns the genre of an ID3 tag. This method is implemented in ID3v1 and
ID3v2 tags.
Return Values
Returns the genre string
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_Tag::getTitle
(0.0.1)
KTaglib_Tag::getTitle - Returns the title string from a ID3 tag
Description
public string KTaglib_Tag::getTitle ( void )
Returns the title string of an ID3 tag. This method is implemented in
ID3v1 and ID3v2 tags.
Return Values
Returns the title string
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_Tag::getTrack
(0.0.1)
KTaglib_Tag::getTrack - Returns the track number from a ID3 tag
Description
public int KTaglib_Tag::getTrack ( void )
Returns the track number of an ID3 tag. This method is implemented in
ID3v1 and ID3v2 tags.
Return Values
Returns the track number as an integer
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_Tag::getYear
(0.0.1)
KTaglib_Tag::getYear - Returns the year from a ID3 tag
Description
public int KTaglib_Tag::getYear ( void )
Returns the year of an ID3 tag. This method is implemented in ID3v1 and
ID3v2 tags.
Return Values
Returns the year as an integer
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_Tag::isEmpty
(0.0.1)
KTaglib_Tag::isEmpty - Returns true if the tag is empty
Description
public bool KTaglib_Tag::isEmpty ( void )
Returns true if the tag exists, but is empty. This method is implemented
in ID3v1 and ID3v2 tags.
Return Values
Returns true if the tag is empty, otherwise false.
----------------------------------------------------------------------
Table of Contents
* KTaglib_Tag::getAlbum - Returns the title string from a ID3 tag
* KTaglib_Tag::getArtist - Returns the artist string from a ID3 tag
* KTaglib_Tag::getComment - Returns the comment from a ID3 tag
* KTaglib_Tag::getGenre - Returns the genre from a ID3 tag
* KTaglib_Tag::getTitle - Returns the title string from a ID3 tag
* KTaglib_Tag::getTrack - Returns the track number from a ID3 tag
* KTaglib_Tag::getYear - Returns the year from a ID3 tag
* KTaglib_Tag::isEmpty - Returns true if the tag is empty
----------------------------------------------------------------------
----------------------------------------------------------------------
The KTagLib_ID3v2_Tag class
Introduction
Represents and ID3v2 tag. It provides a list of ID3v2 frames and can be
used to add and remove additional frames.
Class synopsis
extends KTagLib_Tag {
}
----------------------------------------------------------------------
KTaglib_ID3v2_Tag::addFrame
(0.0.1)
KTaglib_ID3v2_Tag::addFrame - Add a frame to the ID3v2 tag
Description
public bool KTaglib_ID3v2_Tag::addFrame ( KTagLib_ID3v2_Frame $frame )
Adds a frame to the ID3v2 tag. The frame must be a valid
KTagLib_ID3v2_Frame object. To save the tag, the save function needs to be
invoked.
Return Values
Returns true on success, otherwise false.
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_ID3v2_Tag::getFrameList
(0.0.1)
KTaglib_ID3v2_Tag::getFrameList - Returns an array of ID3v2 frames,
associated with the ID3v2 tag
Description
public array KTaglib_ID3v2_Tag::getFrameList ( void )
Returns an array of ID3v2 frames, associated with the ID3v2 tag.
Return Values
Return an array of KTaglib_ID3v2_Frame objects
----------------------------------------------------------------------
Table of Contents
* KTaglib_ID3v2_Tag::addFrame - Add a frame to the ID3v2 tag
* KTaglib_ID3v2_Tag::getFrameList - Returns an array of ID3v2 frames,
associated with the ID3v2 tag
----------------------------------------------------------------------
----------------------------------------------------------------------
The KTagLib_ID3v2_Frame class
Introduction
The base class for ID3v2 frames. ID3v2 tags are separated in various
specialized frames. Some frames can exists multiple times.
Class synopsis
extends KTagLib_Tag {
}
----------------------------------------------------------------------
KTaglib_ID3v2_Frame::getSize
(0.0.1)
KTaglib_ID3v2_Frame::getSize - Returns the size of the frame in bytes
Description
public int KTaglib_ID3v2_Frame::getSize ( void )
Returns the size of the frame in bytes. Please refer to id3.org to see
what ID3v2 frames are and how they are defined.
Return Values
Returns the size of the frame in bytes
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_ID3v2_Frame::__toString
(0.0.1)
KTaglib_ID3v2_Frame::__toString - Returns a string representation of the
frame
Description
public string KTaglib_ID3v2_Frame::__toString ( void )
Returns a string representation of the frame. This might be just the frame
id, but might contain more information. Please see the ktaglib
documentation for more information
Return Values
Returns a string representation of the frame.
----------------------------------------------------------------------
Table of Contents
* KTaglib_ID3v2_Frame::getSize - Returns the size of the frame in bytes
* KTaglib_ID3v2_Frame::__toString - Returns a string representation of
the frame
----------------------------------------------------------------------
----------------------------------------------------------------------
The KTaglib_ID3v2_AttachedPictureFrame class
Introduction
Represents an ID3v2 frame that can hold a picture.
Class synopsis
extends KTagLib_ID3v2_Frame {
}
----------------------------------------------------------------------
KTaglib_ID3v2_AttachedPictureFrame::getDescription
(0.0.1)
KTaglib_ID3v2_AttachedPictureFrame::getDescription - Returns a description
for the picture in a picture frame
Description
public string KTaglib_ID3v2_AttachedPictureFrame::getDescription ( void )
Returns the attached description for a picture frame in an ID3v2.x frame.
Return Values
Returns a description for the picture in a picture frame
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_ID3v2_AttachedPictureFrame::getMimeType
(0.2.0)
KTaglib_ID3v2_AttachedPictureFrame::getMimeType - Returns the mime type of
the picture
Description
public string KTaglib_ID3v2_AttachedPictureFrame::getMimeType ( void )
Returns the mime type of the image represented by the attached picture
frame.
Please notice that this method might return different types. While ID3v2.2
have a mime type that doesn't start with "image/", ID3v2.3 and v2.4
usually start with "image/". Therefore the method might return "image/png"
for IDv2.3 frames and just "PNG" for ID3v2.2 frames.
Notice that even the frame is an attached picture, the mime type might not
be set and therefore an empty string might be returned.
Return Values
Returns the mime type of the image represented by the attached picture
frame.
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_ID3v2_AttachedPictureFrame::getType
(0.2.0)
KTaglib_ID3v2_AttachedPictureFrame::getType - Returns the type of the
image
Description
public int KTaglib_ID3v2_AttachedPictureFrame::getType ( void )
Returns the type of the image.
The ID3v2 specification allows an AttachedPictureFrame to set the type of
an image. This can be e.g. FrontCover or FileIcon. Please refer to the
KTagLib_ID3v2_AttachedPictureFrame class description for a list of
available types.
Return Values
Returns the integer representation of the type.
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_ID3v2_AttachedPictureFrame::savePicture
(0.0.1)
KTaglib_ID3v2_AttachedPictureFrame::savePicture - Saves the picture to a
file
Description
public bool KTaglib_ID3v2_AttachedPictureFrame::savePicture ( string
$filename )
Saves the attached picture to the given filename.
Return Values
Returns true on success, otherwise false
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_ID3v2_AttachedPictureFrame::setMimeType
(0.2.0)
KTaglib_ID3v2_AttachedPictureFrame::setMimeType - Set's the mime type of
the picture
Description
public string KTaglib_ID3v2_AttachedPictureFrame::getMimeType ( string
$type )
Sets the mime type of the image. This should in most cases be "image/png"
or "image/jpeg".
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_ID3v2_AttachedPictureFrame::setPicture
(0.0.1)
KTaglib_ID3v2_AttachedPictureFrame::setPicture - Sets the frame picture to
the given image
Description
public void KTaglib_ID3v2_AttachedPictureFrame::setPicture ( string
$filename )
Sets the picture to the give image. The image is loaded from the given
filename. Please note that the picture is not saved unless you call the
save method of the corresponding file object.
Return Values
Returns true on success, otherwise false
----------------------------------------------------------------------
----------------------------------------------------------------------
KTaglib_ID3v2_AttachedPictureFrame::setType
(0.2.0)
KTaglib_ID3v2_AttachedPictureFrame::setType - Set the type of the image
Description
public void KTaglib_ID3v2_AttachedPictureFrame::setType ( int $type )
Sets the type of the image. This can be e.g. FrontCover or FileIcon.
Please refer to the KTaglib_ID3v2_AttachedPictureFrame class description
for a list of available types and their constant mappings.
----------------------------------------------------------------------
Table of Contents
* KTaglib_ID3v2_AttachedPictureFrame::getDescription - Returns a
description for the picture in a picture frame
* KTaglib_ID3v2_AttachedPictureFrame::getMimeType - Returns the mime
type of the picture
* KTaglib_ID3v2_AttachedPictureFrame::getType - Returns the type of the
image
* KTaglib_ID3v2_AttachedPictureFrame::savePicture - Saves the picture to
a file
* KTaglib_ID3v2_AttachedPictureFrame::setMimeType - Set's the mime type
of the picture
* KTaglib_ID3v2_AttachedPictureFrame::setPicture - Sets the frame
picture to the given image
* KTaglib_ID3v2_AttachedPictureFrame::setType - Set the type of the
image
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Predefined Constants
* KTaglib_MPEG_File - The KTagLib_MPEG_File class
* KTaglib_MPEG_File::__construct - Opens a new file
* KTaglib_MPEG_File::getAudioProperties - Returns an object that
provides access to the audio properties
* KTaglib_MPEG_File::getID3v1Tag - Returns an object representing
an ID3v1 tag
* KTaglib_MPEG_File::getID3v2Tag - Returns a ID3v2 object
* KTaglib_MPEG_AudioProperties - The KTaglib_MPEG_AudioProperties class
* KTaglib_MPEG_AudioProperties::getBitrate - Returns the bitrate of
the MPEG file
* KTaglib_MPEG_AudioProperties::getChannels - Returns the amount of
channels of a MPEG file
* KTaglib_MPEG_AudioProperties::getLayer - Returns the layer of a
MPEG file
* KTaglib_MPEG_AudioProperties::getLength - Returns the length of a
MPEG file
* KTaglib_MPEG_AudioProperties::getSampleBitrate - Returns the
sample bitrate of a MPEG file
* KTaglib_MPEG_AudioProperties::getVersion - Returns the version of
a MPEG file
* KTaglib_MPEG_AudioProperties::isCopyrighted - Returns the length
of a MPEG file
* KTaglib_MPEG_AudioProperties::isOriginal - Returns the length of
a MPEG file
* KTaglib_MPEG_AudioProperties::isProtectionEnabled - Returns the
length of a MPEG file
* KTaglib_Tag - The KTaglib_Tag class
* KTaglib_Tag::getAlbum - Returns the title string from a ID3 tag
* KTaglib_Tag::getArtist - Returns the artist string from a ID3 tag
* KTaglib_Tag::getComment - Returns the comment from a ID3 tag
* KTaglib_Tag::getGenre - Returns the genre from a ID3 tag
* KTaglib_Tag::getTitle - Returns the title string from a ID3 tag
* KTaglib_Tag::getTrack - Returns the track number from a ID3 tag
* KTaglib_Tag::getYear - Returns the year from a ID3 tag
* KTaglib_Tag::isEmpty - Returns true if the tag is empty
* KTaglib_ID3v2_Tag - The KTagLib_ID3v2_Tag class
* KTaglib_ID3v2_Tag::addFrame - Add a frame to the ID3v2 tag
* KTaglib_ID3v2_Tag::getFrameList - Returns an array of ID3v2
frames, associated with the ID3v2 tag
* KTaglib_ID3v2_Frame - The KTagLib_ID3v2_Frame class
* KTaglib_ID3v2_Frame::getSize - Returns the size of the frame in
bytes
* KTaglib_ID3v2_Frame::__toString - Returns a string representation
of the frame
* KTaglib_ID3v2_AttachedPictureFrame - The
KTaglib_ID3v2_AttachedPictureFrame class
* KTaglib_ID3v2_AttachedPictureFrame::getDescription - Returns a
description for the picture in a picture frame
* KTaglib_ID3v2_AttachedPictureFrame::getMimeType - Returns the
mime type of the picture
* KTaglib_ID3v2_AttachedPictureFrame::getType - Returns the type of
the image
* KTaglib_ID3v2_AttachedPictureFrame::savePicture - Saves the
picture to a file
* KTaglib_ID3v2_AttachedPictureFrame::setMimeType - Set's the mime
type of the picture
* KTaglib_ID3v2_AttachedPictureFrame::setPicture - Sets the frame
picture to the given image
* KTaglib_ID3v2_AttachedPictureFrame::setType - Set the type of the
image
----------------------------------------------------------------------
----------------------------------------------------------------------
OGG/Vorbis
----------------------------------------------------------------------
Introduction
The OGG/Vorbis file format, as defined by >> http://www.vorbis.com/, is a
scheme for compressing audio streams by multiple factors with a minimum of
quality loss. This extension adds Ogg Vorbis support to PHP's URL
Wrappers. When used in read mode, compressed OGG/Vorbis data is expanded
to raw PCM audio in one of six PCM encoding formats listed below.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
This extension requires PHP >= 4.3.0, >> libogg >= 1.0, and >> libvorbis
>= 1.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here: >> http://pecl.php.net/package/oggvorbis
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
OGG/Vorbis supports PCM encodings in the following formats
Constant Definition
OGGVORBIS_PCM_U8 Unsigned 8-bit PCM.
OGGVORBIS_PCM_S8 Signed 8-bit PCM.
OGGVORBIS_PCM_U16_LE Unsigned 16-bit PCM. Little Endian byte order.
OGGVORBIS_PCM_U16_BE Unsigned 16-bit PCM. Big Endian byte order.
OGGVORBIS_PCM_S16_LE Signed 16-bit PCM. Little Endian byte order.
OGGVORBIS_PCM_S16_BE Signed 16-bit PCM. Big Endian byte order.
----------------------------------------------------------------------
----------------------------------------------------------------------
Context options
OGG/Vorbis tuning options
Option Definition Relevance Default
PCM byte encoding Read /
pcm_mode used. See constants Write OGGVORBIS_PCM_S16_LE
below.
rate PCM Sampling rate. Write only 44100
Measured in Hz.
Vorbis Average Bitrate
Encoding / Variable
Bitrate Encoding.
bitrate Measured in bps (ABR) Write only 128000
or Quality level (VBR:
0.0 to 1.0). 128000
ABR is rough equal to
0.4 VBR.
Number of PCM
channels channels. 1 == Mono, 2 Write only 2
== Stereo.
Serial Number of
stream within file.
Must be unique within
file. Because of the
potential to select a
serialno duplicate serial Write only Random
number within a
chained file, make
efforts to manually
assign unique numbers
when encoding.
Associative array of
file comments. Will be
translated to array('ENCODER' =>
comments strtoupper($name) . Write only 'PHP/OggVorbis,
"=$value". Note: This http://pear.php.net/oggvorbis')
context option is not
available in
oggvorbis-0.1
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Table of Contents
* Examples on using the ogg:// wrapper.
----------------------------------------------------------------------
Examples on using the ogg:// wrapper.
Example #1 Reading an OGG/Vorbis file
Example #2 Encode an audio file to OGG/Vorbis
array(
'pcm_mode' => OGGVORBIS_PCM_S8, /* Signed 8bit audio */
'rate' => 44100, /* 44kHz CD quality */
'bitrate' => 0.5, /* Midquality VBR */
'channels' => 1, /* Mono */
'serialno' => 12345))); /* Unique within our stream */
/* Open file for appending. This will "chain" a second OGG stream at the end of the first. */
$ogg = fopen('ogg://mysong.ogg', 'a', false, $context);
$pcm = fopen('mysample.pcm', 'r');
/* Compress the raw PCM audio from mysample.pcm into mysong.ogg */
stream_copy_to_stream($pcm, $ogg);
fclose($pcm);
fclose($ogg);
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Context options
* Examples
* Examples on using the ogg:// wrapper.
----------------------------------------------------------------------
----------------------------------------------------------------------
OpenAL Audio Bindings
----------------------------------------------------------------------
Introduction
Platform independent audio bindings. Requires the >> OpenAL library.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
This >> PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here: >> http://pecl.php.net/package/openal.
A DLL for this PECL extension is currently unavailable. See also the
building on Windows section.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension defines four resource types: Open AL(Device) - Returned by
openal_device_open(), Open AL(Context) - Returned by
openal_context_create(), Open AL(Buffer) - Returned by
openal_buffer_create(), and Open AL(Source) - Returned by
openal_source_create().
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
ALC_FREQUENCY (integer)
Context Attribute
ALC_REFRESH (integer)
Context Attribute
ALC_SYNC (integer)
Context Attribute
AL_FREQUENCY (integer)
Buffer Setting
AL_BITS (integer)
Buffer Setting
AL_CHANNELS (integer)
Buffer Setting
AL_SIZE (integer)
Buffer Setting
AL_BUFFER (integer)
Source/Listener Setting (Integer)
AL_SOURCE_RELATIVE (integer)
Source/Listener Setting (Integer)
AL_SOURCE_STATE (integer)
Source/Listener Setting (Integer)
AL_PITCH (integer)
Source/Listener Setting (Float)
AL_GAIN (integer)
Source/Listener Setting (Float)
AL_MIN_GAIN (integer)
Source/Listener Setting (Float)
AL_MAX_GAIN (integer)
Source/Listener Setting (Float)
AL_MAX_DISTANCE (integer)
Source/Listener Setting (Float)
AL_ROLLOFF_FACTOR (integer)
Source/Listener Setting (Float)
AL_CONE_OUTER_GAIN (integer)
Source/Listener Setting (Float)
AL_CONE_INNER_ANGLE (integer)
Source/Listener Setting (Float)
AL_CONE_OUTER_ANGLE (integer)
Source/Listener Setting (Float)
AL_REFERENCE_DISTANCE (integer)
Source/Listener Setting (Float)
AL_POSITION (integer)
Source/Listener Setting (Float Vector)
AL_VELOCITY (integer)
Source/Listener Setting (Float Vector)
AL_DIRECTION (integer)
Source/Listener Setting (Float Vector)
AL_ORIENTATION (integer)
Source/Listener Setting (Float Vector)
AL_FORMAT_MONO8 (integer)
PCM Format
AL_FORMAT_MONO16 (integer)
PCM Format
AL_FORMAT_STEREO8 (integer)
PCM Format
AL_FORMAT_STEREO16 (integer)
PCM Format
AL_INITIAL (integer)
Source State
AL_PLAYING (integer)
Source State
AL_PAUSED (integer)
Source State
AL_STOPPED (integer)
Source State
AL_LOOPING (integer)
Source State
AL_TRUE (integer)
Boolean value recognized by OpenAL
AL_FALSE (integer)
Boolean value recognized by OpenAL
----------------------------------------------------------------------
----------------------------------------------------------------------
OpenAL Functions
----------------------------------------------------------------------
openal_buffer_create
(PECL openal >= 0.1.0)
openal_buffer_create - Generate OpenAL buffer
Description
resource openal_buffer_create ( void )
Return Values
Returns an Open AL(Buffer) resource on success or FALSE on failure.
See Also
* openal_buffer_loadwav() - Load a .wav file into a buffer
* openal_buffer_data() - Load a buffer with data
----------------------------------------------------------------------
----------------------------------------------------------------------
openal_buffer_data
(PECL openal >= 0.1.0)
openal_buffer_data - Load a buffer with data
Description
bool openal_buffer_data ( resource $buffer , int $format , string $data ,
int $freq )
Parameters
buffer
An Open AL(Buffer) resource (previously created by
openal_buffer_create()).
format
Format of data, one of: AL_FORMAT_MONO8, AL_FORMAT_MONO16,
AL_FORMAT_STEREO8 and AL_FORMAT_STEREO16
data
Block of binary audio data in the format and freq specified.
freq
Frequency of data given in Hz.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* openal_buffer_loadwav() - Load a .wav file into a buffer
* openal_stream() - Begin streaming on a source
----------------------------------------------------------------------
----------------------------------------------------------------------
openal_buffer_destroy
(PECL openal >= 0.1.0)
openal_buffer_destroy - Destroys an OpenAL buffer
Description
bool openal_buffer_destroy ( resource $buffer )
Parameters
buffer
An Open AL(Buffer) resource (previously created by
openal_buffer_create()).
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* openal_buffer_create() - Generate OpenAL buffer
----------------------------------------------------------------------
----------------------------------------------------------------------
openal_buffer_get
(PECL openal >= 0.1.0)
openal_buffer_get - Retrieve an OpenAL buffer property
Description
int openal_buffer_get ( resource $buffer , int $property )
Parameters
buffer
An Open AL(Buffer) resource (previously created by
openal_buffer_create()).
property
Specific property, one of: AL_FREQUENCY, AL_BITS, AL_CHANNELS and
AL_SIZE.
Return Values
Returns an integer value appropriate to the property requested or FALSE on
failure.
See Also
* openal_buffer_create() - Generate OpenAL buffer
----------------------------------------------------------------------
----------------------------------------------------------------------
openal_buffer_loadwav
(PECL openal >= 0.1.0)
openal_buffer_loadwav - Load a .wav file into a buffer
Description
bool openal_buffer_loadwav ( resource $buffer , string $wavfile )
Parameters
buffer
An Open AL(Buffer) resource (previously created by
openal_buffer_create()).
wavfile
Path to .wav file on local file system.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* openal_buffer_data() - Load a buffer with data
* openal_stream() - Begin streaming on a source
----------------------------------------------------------------------
----------------------------------------------------------------------
openal_context_create
(PECL openal >= 0.1.0)
openal_context_create - Create an audio processing context
Description
resource openal_context_create ( resource $device )
Parameters
device
An Open AL(Device) resource (previously created by
openal_device_open()).
Return Values
Returns an Open AL(Context) resource on success or FALSE on failure.
See Also
* openal_device_open() - Initialize the OpenAL audio layer
* openal_context_destroy() - Destroys a context
----------------------------------------------------------------------
----------------------------------------------------------------------
openal_context_current
(PECL openal >= 0.1.0)
openal_context_current - Make the specified context current
Description
bool openal_context_current ( resource $context )
Parameters
context
An Open AL(Context) resource (previously created by
openal_context_create()).
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* openal_context_create() - Create an audio processing context
----------------------------------------------------------------------
----------------------------------------------------------------------
openal_context_destroy
(PECL openal >= 0.1.0)
openal_context_destroy - Destroys a context
Description
bool openal_context_destroy ( resource $context )
Parameters
context
An Open AL(Context) resource (previously created by
openal_context_create()).
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* openal_context_create() - Create an audio processing context
----------------------------------------------------------------------
----------------------------------------------------------------------
openal_context_process
(PECL openal >= 0.1.0)
openal_context_process - Process the specified context
Description
bool openal_context_process ( resource $context )
Parameters
context
An Open AL(Context) resource (previously created by
openal_context_create()).
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* openal_context_create() - Create an audio processing context
* openal_context_current() - Make the specified context current
* openal_context_suspend() - Suspend the specified context
----------------------------------------------------------------------
----------------------------------------------------------------------
openal_context_suspend
(PECL openal >= 0.1.0)
openal_context_suspend - Suspend the specified context
Description
bool openal_context_suspend ( resource $context )
Parameters
context
An Open AL(Context) resource (previously created by
openal_context_create()).
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* openal_context_create() - Create an audio processing context
* openal_context_current() - Make the specified context current
* openal_context_process() - Process the specified context
----------------------------------------------------------------------
----------------------------------------------------------------------
openal_device_close
(PECL openal >= 0.1.0)
openal_device_close - Close an OpenAL device
Description
bool openal_device_close ( resource $device )
Parameters
device
An Open AL(Device) resource (previously created by
openal_device_open()) to be closed.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* openal_device_open() - Initialize the OpenAL audio layer
----------------------------------------------------------------------
----------------------------------------------------------------------
openal_device_open
(PECL openal >= 0.1.0)
openal_device_open - Initialize the OpenAL audio layer
Description
resource openal_device_open ([ string $device_desc ] )
Parameters
device_desc
Open an audio device optionally specified by device_desc. If
device_desc is not specified the first available audio device will
be used.
Return Values
Returns an Open AL(Device) resource on success or FALSE on failure.
See Also
* openal_device_close() - Close an OpenAL device
* openal_context_create() - Create an audio processing context
----------------------------------------------------------------------
----------------------------------------------------------------------
openal_listener_get
(PECL openal >= 0.1.0)
openal_listener_get - Retrieve a listener property
Description
mixed openal_listener_get ( int $property )
Parameters
property
Property to retrieve, one of: AL_GAIN (float), AL_POSITION
(array(float,float,float)), AL_VELOCITY (array(float,float,float))
and AL_ORIENTATION (array(float,float,float)).
Return Values
Returns a float or array of floats (as appropriate) or FALSE on failure.
See Also
* openal_listener_set() - Set a listener property
----------------------------------------------------------------------
----------------------------------------------------------------------
openal_listener_set
(PECL openal >= 0.1.0)
openal_listener_set - Set a listener property
Description
bool openal_listener_set ( int $property , mixed $setting )
Parameters
property
Property to set, one of: AL_GAIN (float), AL_POSITION
(array(float,float,float)), AL_VELOCITY (array(float,float,float))
and AL_ORIENTATION (array(float,float,float)).
setting
Value to set, either float, or an array of floats as appropriate.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* openal_listener_get() - Retrieve a listener property
----------------------------------------------------------------------
----------------------------------------------------------------------
openal_source_create
(PECL openal >= 0.1.0)
openal_source_create - Generate a source resource
Description
resource openal_source_create ( void )
Return Values
Returns an Open AL(Source) resource on success or FALSE on failure.
See Also
* openal_source_set() - Set source property
* openal_source_play() - Start playing the source
* openal_source_destroy() - Destroy a source resource
----------------------------------------------------------------------
----------------------------------------------------------------------
openal_source_destroy
(PECL openal >= 0.1.0)
openal_source_destroy - Destroy a source resource
Description
bool openal_source_destroy ( resource $source )
Parameters
source
An Open AL(Source) resource (previously created by
openal_source_create()).
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* openal_source_create() - Generate a source resource
----------------------------------------------------------------------
----------------------------------------------------------------------
openal_source_get
(PECL openal >= 0.1.0)
openal_source_get - Retrieve an OpenAL source property
Description
mixed openal_source_get ( resource $source , int $property )
Parameters
source
An Open AL(Source) resource (previously created by
openal_source_create()).
property
Property to get, one of: AL_SOURCE_RELATIVE (int), AL_SOURCE_STATE
(int), AL_PITCH (float), AL_GAIN (float), AL_MIN_GAIN (float),
AL_MAX_GAIN (float), AL_MAX_DISTANCE (float), AL_ROLLOFF_FACTOR
(float), AL_CONE_OUTER_GAIN (float), AL_CONE_INNER_ANGLE (float),
AL_CONE_OUTER_ANGLE (float), AL_REFERENCE_DISTANCE (float),
AL_POSITION (array(float,float,float)), AL_VELOCITY
(array(float,float,float)), AL_DIRECTION
(array(float,float,float)).
Return Values
Returns the type associated with the property being retrieved or FALSE on
failure.
See Also
* openal_source_create() - Generate a source resource
* openal_source_set() - Set source property
* openal_source_play() - Start playing the source
----------------------------------------------------------------------
----------------------------------------------------------------------
openal_source_pause
(PECL openal >= 0.1.0)
openal_source_pause - Pause the source
Description
bool openal_source_pause ( resource $source )
Parameters
source
An Open AL(Source) resource (previously created by
openal_source_create()).
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* openal_source_stop() - Stop playing the source
* openal_source_play() - Start playing the source
* openal_source_rewind() - Rewind the source
----------------------------------------------------------------------
----------------------------------------------------------------------
openal_source_play
(PECL openal >= 0.1.0)
openal_source_play - Start playing the source
Description
bool openal_source_play ( resource $source )
Parameters
source
An Open AL(Source) resource (previously created by
openal_source_create()).
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* openal_source_stop() - Stop playing the source
* openal_source_pause() - Pause the source
* openal_source_rewind() - Rewind the source
----------------------------------------------------------------------
----------------------------------------------------------------------
openal_source_rewind
(PECL openal >= 0.1.0)
openal_source_rewind - Rewind the source
Description
bool openal_source_rewind ( resource $source )
Parameters
source
An Open AL(Source) resource (previously created by
openal_source_create()).
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* openal_source_stop() - Stop playing the source
* openal_source_pause() - Pause the source
* openal_source_play() - Start playing the source
----------------------------------------------------------------------
----------------------------------------------------------------------
openal_source_set
(PECL openal >= 0.1.0)
openal_source_set - Set source property
Description
bool openal_source_set ( resource $source , int $property , mixed $setting
)
Parameters
source
An Open AL(Source) resource (previously created by
openal_source_create()).
property
Property to set, one of: AL_BUFFER (OpenAL(Source)), AL_LOOPING
(bool), AL_SOURCE_RELATIVE (int), AL_SOURCE_STATE (int), AL_PITCH
(float), AL_GAIN (float), AL_MIN_GAIN (float), AL_MAX_GAIN
(float), AL_MAX_DISTANCE (float), AL_ROLLOFF_FACTOR (float),
AL_CONE_OUTER_GAIN (float), AL_CONE_INNER_ANGLE (float),
AL_CONE_OUTER_ANGLE (float), AL_REFERENCE_DISTANCE (float),
AL_POSITION (array(float,float,float)), AL_VELOCITY
(array(float,float,float)), AL_DIRECTION
(array(float,float,float)).
setting
Value to assign to specified property. Refer to the description of
property for a description of the value(s) expected.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* openal_source_create() - Generate a source resource
* openal_source_get() - Retrieve an OpenAL source property
* openal_source_play() - Start playing the source
----------------------------------------------------------------------
----------------------------------------------------------------------
openal_source_stop
(PECL openal >= 0.1.0)
openal_source_stop - Stop playing the source
Description
bool openal_source_stop ( resource $source )
Parameters
source
An Open AL(Source) resource (previously created by
openal_source_create()).
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* openal_source_play() - Start playing the source
* openal_source_pause() - Pause the source
* openal_source_rewind() - Rewind the source
----------------------------------------------------------------------
----------------------------------------------------------------------
openal_stream
(PECL openal >= 0.1.0)
openal_stream - Begin streaming on a source
Description
resource openal_stream ( resource $source , int $format , int $rate )
Parameters
source
An Open AL(Source) resource (previously created by
openal_source_create()).
format
Format of data, one of: AL_FORMAT_MONO8, AL_FORMAT_MONO16,
AL_FORMAT_STEREO8 and AL_FORMAT_STEREO16
rate
Frequency of data to stream given in Hz.
Return Values
Returns a stream resource on success or FALSE on failure.
See Also
* openal_source_create() - Generate a source resource
* fwrite() - Binary-safe file write
----------------------------------------------------------------------
Table of Contents
* openal_buffer_create - Generate OpenAL buffer
* openal_buffer_data - Load a buffer with data
* openal_buffer_destroy - Destroys an OpenAL buffer
* openal_buffer_get - Retrieve an OpenAL buffer property
* openal_buffer_loadwav - Load a .wav file into a buffer
* openal_context_create - Create an audio processing context
* openal_context_current - Make the specified context current
* openal_context_destroy - Destroys a context
* openal_context_process - Process the specified context
* openal_context_suspend - Suspend the specified context
* openal_device_close - Close an OpenAL device
* openal_device_open - Initialize the OpenAL audio layer
* openal_listener_get - Retrieve a listener property
* openal_listener_set - Set a listener property
* openal_source_create - Generate a source resource
* openal_source_destroy - Destroy a source resource
* openal_source_get - Retrieve an OpenAL source property
* openal_source_pause - Pause the source
* openal_source_play - Start playing the source
* openal_source_rewind - Rewind the source
* openal_source_set - Set source property
* openal_source_stop - Stop playing the source
* openal_stream - Begin streaming on a source
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* OpenAL Functions
* openal_buffer_create - Generate OpenAL buffer
* openal_buffer_data - Load a buffer with data
* openal_buffer_destroy - Destroys an OpenAL buffer
* openal_buffer_get - Retrieve an OpenAL buffer property
* openal_buffer_loadwav - Load a .wav file into a buffer
* openal_context_create - Create an audio processing context
* openal_context_current - Make the specified context current
* openal_context_destroy - Destroys a context
* openal_context_process - Process the specified context
* openal_context_suspend - Suspend the specified context
* openal_device_close - Close an OpenAL device
* openal_device_open - Initialize the OpenAL audio layer
* openal_listener_get - Retrieve a listener property
* openal_listener_set - Set a listener property
* openal_source_create - Generate a source resource
* openal_source_destroy - Destroy a source resource
* openal_source_get - Retrieve an OpenAL source property
* openal_source_pause - Pause the source
* openal_source_play - Start playing the source
* openal_source_rewind - Rewind the source
* openal_source_set - Set source property
* openal_source_stop - Stop playing the source
* openal_stream - Begin streaming on a source
----------------------------------------------------------------------
* ID3 - ID3 Tags
* Introduction
* Installing/Configuring
* Predefined Constants
* ID3 Functions
* KTaglib
* Introduction
* Installing/Configuring
* Predefined Constants
* KTaglib_MPEG_File - The KTagLib_MPEG_File class
* KTaglib_MPEG_AudioProperties - The KTaglib_MPEG_AudioProperties
class
* KTaglib_Tag - The KTaglib_Tag class
* KTaglib_ID3v2_Tag - The KTagLib_ID3v2_Tag class
* KTaglib_ID3v2_Frame - The KTagLib_ID3v2_Frame class
* KTaglib_ID3v2_AttachedPictureFrame - The
KTaglib_ID3v2_AttachedPictureFrame class
* oggvorbis - OGG/Vorbis
* Introduction
* Installing/Configuring
* Predefined Constants
* Context options
* Examples
* OpenAL - OpenAL Audio Bindings
* Introduction
* Installing/Configuring
* Predefined Constants
* OpenAL Functions
----------------------------------------------------------------------
----------------------------------------------------------------------
Authentication Services
----------------------------------------------------------------------
Kerberos V
----------------------------------------------------------------------
Introduction
These package allows you to access Kerberos V administration servers. You
can create, modify, and delete Kerberos V principals and policies.
More information about Kerberos can be found at
>> http://web.mit.edu/kerberos/www/.
Documentation for Kerberos and KADM5 can be found at
>> http://web.mit.edu/kerberos/www/krb5-1.2/krb5-1.2.8/doc/admin_toc.html.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here: >> http://pecl.php.net/package/kadm5.
Note:
If this option is used without specifying the path to KADM5, PHP will
use the built-in KADM5 client libraries. Users who run other
applications that use KADM5 (for example, running PHP 4 and PHP 5 as
concurrent apache modules, or auth-kadm5) should always specify the path
to KADM5: --with-kadm5=/path/to/kadm5. This will force PHP to use the
client libraries installed by KADM5, avoiding any conflicts.
A DLL for this PECL extension is currently unavailable. See also the
building on Windows section.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension defines a KADM5 handle returned by
kadm5_init_with_password().
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
Table of Contents
* Constants for Attribute Flags
* Constants for Options
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
----------------------------------------------------------------------
Constants for Attribute Flags
The functions kadm5_create_principal(), kadm5_modify_principal(), and
kadm5_modify_principal() allow to specify special attributes using a
bitfield. The symbols are defined below:
Attributes for use by the KDC
constant
KRB5_KDB_DISALLOW_POSTDATED
KRB5_KDB_DISALLOW_FORWARDABLE
KRB5_KDB_DISALLOW_TGT_BASED
KRB5_KDB_DISALLOW_RENEWABLE
KRB5_KDB_DISALLOW_PROXIABLE
KRB5_KDB_DISALLOW_DUP_SKEY
KRB5_KDB_DISALLOW_ALL_TIX
KRB5_KDB_REQUIRES_PRE_AUTH
KRB5_KDB_REQUIRES_HW_AUTH
KRB5_KDB_REQUIRES_PWCHANGE
KRB5_KDB_DISALLOW_SVR
KRB5_KDB_PWCHANGE_SERVER
KRB5_KDB_SUPPORT_DESMD5
KRB5_KDB_NEW_PRINC
----------------------------------------------------------------------
----------------------------------------------------------------------
Constants for Options
The functions kadm5_create_principal(), kadm5_modify_principal(), and
kadm5_get_principal() allow to specify or return principal's options as an
associative array. The keys for the associative array are defined as
string constants below:
Options for creating/modifying/retrieving principals
constant funcdef description
KADM5_PRINCIPAL long The expire time of the princial as a
Kerberos timestamp.
KADM5_PRINC_EXPIRE_TIME long The expire time of the princial as a
Kerberos timestamp.
KADM5_LAST_PW_CHANGE long The time this principal's password was
last changed.
KADM5_PW_EXPIRATION long The expire time of the principal's current
password, as a Kerberos timestamp.
KADM5_MAX_LIFE long The maximum lifetime of any Kerberos
ticket issued to this principal.
The maximum renewable lifetime of any
KADM5_MAX_RLIFE long Kerberos ticket issued to or for this
principal.
KADM5_MOD_NAME string The name of the Kerberos principal that
most recently modified this principal.
KADM5_MOD_TIME long The time this principal was last modified,
as a Kerberos timestamp.
KADM5_KVNO long The version of the principal's current
key.
KADM5_POLICY string The name of the policy controlling this
principal.
Standard procedure is to assign the
KADM5_CLEARPOLICY long 'default' policy to new principals.
KADM5_CLEARPOLICY suppresses this
behaviour.
KADM5_LAST_SUCCESS long The KDC time of the last successfull
AS_REQ.
KADM5_LAST_FAILED long The KDC time of the last failed AS_REQ.
KADM5_FAIL_AUTH_COUNT long The number of consecutive failed AS_REQs.
Generates a random password for the
KADM5_RANDKEY long principal. The parameter password will be
ignored.
KADM5_ATTRIBUTES long A bitfield of attributes for use by the
KDC.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Table of Contents
* Basic usage
----------------------------------------------------------------------
Basic usage
This simple example shows how to connect, query, print resulting
principals and disconnect from a KADM5 database.
Example #1 KADM5 extension overview example
get_principals\n";
$principals = kadm5_get_principals($handle);
for( $i=0; $i\n";
print "get_policies \n";
$policies = kadm5_get_policies($handle);
for( $i=0; $i\n";
print "get_principal burbach@GONICUS.LOCAL \n";
$options = kadm5_get_principal($handle, "burbach@GONICUS.LOCAL" );
$keys = array_keys($options);
for( $i=0; $i\n";
}
$options = array(KADM5_PRINC_EXPIRE_TIME => 0);
kadm5_modify_principal($handle, "burbach@GONICUS.LOCAL", $options);
kadm5_destroy($handle);
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
KADM5 Functions
----------------------------------------------------------------------
kadm5_chpass_principal
(PECL kadm5 >= 0.2.3)
kadm5_chpass_principal - Changes the principal's password
Description
bool kadm5_chpass_principal ( resource $handle , string $principal ,
string $password )
kadm5_chpass_principal() sets the new password password for the principal.
Parameters
handle
A KADM5 handle.
principal
The principal.
password
The new password.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Example of changing principal's password
----------------------------------------------------------------------
----------------------------------------------------------------------
kadm5_create_principal
(PECL kadm5 >= 0.2.3)
kadm5_create_principal - Creates a kerberos principal with the given
parameters
Description
bool kadm5_create_principal ( resource $handle , string $principal [,
string $password [, array $options ]] )
Creates a principal with the given password.
Parameters
handle
A KADM5 handle.
principal
The principal.
password
If password is omitted or is NULL, a random key will be generated.
options
It is possible to specify several optional parameters within the
array options. Allowed are the following options:
KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES,
KADM5_MAX_LIFE, KADM5_KVNO, KADM5_POLICY, KADM5_CLEARPOLICY,
KADM5_MAX_RLIFE.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Example of principal's creation
0,
KADM5_POLICY => "default",
KADM5_ATTRIBUTES => $attributes);
kadm5_create_principal($handle, "burbach@GONICUS.LOCAL", "password", $options);
kadm5_destroy($handle);
?>
See Also
* kadm5_modify_principal() - Modifies a kerberos principal with the
given parameters
* kadm5_delete_principal() - Deletes a kerberos principal
----------------------------------------------------------------------
----------------------------------------------------------------------
kadm5_delete_principal
(PECL kadm5 >= 0.2.3)
kadm5_delete_principal - Deletes a kerberos principal
Description
bool kadm5_delete_principal ( resource $handle , string $principal )
Removes the principal from the Kerberos database.
Parameters
handle
A KADM5 handle.
principal
The removed principal.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 kadm5_delete_principal() example
See Also
* kadm5_modify_principal() - Modifies a kerberos principal with the
given parameters
* kadm5_create_principal() - Creates a kerberos principal with the given
parameters
----------------------------------------------------------------------
----------------------------------------------------------------------
kadm5_destroy
(PECL kadm5 >= 0.2.3)
kadm5_destroy - Closes the connection to the admin server and releases all
related resources
Description
bool kadm5_destroy ( resource $handle )
Closes the connection to the admin server and releases all related
resources.
Parameters
handle
A KADM5 handle.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* kadm5_init_with_password() - Opens a connection to the KADM5 library
----------------------------------------------------------------------
----------------------------------------------------------------------
kadm5_flush
(PECL kadm5 >= 0.2.3)
kadm5_flush - Flush all changes to the Kerberos database
Description
bool kadm5_flush ( resource $handle )
Flush all changes to the Kerberos database, leaving the connection to the
Kerberos admin server open.
Parameters
handle
A KADM5 handle.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
kadm5_get_policies
(PECL kadm5 >= 0.2.3)
kadm5_get_policies - Gets all policies from the Kerberos database
Description
array kadm5_get_policies ( resource $handle )
Gets an array containing the policies's names.
Parameters
handle
A KADM5 handle.
Return Values
Returns array of policies on success or FALSE on failure.
Examples
Example #1 kadm5_get_policies() example
get_policies\n";
foreach (kadm5_get_policies($handle) as $policy) {
echo "$policy \n";
}
kadm5_destroy($handle);
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
kadm5_get_principal
(PECL kadm5 >= 0.2.3)
kadm5_get_principal - Gets the principal's entries from the Kerberos
database
Description
array kadm5_get_principal ( resource $handle , string $principal )
Gets the principal's entries from the Kerberos database.
Parameters
handle
A KADM5 handle.
principal
The principal.
Return Values
Returns array of options containing the following keys: KADM5_PRINCIPAL,
KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES,
KADM5_MAX_LIFE, KADM5_MOD_NAME, KADM5_MOD_TIME, KADM5_KVNO, KADM5_POLICY,
KADM5_MAX_RLIFE, KADM5_LAST_SUCCESS, KADM5_LAST_FAILED,
KADM5_FAIL_AUTH_COUNT on success or FALSE on failure.
Examples
Example #1 kadm5_get_principal() example
get_principal burbach@GONICUS.LOCAL\n";
$options = kadm5_get_principal($handle, "burbach@GONICUS.LOCAL" );
foreach ($options as $key => $value) {
echo "$key: $value \n";
}
kadm5_destroy($handle);
?>
See Also
* kadm5_get_principals() - Gets all principals from the Kerberos
database
----------------------------------------------------------------------
----------------------------------------------------------------------
kadm5_get_principals
(PECL kadm5 >= 0.2.3)
kadm5_get_principals - Gets all principals from the Kerberos database
Description
array kadm5_get_principals ( resource $handle )
kadm5_get_principals() returns an array containing the principals's names.
Parameters
handle
A KADM5 handle.
Return Values
Returns array of principals on success or FALSE on failure.
Examples
Example #1 kadm5_get_principals() example
get_principals\n";
foreach (kadm5_get_principals($handle) as $principal) {
echo "$principal \n";
}
kadm5_destroy($handle);
?>
See Also
* kadm5_get_principal() - Gets the principal's entries from the Kerberos
database
----------------------------------------------------------------------
----------------------------------------------------------------------
kadm5_init_with_password
(PECL kadm5 >= 0.2.3)
kadm5_init_with_password - Opens a connection to the KADM5 library
Description
resource kadm5_init_with_password ( string $admin_server , string $realm ,
string $principal , string $password )
Opens a connection with the KADM5 library using the principal and the
given password to obtain initial credentials from the admin_server.
Parameters
admin_server
The server.
realm
Defines the authentication domain for the connection.
principal
The principal.
password
If password is omitted or is NULL, a random key will be generated.
Return Values
Returns a KADM5 handle on success or FALSE on failure.
Examples
Example #1 KADM5 initialization example
0,
KADM5_POLICY => "default",
KADM5_ATTRIBUTES => $attributes);
kadm5_create_principal($handle, "burbach@GONICUS.LOCAL", "password", $options);
kadm5_destroy($handle);
?>
Notes
Note:
Connection should be closed after use with kadm5_destroy().
See Also
* kadm5_destroy() - Closes the connection to the admin server and
releases all related resources
----------------------------------------------------------------------
----------------------------------------------------------------------
kadm5_modify_principal
(PECL kadm5 >= 0.2.3)
kadm5_modify_principal - Modifies a kerberos principal with the given
parameters
Description
bool kadm5_modify_principal ( resource $handle , string $principal , array
$options )
Modifies a principal according to the given options.
Parameters
handle
A KADM5 handle.
principal
The principal.
options
It is possible to specify several optional parameters within the
array options. Allowed are the following options:
KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES,
KADM5_MAX_LIFE, KADM5_KVNO, KADM5_POLICY, KADM5_CLEARPOLICY,
KADM5_MAX_RLIFE. KADM5_FAIL_AUTH_COUNT.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Example of modifying principal
3451234,
KADM5_POLICY => "gonicus",
KADM5_ATTRIBUTES => $attributes);
kadm5_modify_principal($handle, "burbach@GONICUS.LOCAL", $options);
kadm5_destroy($handle);
?>
See Also
* kadm5_create_principal() - Creates a kerberos principal with the given
parameters
* kadm5_delete_principal() - Deletes a kerberos principal
----------------------------------------------------------------------
Table of Contents
* kadm5_chpass_principal - Changes the principal's password
* kadm5_create_principal - Creates a kerberos principal with the given
parameters
* kadm5_delete_principal - Deletes a kerberos principal
* kadm5_destroy - Closes the connection to the admin server and releases
all related resources
* kadm5_flush - Flush all changes to the Kerberos database
* kadm5_get_policies - Gets all policies from the Kerberos database
* kadm5_get_principal - Gets the principal's entries from the Kerberos
database
* kadm5_get_principals - Gets all principals from the Kerberos database
* kadm5_init_with_password - Opens a connection to the KADM5 library
* kadm5_modify_principal - Modifies a kerberos principal with the given
parameters
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Constants for Attribute Flags
* Constants for Options
* Examples
* Basic usage
* KADM5 Functions
* kadm5_chpass_principal - Changes the principal's password
* kadm5_create_principal - Creates a kerberos principal with the
given parameters
* kadm5_delete_principal - Deletes a kerberos principal
* kadm5_destroy - Closes the connection to the admin server and
releases all related resources
* kadm5_flush - Flush all changes to the Kerberos database
* kadm5_get_policies - Gets all policies from the Kerberos database
* kadm5_get_principal - Gets the principal's entries from the
Kerberos database
* kadm5_get_principals - Gets all principals from the Kerberos
database
* kadm5_init_with_password - Opens a connection to the KADM5
library
* kadm5_modify_principal - Modifies a kerberos principal with the
given parameters
----------------------------------------------------------------------
----------------------------------------------------------------------
Radius
----------------------------------------------------------------------
Introduction
This package is based on the libradius (Remote Authentication Dial In User
Service) of FreeBSD. It allows clients to perform authentication and
accounting by means of network requests to remote servers.
This PECL extension adds full support for Radius Authentication (>> RFC
2865) and Radius Accounting (>> RFC 2866). This package is available for
Unix (tested on FreeBSD and Linux) and for Windows.
Note:
An exact description for libradius can be found >> here. A detailed
description of the configuration file can be found >> here.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
This >> PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here: >> http://pecl.php.net/package/radius.
A DLL for this PECL extension is currently unavailable. See also the
building on Windows section.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
RADIUS_ACCESS_REQUEST ()
Authentication Request
RADIUS_ACCESS_ACCEPT ()
Access accepted
RADIUS_ACCESS_REJECT ()
Access rejected
RADIUS_ACCOUNTING_REQUEST ()
Accounting request
RADIUS_ACCOUNTING_RESPONSE ()
Accounting response
RADIUS_ACCESS_CHALLENGE ()
Accsess challenge
RADIUS_USER_NAME (string)
Username
RADIUS_USER_PASSWORD (string)
Password
RADIUS_CHAP_PASSWORD (string)
Chap Password: chappass = md5(ident + plaintextpass + challenge)
RADIUS_NAS_IP_ADDRESS (string)
NAS IP-Adress
RADIUS_NAS_PORT (int)
NAS Port
RADIUS_SERVICE_TYPE (int)
Type of Service, one of:
* RADIUS_LOGIN
* RADIUS_FRAMED
* RADIUS_CALLBACK_LOGIN
* RADIUS_CALLBACK_FRAMED
* RADIUS_OUTBOUND
* RADIUS_ADMINISTRATIVE
* RADIUS_NAS_PROMPT
* RADIUS_AUTHENTICATE_ONLY
* RADIUS_CALLBACK_NAS_PROMPT
RADIUS_FRAMED_PROTOCOL (int)
Framed Protocol, one of:
* RADIUS_PPP
* RADIUS_SLIP
* RADIUS_ARAP
* RADIUS_GANDALF
* RADIUS_XYLOGICS
RADIUS_FRAMED_IP_ADDRESS (string)
IP-Address
RADIUS_FRAMED_IP_NETMASK (string)
Netmask
RADIUS_FRAMED_ROUTING (int)
Routing
RADIUS_FILTER_ID (string)
Filter ID
RADIUS_FRAMED_MTU (int)
MTU
RADIUS_FRAMED_COMPRESSION (int)
Compression, one of:
* RADIUS_COMP_NONE
* RADIUS_COMP_VJ
* RADIUS_COMP_IPXHDR
RADIUS_LOGIN_IP_HOST (string)
Login IP Host
RADIUS_LOGIN_SERVICE (int)
Login Service
RADIUS_LOGIN_TCP_PORT (int)
Login TCP Port
RADIUS_REPLY_MESSAGE (string)
Reply Message
RADIUS_CALLBACK_NUMBER (string)
Callback Number
RADIUS_CALLBACK_ID (string)
Callback ID
RADIUS_FRAMED_ROUTE (string)
Framed Route
RADIUS_FRAMED_IPX_NETWORK (string)
Framed IPX Network
RADIUS_STATE (string)
State
RADIUS_CLASS (int)
Class
RADIUS_VENDOR_SPECIFIC (int)
Vendor specific attribute
RADIUS_SESSION_TIMEOUT (int)
Session timeout
RADIUS_IDLE_TIMEOUT (int)
Idle timeout
RADIUS_TERMINATION_ACTION (int)
Termination action
RADIUS_CALLED_STATION_ID (int)
Called Station Id
RADIUS_CALLING_STATION_ID (string)
Calling Station Id
RADIUS_NAS_IDENTIFIER (int)
NAS ID
RADIUS_PROXY_STATE (int)
Proxy State
RADIUS_LOGIN_LAT_SERVICE (int)
Login LAT Service
RADIUS_LOGIN_LAT_NODE (int)
Login LAT Node
RADIUS_LOGIN_LAT_GROUP (int)
Login LAT Group
RADIUS_FRAMED_APPLETALK_LINK (int)
Framed Appletalk Link
RADIUS_FRAMED_APPLETALK_NETWORK (int)
Framed Appletalk Network
RADIUS_FRAMED_APPLETALK_ZONE (int)
Framed Appletalk Zone
RADIUS_CHAP_CHALLENGE (string)
Challenge
RADIUS_NAS_PORT_TYPE (int)
NAS port type, one of:
* RADIUS_ASYNC
* RADIUS_SYNC
* RADIUS_ISDN_SYNC
* RADIUS_ISDN_ASYNC_V120
* RADIUS_ISDN_ASYNC_V110
* RADIUS_VIRTUAL
* RADIUS_PIAFS
* RADIUS_HDLC_CLEAR_CHANNEL
* RADIUS_X_25
* RADIUS_X_75
* RADIUS_G_3_FAX
* RADIUS_SDSL
* RADIUS_ADSL_CAP
* RADIUS_ADSL_DMT
* RADIUS_IDSL
* RADIUS_ETHERNET
* RADIUS_XDSL
* RADIUS_CABLE
* RADIUS_WIRELESS_OTHER
* RADIUS_WIRELESS_IEEE_802_11
RADIUS_PORT_LIMIT (int)
Port Limit
RADIUS_LOGIN_LAT_PORT (int)
Login LAT Port
RADIUS_CONNECT_INFO (string)
Connect info
RADIUS_ACCT_STATUS_TYPE (int)
Accounting status type, one of:
* RADIUS_START
* RADIUS_STOP
* RADIUS_ACCOUNTING_ON
* RADIUS_ACCOUNTING_OFF
RADIUS_ACCT_DELAY_TIME (int)
Accounting delay time
RADIUS_ACCT_INPUT_OCTETS (int)
Accounting input bytes
RADIUS_ACCT_OUTPUT_OCTETS (int)
Accounting output bytes
RADIUS_ACCT_SESSION_ID (int)
Accounting session ID
RADIUS_ACCT_AUTHENTIC (int)
Accounting authentic, one of:
* RADIUS_AUTH_RADIUS
* RADIUS_AUTH_LOCAL
* RADIUS_AUTH_REMOTE
RADIUS_ACCT_SESSION_TIME (int)
Accounting session time
RADIUS_ACCT_INPUT_PACKETS (int)
Accounting input packets
RADIUS_ACCT_OUTPUT_PACKETS (int)
Accounting output packets
RADIUS_ACCT_TERMINATE_CAUSE (int)
Accounting terminate cause, one of:
* RADIUS_TERM_USER_REQUEST
* RADIUS_TERM_LOST_CARRIER
* RADIUS_TERM_LOST_SERVICE
* RADIUS_TERM_IDLE_TIMEOUT
* RADIUS_TERM_SESSION_TIMEOUT
* RADIUS_TERM_ADMIN_RESET
* RADIUS_TERM_ADMIN_REBOOT
* RADIUS_TERM_PORT_ERROR
* RADIUS_TERM_NAS_ERROR
* RADIUS_TERM_NAS_REQUEST
* RADIUS_TERM_NAS_REBOOT
* RADIUS_TERM_PORT_UNNEEDED
* RADIUS_TERM_PORT_PREEMPTED
* RADIUS_TERM_PORT_SUSPENDED
* RADIUS_TERM_SERVICE_UNAVAILABLE
* RADIUS_TERM_CALLBACK
* RADIUS_TERM_USER_ERROR
* RADIUS_TERM_HOST_REQUEST
RADIUS_ACCT_MULTI_SESSION_ID (string)
Accounting multi session ID
RADIUS_ACCT_LINK_COUNT (int)
Accounting link count
RADIUS_VENDOR_MICROSOFT (int)
Microsoft specific vendor attributes (>> RFC 2548), one of:
* RADIUS_MICROSOFT_MS_CHAP_RESPONSE
* RADIUS_MICROSOFT_MS_CHAP_ERROR
* RADIUS_MICROSOFT_MS_CHAP_PW_1
* RADIUS_MICROSOFT_MS_CHAP_PW_2
* RADIUS_MICROSOFT_MS_CHAP_LM_ENC_PW
* RADIUS_MICROSOFT_MS_CHAP_NT_ENC_PW
* RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_POLICY
* RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_TYPES
* RADIUS_MICROSOFT_MS_RAS_VENDOR
* RADIUS_MICROSOFT_MS_CHAP_DOMAIN
* RADIUS_MICROSOFT_MS_CHAP_CHALLENGE
* RADIUS_MICROSOFT_MS_CHAP_MPPE_KEYS
* RADIUS_MICROSOFT_MS_BAP_USAGE
* RADIUS_MICROSOFT_MS_LINK_UTILIZATION_THRESHOLD
* RADIUS_MICROSOFT_MS_LINK_DROP_TIME_LIMIT
* RADIUS_MICROSOFT_MS_MPPE_SEND_KEY
* RADIUS_MICROSOFT_MS_MPPE_RECV_KEY
* RADIUS_MICROSOFT_MS_RAS_VERSION
* RADIUS_MICROSOFT_MS_OLD_ARAP_PASSWORD
* RADIUS_MICROSOFT_MS_NEW_ARAP_PASSWORD
* RADIUS_MICROSOFT_MS_ARAP_PASSWORD_CHANGE_REASON
* RADIUS_MICROSOFT_MS_FILTER
* RADIUS_MICROSOFT_MS_ACCT_AUTH_TYPE
* RADIUS_MICROSOFT_MS_ACCT_EAP_TYPE
* RADIUS_MICROSOFT_MS_CHAP2_RESPONSE
* RADIUS_MICROSOFT_MS_CHAP2_SUCCESS
* RADIUS_MICROSOFT_MS_CHAP2_PW
* RADIUS_MICROSOFT_MS_PRIMARY_DNS_SERVER
* RADIUS_MICROSOFT_MS_SECONDARY_DNS_SERVER
* RADIUS_MICROSOFT_MS_PRIMARY_NBNS_SERVER
* RADIUS_MICROSOFT_MS_SECONDARY_NBNS_SERVER
* RADIUS_MICROSOFT_MS_ARAP_CHALLENGE
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Howto start?
* get a radius resource
* configure the library
* create the request
* put attributes
* send the request
* receive attributes
* close the radius resource (optional)
Take also a look at the examples in this package.
The package contains an example php script. This script demonstrates howto
authenticate with radius using PAP or CHAP (md5). If you authenticate with
Microsoft Radius servers then its not possible to use CHAP (md5). If you
would like to authenticate with Microsoft Servers you have to use
MS-CHAPv1 or MS-CHAPv2, but its more complicated, because you need md4,
sha1 and des to generate the right data. The enclosed examples demonstrate
all authentication-methods, including MS-CHAPv1 and MS-CHAPv2. To get the
MS-CHAP to work you need the mcrypt and the mhash extension, starting with
version 1.2 of the package, the mcrypt extension is no longer needed.
----------------------------------------------------------------------
----------------------------------------------------------------------
Radius Functions
Contact Information
If you have comments, bugfixes, enhancements or want to help to develop
this you can send me a mail at >> mbretter@php.net.
----------------------------------------------------------------------
radius_acct_open
(PECL radius >= 1.1.0)
radius_acct_open - Creates a Radius handle for accounting
Description
resource radius_acct_open ( void )
Return Values
Returns a handle on success, FALSE on error. This function only fails if
insufficient memory is available.
Examples
Example #1 radius_acct_open() example
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_add_server
(PECL radius >= 1.1.0)
radius_add_server - Adds a server
Description
bool radius_add_server ( resource $radius_handle , string $hostname , int
$port , string $secret , int $timeout , int $max_tries )
radius_add_server() may be called multiple times, and it may be used
together with radius_config(). At most 10 servers may be specified. When
multiple servers are given, they are tried in round-robin fashion until a
valid response is received, or until each server's max_tries limit has
been reached.
Parameters
radius_handle
hostname
The hostname parameter specifies the server host, either as a
fully qualified domain name or as a dotted-quad IP address in text
form.
port
The port specifies the UDP port to contact on the server. If port
is given as 0, the library looks up the radius/udp or radacct/udp
service in the network services database, and uses the port found
there. If no entry is found, the library uses the standard Radius
ports, 1812 for authentication and 1813 for accounting.
secret
The shared secret for the server host is passed to the secret
parameter. The Radius protocol ignores all but the leading 128
bytes of the shared secret.
timeout
The timeout for receiving replies from the server is passed to the
timeout parameter, in units of seconds.
max_tries
The maximum number of repeated requests to make before giving up
is passed into the max_tries.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 radius_add_server() example
";
exit;
}
?>
See Also
* radius_config() - Causes the library to read the given configuration
file
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_auth_open
(PECL radius >= 1.1.0)
radius_auth_open - Creates a Radius handle for authentication
Description
resource radius_auth_open ( void )
Return Values
Returns a handle on success, FALSE on error. This function only fails if
insufficient memory is available.
Examples
Example #1 radius_auth_open() example
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_close
(PECL radius >= 1.1.0)
radius_close - Frees all ressources
Description
bool radius_close ( resource $radius_handle )
It is not needed to call this function because php frees all resources at
the end of each request.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_config
(PECL radius >= 1.1.0)
radius_config - Causes the library to read the given configuration file
Description
bool radius_config ( resource $radius_handle , string $file )
Before issuing any Radius requests, the library must be made aware of the
servers it can contact. The easiest way to configure the library is to
call radius_config(). radius_config() causes the library to read a
configuration file whose format is described in >> radius.conf.
Parameters
radius_handle
file
The pathname of the configuration file is passed as the file
argument to radius_config(). The library can also be configured
programmatically by calls to radius_add_server().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* radius_add_server() - Adds a server
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_create_request
(PECL radius >= 1.1.0)
radius_create_request - Create accounting or authentication request
Description
bool radius_create_request ( resource $radius_handle , int $type )
A Radius request consists of a code specifying the kind of request, and
zero or more attributes which provide additional information. To begin
constructing a new request, call radius_create_request().
Note: Attention: You must call this function, before you can put any
attribute!
Parameters
radius_handle
type
Type is RADIUS_ACCESS_REQUEST or RADIUS_ACCOUNTING_REQUEST.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 radius_create_request() example
";
exit;
}
?>
See Also
* radius_send_request() - Sends the request and waites for a reply
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_cvt_addr
(PECL radius >= 1.1.0)
radius_cvt_addr - Converts raw data to IP-Address
Description
string radius_cvt_addr ( string $data )
Examples
Example #1 radius_cvt_addr() example
\n";
break;
case RADIUS_FRAMED_IP_NETMASK:
$mask = radius_cvt_addr($data);
echo "MASK: $mask \n";
break;
}
}
?>
See Also
* radius_cvt_int() - Converts raw data to integer
* radius_cvt_string() - Converts raw data to string
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_cvt_int
(PECL radius >= 1.1.0)
radius_cvt_int - Converts raw data to integer
Description
int radius_cvt_int ( string $data )
Examples
Example #1 radius_cvt_int() example
\n";
break;
}
}
?>
See Also
* radius_cvt_addr() - Converts raw data to IP-Address
* radius_cvt_string() - Converts raw data to string
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_cvt_string
(PECL radius >= 1.1.0)
radius_cvt_string - Converts raw data to string
Description
string radius_cvt_string ( string $data )
Examples
Example #1 radius_cvt_string() example
\n";
break;
}
}
?>
See Also
* radius_cvt_addr() - Converts raw data to IP-Address
* radius_cvt_int() - Converts raw data to integer
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_demangle_mppe_key
(PECL radius >= 1.2.0)
radius_demangle_mppe_key - Derives mppe-keys from mangled data
Description
string radius_demangle_mppe_key ( resource $radius_handle , string
$mangled )
When using MPPE with MS-CHAPv2, the send- and recv-keys are mangled (see
>> RFC 2548), however this function is useless, because I don't think that
there is or will be a PPTP-MPPE implementation in PHP.
Return Values
Returns the demangled string, or FALSE on error.
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_demangle
(PECL radius >= 1.2.0)
radius_demangle - Demangles data
Description
string radius_demangle ( resource $radius_handle , string $mangled )
Some data (Passwords, MS-CHAPv1 MPPE-Keys) is mangled for security
reasons, and must be demangled before you can use them.
Return Values
Returns the demangled string, or FALSE on error.
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_get_attr
(PECL radius >= 1.1.0)
radius_get_attr - Extracts an attribute
Description
mixed radius_get_attr ( resource $radius_handle )
Like Radius requests, each response may contain zero or more attributes.
After a response has been received successfully by radius_send_request(),
its attributes can be extracted one by one using radius_get_attr(). Each
time radius_get_attr() is called, it gets the next attribute from the
current response.
Return Values
Returns an associative array containing the attribute-type and the data,
or error number <= 0.
Examples
Example #1 radius_get_attr() example
See Also
* radius_put_attr() - Attaches a binary attribute
* radius_get_vendor_attr() - Extracts a vendor specific attribute
* radius_put_vendor_attr() - Attaches a vendor specific binary attribute
* radius_send_request() - Sends the request and waites for a reply
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_get_vendor_attr
(PECL radius >= 1.1.0)
radius_get_vendor_attr - Extracts a vendor specific attribute
Description
array radius_get_vendor_attr ( string $data )
If radius_get_attr() returns RADIUS_VENDOR_SPECIFIC,
radius_get_vendor_attr() may be called to determine the vendor.
Return Values
Returns an associative array containing the attribute-type, vendor and the
data, or FALSE on error.
Examples
Example #1 radius_get_vendor_attr() example
See Also
* radius_get_attr() - Extracts an attribute
* radius_put_vendor_attr() - Attaches a vendor specific binary attribute
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_put_addr
(PECL radius >= 1.1.0)
radius_put_addr - Attaches an IP-Address attribute
Description
bool radius_put_addr ( resource $radius_handle , int $type , string $addr
)
Warning
This function is currently not documented; only its argument list is
available.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_put_attr
(PECL radius >= 1.1.0)
radius_put_attr - Attaches a binary attribute
Description
bool radius_put_attr ( resource $radius_handle , int $type , string $value
)
Warning
This function is currently not documented; only its argument list is
available.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 radius_put_attr() example
";
exit;
}
?>
See Also
* radius_get_attr() - Extracts an attribute
* radius_get_vendor_attr() - Extracts a vendor specific attribute
* radius_put_vendor_attr() - Attaches a vendor specific binary attribute
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_put_int
(PECL radius >= 1.1.0)
radius_put_int - Attaches an integer attribute
Description
bool radius_put_int ( resource $radius_handle , int $type , int $value )
Warning
This function is currently not documented; only its argument list is
available.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 radius_put_int() example
";
exit;
}
?>
See Also
* radius_put_string() - Attaches a string attribute
* radius_put_vendor_int() - Attaches a vendor specific integer attribute
* radius_put_vendor_string() - Attaches a vendor specific string
attribute
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_put_string
(PECL radius >= 1.1.0)
radius_put_string - Attaches a string attribute
Description
bool radius_put_string ( resource $radius_handle , int $type , string
$value )
Warning
This function is currently not documented; only its argument list is
available.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 radius_put_string() example
";
exit;
}
?>
See Also
* radius_put_int() - Attaches an integer attribute
* radius_put_vendor_int() - Attaches a vendor specific integer attribute
* radius_put_vendor_string() - Attaches a vendor specific string
attribute
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_put_vendor_addr
(PECL radius >= 1.1.0)
radius_put_vendor_addr - Attaches a vendor specific IP-Address attribute
Description
bool radius_put_vendor_addr ( resource $radius_handle , int $vendor , int
$type , string $addr )
Warning
This function is currently not documented; only its argument list is
available.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_put_vendor_attr
(PECL radius >= 1.1.0)
radius_put_vendor_attr - Attaches a vendor specific binary attribute
Description
bool radius_put_vendor_attr ( resource $radius_handle , int $vendor , int
$type , string $value )
Warning
This function is currently not documented; only its argument list is
available.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 radius_put_vendor_attr() example
";
exit;
}
?>
See Also
* radius_get_vendor_attr() - Extracts a vendor specific attribute
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_put_vendor_int
(PECL radius >= 1.1.0)
radius_put_vendor_int - Attaches a vendor specific integer attribute
Description
bool radius_put_vendor_int ( resource $radius_handle , int $vendor , int
$type , int $value )
Warning
This function is currently not documented; only its argument list is
available.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* radius_put_vendor_string() - Attaches a vendor specific string
attribute
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_put_vendor_string
(PECL radius >= 1.1.0)
radius_put_vendor_string - Attaches a vendor specific string attribute
Description
bool radius_put_vendor_string ( resource $radius_handle , int $vendor ,
int $type , string $value )
Warning
This function is currently not documented; only its argument list is
available.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* radius_put_vendor_int() - Attaches a vendor specific integer attribute
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_request_authenticator
(PECL radius >= 1.1.0)
radius_request_authenticator - Returns the request authenticator
Description
string radius_request_authenticator ( resource $radius_handle )
The request authenticator is needed for demangling mangled data like
passwords and encryption-keys.
Return Values
Returns the request authenticator as string, or FALSE on error.
See Also
* radius_demangle() - Demangles data
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_send_request
(PECL radius >= 1.1.0)
radius_send_request - Sends the request and waites for a reply
Description
int radius_send_request ( resource $radius_handle )
After the Radius request has been constructed, it is sent by
radius_send_request().
The radius_send_request() function sends the request and waits for a valid
reply, retrying the defined servers in round-robin fashion as necessary.
Return Values
If a valid response is received, radius_send_request() returns the Radius
code which specifies the type of the response. This will typically be
RADIUS_ACCESS_ACCEPT, RADIUS_ACCESS_REJECT, or RADIUS_ACCESS_CHALLENGE. If
no valid response is received, radius_send_request() returns FALSE.
See Also
* radius_create_request() - Create accounting or authentication request
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_server_secret
(PECL radius >= 1.1.0)
radius_server_secret - Returns the shared secret
Description
string radius_server_secret ( resource $radius_handle )
The shared secret is needed as salt for demangling mangled data like
passwords and encryption-keys.
Return Values
Returns the server's shared secret as string, or FALSE on error.
----------------------------------------------------------------------
----------------------------------------------------------------------
radius_strerror
(PECL radius >= 1.1.0)
radius_strerror - Returns an error message
Description
string radius_strerror ( resource $radius_handle )
If Radius-functions fail then they record an error message. This error
message can be retrieved with this function.
Return Values
Returns error messages as string from failed radius functions.
----------------------------------------------------------------------
Table of Contents
* radius_acct_open - Creates a Radius handle for accounting
* radius_add_server - Adds a server
* radius_auth_open - Creates a Radius handle for authentication
* radius_close - Frees all ressources
* radius_config - Causes the library to read the given configuration
file
* radius_create_request - Create accounting or authentication request
* radius_cvt_addr - Converts raw data to IP-Address
* radius_cvt_int - Converts raw data to integer
* radius_cvt_string - Converts raw data to string
* radius_demangle_mppe_key - Derives mppe-keys from mangled data
* radius_demangle - Demangles data
* radius_get_attr - Extracts an attribute
* radius_get_vendor_attr - Extracts a vendor specific attribute
* radius_put_addr - Attaches an IP-Address attribute
* radius_put_attr - Attaches a binary attribute
* radius_put_int - Attaches an integer attribute
* radius_put_string - Attaches a string attribute
* radius_put_vendor_addr - Attaches a vendor specific IP-Address
attribute
* radius_put_vendor_attr - Attaches a vendor specific binary attribute
* radius_put_vendor_int - Attaches a vendor specific integer attribute
* radius_put_vendor_string - Attaches a vendor specific string attribute
* radius_request_authenticator - Returns the request authenticator
* radius_send_request - Sends the request and waites for a reply
* radius_server_secret - Returns the shared secret
* radius_strerror - Returns an error message
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* Radius Functions
* radius_acct_open - Creates a Radius handle for accounting
* radius_add_server - Adds a server
* radius_auth_open - Creates a Radius handle for authentication
* radius_close - Frees all ressources
* radius_config - Causes the library to read the given
configuration file
* radius_create_request - Create accounting or authentication
request
* radius_cvt_addr - Converts raw data to IP-Address
* radius_cvt_int - Converts raw data to integer
* radius_cvt_string - Converts raw data to string
* radius_demangle_mppe_key - Derives mppe-keys from mangled data
* radius_demangle - Demangles data
* radius_get_attr - Extracts an attribute
* radius_get_vendor_attr - Extracts a vendor specific attribute
* radius_put_addr - Attaches an IP-Address attribute
* radius_put_attr - Attaches a binary attribute
* radius_put_int - Attaches an integer attribute
* radius_put_string - Attaches a string attribute
* radius_put_vendor_addr - Attaches a vendor specific IP-Address
attribute
* radius_put_vendor_attr - Attaches a vendor specific binary
attribute
* radius_put_vendor_int - Attaches a vendor specific integer
attribute
* radius_put_vendor_string - Attaches a vendor specific string
attribute
* radius_request_authenticator - Returns the request authenticator
* radius_send_request - Sends the request and waites for a reply
* radius_server_secret - Returns the shared secret
* radius_strerror - Returns an error message
----------------------------------------------------------------------
* KADM5 - Kerberos V
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* KADM5 Functions
* Radius
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* Radius Functions
----------------------------------------------------------------------
----------------------------------------------------------------------
Date and Time Related Extensions
----------------------------------------------------------------------
Calendar
----------------------------------------------------------------------
Introduction
The calendar extension presents a series of functions to simplify
converting between different calendar formats. The intermediary or
standard it is based on is the Julian Day Count. The Julian Day Count is a
count of days starting from January 1st, 4713 B.C. To convert between
calendar systems, you must first convert to Julian Day Count, then to the
calendar system of your choice. Julian Day Count is very different from
the Julian Calendar! For more information on Julian Day Count, visit
>> http://www.hermetic.ch/cal_stud/jdn.htm. For more information on
calendar systems visit >> http://www.fourmilab.ch/documents/calendar/.
Excerpts from this page are included in these instructions, and are in
quotes.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
To get these functions to work, you have to compile PHP with
--enable-calendar .
The Windows version of PHP has built-in support for this extension. You do
not need to load any additional extensions in order to use these
functions.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
CAL_GREGORIAN (integer)
CAL_JULIAN (integer)
CAL_JEWISH (integer)
CAL_FRENCH (integer)
CAL_NUM_CALS (integer)
CAL_DOW_DAYNO (integer)
CAL_DOW_SHORT (integer)
CAL_DOW_LONG (integer)
CAL_MONTH_GREGORIAN_SHORT (integer)
CAL_MONTH_GREGORIAN_LONG (integer)
CAL_MONTH_JULIAN_SHORT (integer)
CAL_MONTH_JULIAN_LONG (integer)
CAL_MONTH_JEWISH (integer)
CAL_MONTH_FRENCH (integer)
The following constants are available since PHP 4.3.0 :
CAL_EASTER_DEFAULT (integer)
CAL_EASTER_ROMAN (integer)
CAL_EASTER_ALWAYS_GREGORIAN (integer)
CAL_EASTER_ALWAYS_JULIAN (integer)
The following constants are available since PHP 5.0.0 :
CAL_JEWISH_ADD_ALAFIM_GERESH (integer)
CAL_JEWISH_ADD_ALAFIM (integer)
CAL_JEWISH_ADD_GERESHAYIM (integer)
----------------------------------------------------------------------
----------------------------------------------------------------------
Calendar Functions
----------------------------------------------------------------------
cal_days_in_month
(PHP 4 >= 4.1.0, PHP 5)
cal_days_in_month - Return the number of days in a month for a given year
and calendar
Description
int cal_days_in_month ( int $calendar , int $month , int $year )
This function will return the number of days in the month of year for the
specified calendar.
Parameters
calendar
Calendar to use for calculation
month
Month in the selected calendar
year
Year in the selected calendar
Return Values
The length in days of the selected month in the given calendar
Examples
Example #1 cal_days_in_month() example
----------------------------------------------------------------------
----------------------------------------------------------------------
cal_from_jd
(PHP 4 >= 4.1.0, PHP 5)
cal_from_jd - Converts from Julian Day Count to a supported calendar
Description
array cal_from_jd ( int $jd , int $calendar )
cal_from_jd() converts the Julian day given in jd into a date of the
specified calendar. Supported calendar values are CAL_GREGORIAN,
CAL_JULIAN, CAL_JEWISH and CAL_FRENCH.
Parameters
jd
Julian day as integer
calendar
Calendar to convert to
Return Values
Returns an array containing calendar information like month, day, year,
day of week, abbreviated and full names of weekday and month and the date
in string form "month/day/year".
Examples
Example #1 cal_from_jd() example
The above example will output:
Array
(
[date] => 8/16/2003
[month] => 8
[day] => 16
[year] => 2003
[dow] => 6
[abbrevdayname] => Sat
[dayname] => Saturday
[abbrevmonth] => Aug
[monthname] => August
)
See Also
* cal_to_jd() - Converts from a supported calendar to Julian Day Count
* jdtofrench() - Converts a Julian Day Count to the French Republican
Calendar
* jdtogregorian() - Converts Julian Day Count to Gregorian date
* jdtojewish() - Converts a Julian day count to a Jewish calendar date
* jdtojulian() - Converts a Julian Day Count to a Julian Calendar Date
* jdtounix() - Convert Julian Day to Unix timestamp
----------------------------------------------------------------------
----------------------------------------------------------------------
cal_info
(PHP 4 >= 4.1.0, PHP 5)
cal_info - Returns information about a particular calendar
Description
array cal_info ([ int $calendar = -1 ] )
cal_info() returns information on the specified calendar.
Calendar information is returned as an array containing the elements
calname, calsymbol, month, abbrevmonth and maxdaysinmonth. The names of
the different calendars which can be used as calendar are as follows:
* 0 or CAL_GREGORIAN - Gregorian Calendar
* 1 or CAL_JULIAN - Julian Calendar
* 2 or CAL_JEWISH - Jewish Calendar
* 3 or CAL_FRENCH - French Revolutionary Calendar
If no calendar is specified information on all supported calendars is
returned as an array.
Parameters
calendar
Calendar to return information for. If no calendar is specified
information about all calendars is returned.
Return Values
Changelog
Version Description
5.0.0 The calendar parameter becomes optional and defaults to "all
calendars" if omitted.
Examples
Example #1 cal_info() example
The above example will output:
Array
(
[months] => Array
(
[1] => January
[2] => February
[3] => March
[4] => April
[5] => May
[6] => June
[7] => July
[8] => August
[9] => September
[10] => October
[11] => November
[12] => December
)
[abbrevmonths] => Array
(
[1] => Jan
[2] => Feb
[3] => Mar
[4] => Apr
[5] => May
[6] => Jun
[7] => Jul
[8] => Aug
[9] => Sep
[10] => Oct
[11] => Nov
[12] => Dec
)
[maxdaysinmonth] => 31
[calname] => Gregorian
[calsymbol] => CAL_GREGORIAN
)
----------------------------------------------------------------------
----------------------------------------------------------------------
cal_to_jd
(PHP 4 >= 4.1.0, PHP 5)
cal_to_jd - Converts from a supported calendar to Julian Day Count
Description
int cal_to_jd ( int $calendar , int $month , int $day , int $year )
cal_to_jd() calculates the Julian day count for a date in the specified
calendar. Supported calendars are CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH
and CAL_FRENCH.
Parameters
calendar
Calendar to convert from, one of CAL_GREGORIAN, CAL_JULIAN,
CAL_JEWISH or CAL_FRENCH.
month
The month as a number, the valid range depends on the calendar
day
The day as a number, the valid range depends on the calendar
year
The year as a number, the valid range depends on the calendar
Return Values
A Julian Day number.
See Also
* cal_from_jd() - Converts from Julian Day Count to a supported calendar
* frenchtojd() - Converts a date from the French Republican Calendar to
a Julian Day Count
* gregoriantojd() - Converts a Gregorian date to Julian Day Count
* jewishtojd() - Converts a date in the Jewish Calendar to Julian Day
Count
* juliantojd() - Converts a Julian Calendar date to Julian Day Count
* unixtojd() - Convert Unix timestamp to Julian Day
----------------------------------------------------------------------
----------------------------------------------------------------------
easter_date
(PHP 4, PHP 5)
easter_date - Get Unix timestamp for midnight on Easter of a given year
Description
int easter_date ([ int $year ] )
Returns the Unix timestamp corresponding to midnight on Easter of the
given year.
Warning
This function will generate a warning if the year is outside of the range
for Unix timestamps (i.e. before 1970 or after 2037).
The date of Easter Day was defined by the Council of Nicaea in AD325 as
the Sunday after the first full moon which falls on or after the Spring
Equinox. The Equinox is assumed to always fall on 21st March, so the
calculation reduces to determining the date of the full moon and the date
of the following Sunday. The algorithm used here was introduced around the
year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before
1753) a simple 19-year cycle is used to track the phases of the Moon.
Under the Gregorian Calendar (for years after 1753 - devised by Clavius
and Lilius, and introduced by Pope Gregory XIII in October 1582, and into
Britain and its then colonies in September 1752) two correction factors
are added to make the cycle more accurate.
Parameters
year
The year as a number between 1970 an 2037
Return Values
The easter date as a unix timestamp.
Changelog
Version Description
Since 4.3.0 The year parameter is optional and defaults to the current
year according to the local time if omitted.
Examples
Example #1 easter_date() example
See Also
* easter_days() - Get number of days after March 21 on which Easter
falls for a given year for calculating Easter before 1970 or after
2037
----------------------------------------------------------------------
----------------------------------------------------------------------
easter_days
(PHP 4, PHP 5)
easter_days - Get number of days after March 21 on which Easter falls for
a given year
Description
int easter_days ([ int $year [, int $method = CAL_EASTER_DEFAULT ]] )
Returns the number of days after March 21 on which Easter falls for a
given year. If no year is specified, the current year is assumed.
This function can be used instead of easter_date() to calculate Easter for
years which fall outside the range of Unix timestamps (i.e. before 1970 or
after 2037).
The date of Easter Day was defined by the Council of Nicaea in AD325 as
the Sunday after the first full moon which falls on or after the Spring
Equinox. The Equinox is assumed to always fall on 21st March, so the
calculation reduces to determining the date of the full moon and the date
of the following Sunday. The algorithm used here was introduced around the
year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before
1753) a simple 19-year cycle is used to track the phases of the Moon.
Under the Gregorian Calendar (for years after 1753 - devised by Clavius
and Lilius, and introduced by Pope Gregory XIII in October 1582, and into
Britain and its then colonies in September 1752) two correction factors
are added to make the cycle more accurate.
Parameters
year
The year as a positive number
method
Allows to calculate easter dates based on the Gregorian calendar
during the years 1582 - 1752 when set to CAL_EASTER_ROMAN. See the
calendar constants for more valid constants.
Return Values
The number of days after March 21st that the Easter Sunday is in the given
year.
Changelog
Version Description
Since 4.3.0 The year parameter is optional and defaults to the current
year according to the local time if omitted.
Since 4.3.0 The method parameter was introduced.
Examples
Example #1 easter_days() example
See Also
* easter_date() - Get Unix timestamp for midnight on Easter of a given
year
----------------------------------------------------------------------
----------------------------------------------------------------------
FrenchToJD
(PHP 4, PHP 5)
FrenchToJD - Converts a date from the French Republican Calendar to a
Julian Day Count
Description
int frenchtojd ( int $month , int $day , int $year )
Converts a date from the French Republican Calendar to a Julian Day Count.
These routines only convert dates in years 1 through 14 (Gregorian dates
22 September 1792 through 22 September 1806). This more than covers the
period when the calendar was in use.
Parameters
month
The month as a number from 1 (for Vendemiaire) to 13 (for the
period of 5-6 days at the end of each year)
day
The day as a number from 1 to 30
year
The year as a number between 1 and 14
Return Values
The julian day for the given french revolution date as an integer.
See Also
* jdtofrench() - Converts a Julian Day Count to the French Republican
Calendar
* cal_to_jd() - Converts from a supported calendar to Julian Day Count
----------------------------------------------------------------------
----------------------------------------------------------------------
GregorianToJD
(PHP 4, PHP 5)
GregorianToJD - Converts a Gregorian date to Julian Day Count
Description
int gregoriantojd ( int $month , int $day , int $year )
Valid Range for Gregorian Calendar 4714 B.C. to 9999 A.D.
Although this function can handle dates all the way back to 4714 B.C.,
such use may not be meaningful. The Gregorian calendar was not instituted
until October 15, 1582 (or October 5, 1582 in the Julian calendar). Some
countries did not accept it until much later. For example, Britain
converted in 1752, The USSR in 1918 and Greece in 1923. Most European
countries used the Julian calendar prior to the Gregorian.
Parameters
month
The month as a number from 1 (for January) to 12 (for December)
day
The day as a number from 1 to 31
year
The year as a number between -4714 and 9999
Return Values
The julian day for the given gregorian date as an integer.
Examples
Example #1 Calendar functions
See Also
* jdtogregorian() - Converts Julian Day Count to Gregorian date
* cal_to_jd() - Converts from a supported calendar to Julian Day Count
----------------------------------------------------------------------
----------------------------------------------------------------------
JDDayOfWeek
(PHP 4, PHP 5)
JDDayOfWeek - Returns the day of the week
Description
mixed jddayofweek ( int $julianday [, int $mode = CAL_DOW_DAYNO ] )
Returns the day of the week. Can return a string or an integer depending
on the mode.
Parameters
julianday
A julian day number as integer
mode
Calendar week modes
Mode Meaning
0 (Default) Return the day number as an int (0=Sunday, 1=Monday,
etc)
1 Returns string containing the day of week
(English-Gregorian)
2 Return a string containing the abbreviated day of week
(English-Gregorian)
Return Values
The gregorian weekday as either an integer or string.
----------------------------------------------------------------------
----------------------------------------------------------------------
JDMonthName
(PHP 4, PHP 5)
JDMonthName - Returns a month name
Description
string jdmonthname ( int $julianday , int $mode )
Returns a string containing a month name. mode tells this function which
calendar to convert the Julian Day Count to, and what type of month names
are to be returned.
Calendar modes
Mode Meaning Values
0 Gregorian - abbreviated Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep,
Oct, Nov, Dec
January, February, March, April, May, June,
1 Gregorian July, August, September, October, November,
December
2 Julian - abbreviated Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep,
Oct, Nov, Dec
January, February, March, April, May, June,
3 Julian July, August, September, October, November,
December
Tishri, Heshvan, Kislev, Tevet, Shevat,
4 Jewish AdarI, AdarII, Nisan, Iyyar, Sivan, Tammuz,
Av, Elul
Vendemiaire, Brumaire, Frimaire, Nivose,
5 French Republican Pluviose, Ventose, Germinal, Floreal,
Prairial, Messidor, Thermidor, Fructidor,
Extra
Parameters
jday
The Julian Day to operate on
calendar
The calendar to take the month name from
Return Values
The month name for the given Julian Day and calendar.
----------------------------------------------------------------------
----------------------------------------------------------------------
JDToFrench
(PHP 4, PHP 5)
JDToFrench - Converts a Julian Day Count to the French Republican Calendar
Description
string jdtofrench ( int $juliandaycount )
Converts a Julian Day Count to the French Republican Calendar.
Parameters
julianday
A julian day number as integer
Return Values
The french revolution date as a string in the form "month/day/year"
See Also
* frenchtojd() - Converts a date from the French Republican Calendar to
a Julian Day Count
* cal_from_jd() - Converts from Julian Day Count to a supported calendar
----------------------------------------------------------------------
----------------------------------------------------------------------
JDToGregorian
(PHP 4, PHP 5)
JDToGregorian - Converts Julian Day Count to Gregorian date
Description
string jdtogregorian ( int $julianday )
Converts Julian Day Count to a string containing the Gregorian date in the
format of "month/day/year".
Parameters
julianday
A julian day number as integer
Return Values
The gregorian date as a string in the form "month/day/year"
See Also
* gregoriantojd() - Converts a Gregorian date to Julian Day Count
* cal_from_jd() - Converts from Julian Day Count to a supported calendar
----------------------------------------------------------------------
----------------------------------------------------------------------
jdtojewish
(PHP 4, PHP 5)
jdtojewish - Converts a Julian day count to a Jewish calendar date
Description
string jdtojewish ( int $juliandaycount [, bool $hebrew = false [, int $fl
= 0 ]] )
Converts a Julian Day Count to the Jewish Calendar.
Parameters
julianday
A julian day number as integer
hebrew
If the hebrew parameter is set to TRUE, the fl parameter is used
for Hebrew, string based, output format.
fl
The available formats are: CAL_JEWISH_ADD_ALAFIM_GERESH,
CAL_JEWISH_ADD_ALAFIM, CAL_JEWISH_ADD_GERESHAYIM.
Return Values
The jewish date as a string in the form "month/day/year"
Changelog
Version Description
5.0.0 The fl parameter was added.
4.3.0 The hebrew parameter was added.
Examples
Example #1 jdtojewish() Example
See Also
* jewishtojd() - Converts a date in the Jewish Calendar to Julian Day
Count
* cal_from_jd() - Converts from Julian Day Count to a supported calendar
----------------------------------------------------------------------
----------------------------------------------------------------------
JDToJulian
(PHP 4, PHP 5)
JDToJulian - Converts a Julian Day Count to a Julian Calendar Date
Description
string jdtojulian ( int $julianday )
Converts Julian Day Count to a string containing the Julian Calendar Date
in the format of "month/day/year".
Parameters
julianday
A julian day number as integer
Return Values
The julian date as a string in the form "month/day/year"
See Also
* juliantojd() - Converts a Julian Calendar date to Julian Day Count
* cal_from_jd() - Converts from Julian Day Count to a supported calendar
----------------------------------------------------------------------
----------------------------------------------------------------------
jdtounix
(PHP 4, PHP 5)
jdtounix - Convert Julian Day to Unix timestamp
Description
int jdtounix ( int $jday )
This function will return a Unix timestamp corresponding to the Julian Day
given in jday or FALSE if jday is not inside the Unix epoch (Gregorian
years between 1970 and 2037 or 2440588 <= jday <= 2465342 ). The time
returned is localtime (and not GMT).
Parameters
jday
A julian day number between 2440588 and 2465342.
Return Values
The unix timestamp for the start of the given julian day.
See Also
* unixtojd() - Convert Unix timestamp to Julian Day
----------------------------------------------------------------------
----------------------------------------------------------------------
JewishToJD
(PHP 4, PHP 5)
JewishToJD - Converts a date in the Jewish Calendar to Julian Day Count
Description
int jewishtojd ( int $month , int $day , int $year )
Although this function can handle dates all the way back to the year 1
(3761 B.C.), such use may not be meaningful. The Jewish calendar has been
in use for several thousand years, but in the early days there was no
formula to determine the start of a month. A new month was started when
the new moon was first observed.
Parameters
month
The month as a number from 1 to 13
day
The day as a number from 1 to 30
year
The year as a number between 1 and 9999
Return Values
The julian day for the given jewish date as an integer.
See Also
* jdtojewish() - Converts a Julian day count to a Jewish calendar date
* cal_to_jd() - Converts from a supported calendar to Julian Day Count
----------------------------------------------------------------------
----------------------------------------------------------------------
JulianToJD
(PHP 4, PHP 5)
JulianToJD - Converts a Julian Calendar date to Julian Day Count
Description
int juliantojd ( int $month , int $day , int $year )
Valid Range for Julian Calendar 4713 B.C. to 9999 A.D.
Although this function can handle dates all the way back to 4713 B.C.,
such use may not be meaningful. The calendar was created in 46 B.C., but
the details did not stabilize until at least 8 A.D., and perhaps as late
at the 4th century. Also, the beginning of a year varied from one culture
to another - not all accepted January as the first month.
Caution
Remember, the current calendar system being used worldwide is the
Gregorian calendar. gregoriantojd() can be used to convert such dates to
their Julian Day count.
Parameters
month
The month as a number from 1 (for January) to 12 (for December)
day
The day as a number from 1 to 31
year
The year as a number between -4713 and 9999
Return Values
The julian day for the given julian date as an integer.
See Also
* jdtojulian() - Converts a Julian Day Count to a Julian Calendar Date
* cal_to_jd() - Converts from a supported calendar to Julian Day Count
----------------------------------------------------------------------
----------------------------------------------------------------------
unixtojd
(PHP 4, PHP 5)
unixtojd - Convert Unix timestamp to Julian Day
Description
int unixtojd ([ int $timestamp = time() ] )
Return the Julian Day for a Unix timestamp (seconds since 1.1.1970), or
for the current day if no timestamp is given.
Parameters
timestamp
A unix timestamp to convert.
Return Values
A julian day number as integer.
See Also
* jdtounix() - Convert Julian Day to Unix timestamp
----------------------------------------------------------------------
Table of Contents
* cal_days_in_month - Return the number of days in a month for a given
year and calendar
* cal_from_jd - Converts from Julian Day Count to a supported calendar
* cal_info - Returns information about a particular calendar
* cal_to_jd - Converts from a supported calendar to Julian Day Count
* easter_date - Get Unix timestamp for midnight on Easter of a given
year
* easter_days - Get number of days after March 21 on which Easter falls
for a given year
* FrenchToJD - Converts a date from the French Republican Calendar to a
Julian Day Count
* GregorianToJD - Converts a Gregorian date to Julian Day Count
* JDDayOfWeek - Returns the day of the week
* JDMonthName - Returns a month name
* JDToFrench - Converts a Julian Day Count to the French Republican
Calendar
* JDToGregorian - Converts Julian Day Count to Gregorian date
* jdtojewish - Converts a Julian day count to a Jewish calendar date
* JDToJulian - Converts a Julian Day Count to a Julian Calendar Date
* jdtounix - Convert Julian Day to Unix timestamp
* JewishToJD - Converts a date in the Jewish Calendar to Julian Day
Count
* JulianToJD - Converts a Julian Calendar date to Julian Day Count
* unixtojd - Convert Unix timestamp to Julian Day
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Calendar Functions
* cal_days_in_month - Return the number of days in a month for a
given year and calendar
* cal_from_jd - Converts from Julian Day Count to a supported
calendar
* cal_info - Returns information about a particular calendar
* cal_to_jd - Converts from a supported calendar to Julian Day
Count
* easter_date - Get Unix timestamp for midnight on Easter of a
given year
* easter_days - Get number of days after March 21 on which Easter
falls for a given year
* FrenchToJD - Converts a date from the French Republican Calendar
to a Julian Day Count
* GregorianToJD - Converts a Gregorian date to Julian Day Count
* JDDayOfWeek - Returns the day of the week
* JDMonthName - Returns a month name
* JDToFrench - Converts a Julian Day Count to the French Republican
Calendar
* JDToGregorian - Converts Julian Day Count to Gregorian date
* jdtojewish - Converts a Julian day count to a Jewish calendar
date
* JDToJulian - Converts a Julian Day Count to a Julian Calendar
Date
* jdtounix - Convert Julian Day to Unix timestamp
* JewishToJD - Converts a date in the Jewish Calendar to Julian Day
Count
* JulianToJD - Converts a Julian Calendar date to Julian Day Count
* unixtojd - Convert Unix timestamp to Julian Day
----------------------------------------------------------------------
----------------------------------------------------------------------
Date and Time
----------------------------------------------------------------------
Introduction
These functions allow you to get the date and time from the server where
your PHP scripts are running. You can use these functions to format the
date and time in many different ways.
The date and time information is internally stored as an 64-bit number so
all imaginable dates (including negative years) are supported. The range
is from about 292 billion years in the past to the same in the future.
Note: Please keep in mind that these functions are dependent on the
locale settings of your server. Make sure to take daylight saving time
(use e.g. $date = strtotime('+7 days', $date) and not $date +=
7*24*60*60) and leap years into consideration when working with these
functions.
Note: The timezones referenced in this section can be found in the List
of Supported Timezones.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
There is no installation needed to use these functions; they are part of
the PHP core.
Note: Getting the latest timezone database
The latest version of the timezone database can be installed via PECL's
>> timezonedb.
Note: Experimental DateTime support in PHP 5.1.x
Although the DateTime class (and related functions) are enabled by
default since PHP 5.2.0, it is possible to add experimental support into
PHP 5.1.x by using the following flag before configure/compile:
CFLAGS=-DEXPERIMENTAL_DATE_SUPPORT=1
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Date/Time Configuration Options
Name Default Changeable Changelog
date.default_latitude "31.7667" PHP_INI_ALL Available since PHP 5.0.0.
date.default_longitude "35.2333" PHP_INI_ALL Available since PHP 5.0.0.
date.sunrise_zenith "90.583333" PHP_INI_ALL Available since PHP 5.0.0.
date.sunset_zenith "90.583333" PHP_INI_ALL Available since PHP 5.0.0.
date.timezone "" PHP_INI_ALL Available since PHP 5.1.0.
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
date.default_latitude float
The default latitude.
date.default_longitude float
The default longitude.
date.sunrise_zenith float
The default sunrise zenith.
date.sunset_zenith float
The default sunset zenith.
date.timezone string
Prior to PHP 5.3.0, the default timezone used by all date/time
functions if the TZ environment variable isn't set; this is longer
the case as of 5.3.0. The precedence order is described in the
date_default_timezone_get() page. See List of Supported Timezones
for a list of supported timezones.
Note: The first four configuration options are currently only used by
date_sunrise() and date_sunset().
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The DATE_ constants are defined since PHP 5.1.1 and they offer standard
date representations, which can be used along with the date format
functions (like date()).
Following constants exists since PHP 5.1.2 and specify a format returned
by functions date_sunrise() and date_sunset().
SUNFUNCS_RET_TIMESTAMP (integer)
Timestamp
SUNFUNCS_RET_STRING (integer)
Hours:minutes (example: 08:02)
SUNFUNCS_RET_DOUBLE (integer)
Hours as floating point number (example 8.75)
----------------------------------------------------------------------
----------------------------------------------------------------------
The DateTime class
Introduction
Representation of date and time.
Class synopsis
DateTime {
/* Constants */
const string ATOM = Y-m-d\TH:i:sP ;
const string COOKIE = l, d-M-y H:i:s T ;
const string ISO8601 = Y-m-d\TH:i:sO ;
const string RFC822 = D, d M y H:i:s O ;
const string RFC850 = l, d-M-y H:i:s T ;
const string RFC1036 = D, d M y H:i:s O ;
const string RFC1123 = D, d M Y H:i:s O ;
const string RFC2822 = D, d M Y H:i:s O ;
const string RFC3339 = Y-m-d\TH:i:sP ;
const string RSS = D, d M Y H:i:s O ;
const string W3C = Y-m-d\TH:i:sP ;
/* Methods */
public __construct ([ string $time = "now" [, DateTimeZone $timezone =
NULL ]] )
public DateTime add ( DateInterval $interval )
public static DateTime createFromFormat ( string $format , string $time [,
DateTimeZone $timezone ] )
public DateInterval diff ( DateTime $datetime2 [, bool $absolute = false ]
)
public string format ( string $format )
public static array getLastErrors ( void )
public int getOffset ( void )
public int getTimestamp ( void )
public DateTimeZone getTimezone ( void )
public DateTime modify ( string $modify )
public static DateTime __set_state ( array $array )
public DateTime setDate ( int $year , int $month , int $day )
public DateTime setISODate ( int $year , int $week [, int $day = 1 ] )
public DateTime setTime ( int $hour , int $minute [, int $second = 0 ] )
public DateTime setTimestamp ( int $unixtimestamp )
public DateTime setTimezone ( DateTimeZone $timezone )
public DateTime sub ( DateInterval $interval )
public DateTime __wakeup ( void )
}
Predefined Constants
DateTime Node Types
DateTime::ATOM
DATE_ATOM
Atom (example: 2005-08-15T15:52:01+00:00)
DateTime::COOKIE
DATE_COOKIE
HTTP Cookies (example: Monday, 15-Aug-05 15:52:01 UTC)
DateTime::ISO8601
DATE_ISO8601
ISO-8601 (example: 2005-08-15T15:52:01+0000)
DateTime::RFC822
DATE_RFC822
RFC 822 (example: Mon, 15 Aug 05 15:52:01 +0000)
DateTime::RFC850
DATE_RFC850
RFC 850 (example: Monday, 15-Aug-05 15:52:01 UTC)
DateTime::RFC1036
DATE_RFC1036
RFC 1036 (example: Mon, 15 Aug 05 15:52:01 +0000)
DateTime::RFC1123
DATE_RFC1123
RFC 1123 (example: Mon, 15 Aug 2005 15:52:01 +0000)
DateTime::RFC2822
DATE_RFC2822
RFC 2822 (Mon, 15 Aug 2005 15:52:01 +0000)
DateTime::RFC3339
DATE_RFC3339
Same as DATE_ATOM (since PHP 5.1.3)
DateTime::RSS
DATE_RSS
RSS (Mon, 15 Aug 2005 15:52:01 +0000)
DateTime::W3C
DATE_W3C
World Wide Web Consortium (example: 2005-08-15T15:52:01+00:00)
----------------------------------------------------------------------
DateTime::add
date_add
(PHP 5 >= 5.3.0)
DateTime::add -- date_add - Adds an amount of days, months, years, hours,
minutes and seconds to a DateTime object
Description
Object oriented style
public DateTime DateTime::add ( DateInterval $interval )
Procedural style
DateTime date_add ( DateTime $object , DateInterval $interval )
Adds the specified DateInterval object to the specified DateTime object.
Parameters
object
Procedural style only: A DateTime object returned by
date_create(). The function modifies this object.
interval
A DateInterval object
Return Values
Returns the DateTime object for method chaining or FALSE on failure.
Examples
Example #1 DateTime::add() example
Object oriented style
add(new DateInterval('P10D'));
echo $date->format('Y-m-d') . "\n";
?>
Procedural style
The above examples will output:
2000-01-11
Example #2 Further DateTime::add() examples
add(new DateInterval('PT10H30S'));
echo $date->format('Y-m-d H:i:s') . "\n";
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P7Y5M4DT4H3M2S'));
echo $date->format('Y-m-d H:i:s') . "\n";
?>
The above example will output:
2000-01-01 10:00:30
2007-06-05 04:03:02
Example #3 Beware when adding months
add($interval);
echo $date->format('Y-m-d') . "\n";
$date->add($interval);
echo $date->format('Y-m-d') . "\n";
?>
The above example will output:
2001-01-31
2001-03-03
Notes
DateTime::modify() is an alternative when using PHP 5.2.
See Also
* DateTime::sub() - Subtracts an amount of days, months, years, hours,
minutes and seconds from a DateTime object
* DateTime::diff() - Returns the difference between two DateTime objects
* DateTime::modify() - Alters the timestamp
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTime::__construct
date_create
(PHP 5 >= 5.2.0)
DateTime::__construct -- date_create - Returns new DateTime object
Description
Object oriented style
public DateTime::__construct() ([ string $time = "now" [, DateTimeZone
$timezone = NULL ]] )
Procedural style
DateTime date_create ([ string $time = "now" [, DateTimeZone $timezone =
NULL ]] )
Returns new DateTime object.
Parameters
time
A date/time string. Valid formats are explained in Date and Time
Formats.
Enter NULL here to obtain the current time when using the
$timezone parameter.
timezone
A DateTimeZone object representing the desired time zone.
If $timezone is omitted, the current timezone will be used.
Note:
The $timezone parameter and the current timezone are ignored
when the $time parameter either is a UNIX timestamp (e.g.
@946684800) or specifies a timezone (e.g.
2010-01-28T15:00:00+02:00).
Return Values
Returns a new DateTime instance. Procedural style returns FALSE on
failure.
Errors/Exceptions
Emits Exception in case of an error.
Changelog
Version Description
5.3.0 If an invalid date is specified, then an exception is now thrown.
Previously an error was emitted.
Examples
Example #1 DateTime::__construct() example
Object oriented style
getMessage();
exit(1);
}
echo $date->format('Y-m-d');
?>
Procedural style
The above examples will output:
2000-01-01
Example #2 Intricacies of DateTime::__construct()
format('Y-m-d H:i:sP') . "\n";
// Specified date/time in the specified time zone.
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
// Current date/time in your computer's time zone.
$date = new DateTime();
echo $date->format('Y-m-d H:i:sP') . "\n";
// Current date/time in the specified time zone.
$date = new DateTime(null, new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
// Using a UNIX timestamp. Notice the result is in the UTC time zone.
$date = new DateTime('@946684800');
echo $date->format('Y-m-d H:i:sP') . "\n";
// Non-existent values roll over.
$date = new DateTime('2000-02-30');
echo $date->format('Y-m-d H:i:sP') . "\n";
?>
The above example will output something similar to:
2000-01-01 00:00:00-05:00
2000-01-01 00:00:00+12:00
2010-04-24 10:24:16-04:00
2010-04-25 02:24:16+12:00
2000-01-01 00:00:00+00:00
2000-03-01 00:00:00-05:00
See Also
* DateTime::createFromFormat() - Returns new DateTime object formatted
according to the specified format
* DateTimeZone::__construct() - Creates new DateTimeZone object
* date.timezone ini setting
* date_default_timezone_set() - Sets the default timezone used by all
date/time functions in a script
* DateTime::getLastErrors() - Returns the warnings and errors
* checkdate() - Validate a Gregorian date
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTime::createFromFormat
date_create_from_format
(PHP 5 >= 5.3.0)
DateTime::createFromFormat -- date_create_from_format - Returns new
DateTime object formatted according to the specified format
Description
Object oriented style
public static DateTime DateTime::createFromFormat ( string $format ,
string $time [, DateTimeZone $timezone ] )
Procedural style
DateTime date_create_from_format ( string $format , string $time [,
DateTimeZone $timezone ] )
Returns new DateTime object formatted according to the specified format.
Parameters
format
The format that the passed in string should be in. See the
formatting options below. In most cases, the same letters as for
the date() can be used.
The following characters are recognized in the format parameter
string
format Description Example parsable values
character
Day --- ---
Day of the month, 2
d and j digits with or 01 to 31 or 1 to 31
without leading
zeros
A textual Mon through Sun or Sunday
D and l representation of a through Saturday
day
English ordinal
suffix for the day
S of the month, 2 st, nd, rd or th.
characters. It's
ignored while
processing.
z The day of the year 0 through 365
(starting from 0)
Month --- ---
A textual
F and M representation of a January through December or Jan
month, such as through Dec
January or Sept
Numeric
representation of a
m and n month, with or 01 through 12 or 1 through 12
without leading
zeros
Year --- ---
A full numeric
Y representation of a Examples: 1999 or 2003
year, 4 digits
A two digit
y representation of a Examples: 99 or 03
year
Time --- ---
a and A Ante meridiem and am or pm
Post meridiem
12-hour format of an
g and h hour with or without 1 through 12 or 01 through 12
leading zero
24-hour format of an
G and H hour with or without 0 through 23 or 00 through 23
leading zeros
i Minutes with leading 00 to 59
zeros
s Seconds, with 00 through 59
leading zeros
u Microseconds (up to Example: 45, 654321
six digits)
Timezone --- ---
Timezone identifier,
or difference to UTC
in hours, or Examples: UTC, GMT,
e, O, P and T difference to UTC Atlantic/Azores or +0200 or
with colon between +02:00 or EST, MDT
hours and minutes,
or timezone
abbreviation
Full --- ---
Date/Time
Seconds since the
U Unix Epoch (January Example: 1292177455
1 1970 00:00:00 GMT)
Whitespace
and --- ---
Separators
(space) One space or one tab Example:
One of the following
# separation symbol: Example: /
;, :, /, ., ,, -, (
or )
;, :, /, ., The specified Example: -
,, -, ( or ) character.
Example: ^ (Be aware that for
UTF-8 characracters you might
? A random byte need more than one ?. In this
case, using * is probably what
you want instead)
Random bytes until Example: * in Y-*-d with the
* the next separator string 2009-aWord-08 will match
or digit aWord
Resets all fields
(year, month, day, Without !, all fields will be
! hour, minute, set to the current date and
second, fraction and time.
timzone information)
to the Unix Epoch
Resets all fields
(year, month, day, Y-m-d| will set the year, month
hour, minute, and day to the information
| second, fraction and found in the string to parse,
timzone information) and sets the hour, minute and
to the Unix Epoch if second to 0.
they have not been
parsed yet
If this format
specifier is
present, trailing Use DateTime::getLastErrors()
+ data in the string to find out whether trailing
will not cause an data was present.
error, but a warning
instead
Unrecognized characters in the format string will cause the
parsing to fail and an error message is appended to the returned
structure. You can query error messages with
DateTime::getLastErrors().
If format does not contain the character ! then portions of the
generated time which are not specified in format will be set to
the current system time.
If format contains the character !, then portions of the generated
time not provided in format, as well as values to the left-hand
side of the !, will be set to corresponding values from the Unix
epoch.
The Unix epoch is 1970-01-01 00:00:00 UTC.
time
String representing the time.
timezone
A DateTimeZone object representing the desired time zone.
Return Values
Returns a new DateTime instance or FALSE on failure.
Examples
Example #1 DateTime::createFromFormat() example
Object oriented style
format('Y-m-d');
?>
Procedural style
The above examples will output:
2009-02-15
Example #2 Intricacies of DateTime::createFromFormat()
format('Y-m-d H:i:s') . "\n";
$format = 'Y-m-d H:i:s';
$date = DateTime::createFromFormat($format, '2009-02-15 15:16:17');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";
$format = 'Y-m-!d H:i:s';
$date = DateTime::createFromFormat($format, '2009-02-15 15:16:17');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";
$format = '!d';
$date = DateTime::createFromFormat($format, '15');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";
?>
The above example will output something similar to:
Current time: 2010-04-23 10:29:35
Format: Y-m-d; 2009-02-15 10:29:35
Format: Y-m-d H:i:s; 2009-02-15 15:16:17
Format: Y-m-!d H:i:s; 1970-01-15 15:16:17
Format: !d; 1970-01-15 00:00:00
See Also
* DateTime::__construct() - Returns new DateTime object
* DateTime::getLastErrors() - Returns the warnings and errors
* checkdate() - Validate a Gregorian date
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTime::diff
date_diff
(PHP 5 >= 5.3.0)
DateTime::diff -- date_diff - Returns the difference between two DateTime
objects
Description
Object oriented style
public DateInterval DateTime::diff ( DateTime $datetime2 [, bool $absolute
= false ] )
Procedural style
DateInterval date_diff ( DateTime $datetime1 , DateTime $datetime2 [, bool
$absolute = false ] )
Returns the difference between two DateTime objects.
Parameters
datetime
The date to compare to.
absolute
Whether to return absolute difference.
Return Values
The DateInterval object representing the difference between the two dates
or FALSE on failure.
Examples
Example #1 DateTime::diff() example
Object oriented style
diff($datetime2);
echo $interval->format('%R%a days');
?>
Procedural style
format('%R%a days');
?>
The above examples will output:
+2 days
Example #2 DateTime object comparison
Note:
As of PHP 5.2.2, DateTime objects can be compared using comparison
operators.
$date2);
?>
The above example will output:
bool(false)
bool(true)
bool(false)
See Also
* DateInterval::format() - Formats the interval
* DateTime::add() - Adds an amount of days, months, years, hours,
minutes and seconds to a DateTime object
* DateTime::sub() - Subtracts an amount of days, months, years, hours,
minutes and seconds from a DateTime object
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTime::format
date_format
(PHP 5 >= 5.2.0)
DateTime::format -- date_format - Returns date formatted according to
given format
Description
Object oriented style
public string DateTime::format ( string $format )
Procedural style
string date_format ( DateTime $object , string $format )
Returns date formatted according to given format.
Parameters
object
Procedural style only: A DateTime object returned by date_create()
format
Format accepted by date().
Return Values
Returns the formatted date string on success or FALSE on failure.
Examples
Example #1 DateTime::format() example
Object oriented style
format('Y-m-d H:i:s');
?>
Procedural style
The above example will output:
2000-01-01 00:00:00
Notes
This method does not use locales. All output is in English.
See Also
* date() - Format a local time/date
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTime::getLastErrors
date_get_last_errors
(PHP 5 >= 5.3.0)
DateTime::getLastErrors -- date_get_last_errors - Returns the warnings and
errors
Description
Object oriented style
public static array DateTime::getLastErrors ( void )
Procedural style
array date_get_last_errors ( void )
Returns an array of warnings and errors found while parsing a date/time
string.
Parameters
This function has no parameters.
Return Values
Returns array containing info about warnings and errors.
Examples
Example #1 DateTime::getLastErrors() example
Object oriented style
getMessage();
}
?>
Procedural style
The above examples will output:
Array
(
[warning_count] => 1
[warnings] => Array
(
[6] => Double timezone specification
)
[error_count] => 1
[errors] => Array
(
[0] => The timezone could not be found in the database
)
)
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTime::getOffset
date_offset_get
(PHP 5 >= 5.2.0)
DateTime::getOffset -- date_offset_get - Returns the timezone offset
Description
Object oriented style
public int DateTime::getOffset ( void )
Procedural style
int date_offset_get ( DateTime $object )
Returns the timezone offset.
Parameters
object
Procedural style only: A DateTime object returned by date_create()
Return Values
Returns the timezone offset in seconds from UTC on success or FALSE on
failure.
Examples
Example #1 DateTime::getOffset() example
Object oriented style
getOffset() . "\n";
echo $summer->getOffset() . "\n";
?>
Procedural style
getOffset() . "\n";
echo $summer->getOffset() . "\n";
?>
The above examples will output:
-18000
-14400
Note: -18000 = -5 hours, -14400 = -4 hours.
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTime::getTimestamp
date_timestamp_get
(PHP 5 >= 5.3.0)
DateTime::getTimestamp -- date_timestamp_get - Gets the Unix timestamp
Description
Object oriented style
public int DateTime::getTimestamp ( void )
Procedural style
int date_timestamp_get ( DateTime $object )
Gets the Unix timestamp.
Parameters
This function has no parameters.
Return Values
Returns the Unix timestamp representing the date.
Examples
Example #1 DateTime::getTimestamp() example
Object oriented style
getTimestamp();
?>
Procedural style
The above examples will output something similar to:
1272509157
Notes
Using U as the parameter to DateTime::format() is an alternative when
using PHP 5.2.
See Also
* DateTime::setTimestamp() - Sets the date and time based on an Unix
timestamp
* DateTime::format() - Returns date formatted according to given format
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTime::getTimezone
date_timezone_get
(PHP 5 >= 5.2.0)
DateTime::getTimezone -- date_timezone_get - Return time zone relative to
given DateTime
Description
Object oriented style
public DateTimeZone DateTime::getTimezone ( void )
Procedural style
DateTimeZone date_timezone_get ( DateTime $object )
Return time zone relative to given DateTime.
Parameters
object
Procedural style only: A DateTime object returned by date_create()
Return Values
Returns a DateTimeZone object on success or FALSE on failure.
Examples
Example #1 DateTime::getTimezone() example
Object oriented style
getTimezone();
echo $tz->getName();
?>
Procedural style
The above examples will output:
Europe/London
See Also
* DateTime::setTimezone() - Sets the time zone for the DateTime object
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTime::modify
date_modify
(PHP 5 >= 5.2.0)
DateTime::modify -- date_modify - Alters the timestamp
Description
Object oriented style
public DateTime DateTime::modify ( string $modify )
Procedural style
DateTime date_modify ( DateTime $object , string $modify )
Alter the timestamp of a DateTime object by incrementing or decrementing
in a format accepted by strtotime().
Parameters
object
Procedural style only: A DateTime object returned by
date_create(). The function modifies this object.
modify
A date/time string. Valid formats are explained in Date and Time
Formats.
Return Values
Returns the DateTime object for method chaining or FALSE on failure.
Changelog
Version Description
5.3.6 Absolute date/time statements now take effect. Previously, only
relative parts were used.
5.3.0 Changed the return value on success from NULL to DateTime.
Examples
Example #1 DateTime::modify() example
Object oriented style
modify('+1 day');
echo $date->format('Y-m-d');
?>
Procedural style
The above examples will output:
2006-12-13
Example #2 Beware when adding or subtracting months
modify('+1 month');
echo $date->format('Y-m-d') . "\n";
$date->modify('+1 month');
echo $date->format('Y-m-d') . "\n";
?>
The above example will output:
2001-01-31
2001-03-03
See Also
* strtotime() - Parse about any English textual datetime description
into a Unix timestamp
* DateTime::add() - Adds an amount of days, months, years, hours,
minutes and seconds to a DateTime object
* DateTime::sub() - Subtracts an amount of days, months, years, hours,
minutes and seconds from a DateTime object
* DateTime::setDate() - Sets the date
* DateTime::setISODate() - Sets the ISO date
* DateTime::setTime() - Sets the time
* DateTime::setTimestamp() - Sets the date and time based on an Unix
timestamp
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTime::__set_state
(PHP 5 >= 5.2.0)
DateTime::__set_state - The __set_state handler
Description
public static DateTime DateTime::__set_state ( array $array )
The __set_state handler.
Parameters
array
Initialization array.
Return Values
Returns a new instance of a DateTime object.
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTime::setDate
date_date_set
(PHP 5 >= 5.2.0)
DateTime::setDate -- date_date_set - Sets the date
Description
Object oriented style
public DateTime DateTime::setDate ( int $year , int $month , int $day )
Procedural style
DateTime date_date_set ( DateTime $object , int $year , int $month , int
$day )
Resets the current date of the DateTime object to a different date.
Parameters
object
Procedural style only: A DateTime object returned by
date_create(). The function modifies this object.
year
Year of the date.
month
Month of the date.
day
Day of the date.
Return Values
Returns the DateTime object for method chaining or FALSE on failure.
Changelog
Version Description
5.3.0 Changed the return value on success from NULL to DateTime.
Examples
Example #1 DateTime::setDate() example
Object oriented style
setDate(2001, 2, 3);
echo $date->format('Y-m-d');
?>
Procedural style
The above examples will output:
2001-02-03
Example #2 Values exceeding ranges are added to their parent values
setDate(2001, 2, 28);
echo $date->format('Y-m-d') . "\n";
$date->setDate(2001, 2, 29);
echo $date->format('Y-m-d') . "\n";
$date->setDate(2001, 14, 3);
echo $date->format('Y-m-d') . "\n";
?>
The above example will output:
2001-02-28
2001-03-01
2002-02-03
See Also
* DateTime::setISODate() - Sets the ISO date
* DateTime::setTime() - Sets the time
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTime::setISODate
date_isodate_set
(PHP 5 >= 5.2.0)
DateTime::setISODate -- date_isodate_set - Sets the ISO date
Description
Object oriented style
public DateTime DateTime::setISODate ( int $year , int $week [, int $day =
1 ] )
Procedural style
DateTime date_isodate_set ( DateTime $object , int $year , int $week [,
int $day = 1 ] )
Set a date according to the ISO 8601 standard - using weeks and day
offsets rather than specific dates.
Parameters
object
Procedural style only: A DateTime object returned by
date_create(). The function modifies this object.
year
Year of the date.
week
Week of the date.
day
Offset from the first day of the week.
Return Values
Returns the DateTime object for method chaining or FALSE on failure.
Changelog
Version Description
5.3.0 Changed the return value on success from NULL to DateTime.
Examples
Example #1 DateTime::setISODate() example
Object oriented style
setISODate(2008, 2);
echo $date->format('Y-m-d') . "\n";
$date->setISODate(2008, 2, 7);
echo $date->format('Y-m-d') . "\n";
?>
Procedural style
The above examples will output:
2008-01-07
2008-01-13
Example #2 Values exceeding ranges are added to their parent values
setISODate(2008, 2, 7);
echo $date->format('Y-m-d') . "\n";
$date->setISODate(2008, 2, 8);
echo $date->format('Y-m-d') . "\n";
$date->setISODate(2008, 53, 7);
echo $date->format('Y-m-d') . "\n";
?>
The above example will output:
2008-01-13
2008-01-14
2009-01-04
Example #3 Finding the month a week is in
setISODate(2008, 14);
echo $date->format('n');
?>
The above examples will output:
3
See Also
* DateTime::setDate() - Sets the date
* DateTime::setTime() - Sets the time
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTime::setTime
date_time_set
(PHP 5 >= 5.2.0)
DateTime::setTime -- date_time_set - Sets the time
Description
Object oriented style
public DateTime DateTime::setTime ( int $hour , int $minute [, int $second
= 0 ] )
Procedural style
DateTime date_time_set ( DateTime $object , int $hour , int $minute [, int
$second = 0 ] )
Resets the current time of the DateTime object to a different time.
Parameters
object
Procedural style only: A DateTime object returned by
date_create(). The function modifies this object.
hour
Hour of the time.
minute
Minute of the time.
second
Second of the time.
Return Values
Returns the DateTime object for method chaining or FALSE on failure.
Changelog
Version Description
5.3.0 Changed the return value on success from NULL to DateTime.
Examples
Example #1 DateTime::setTime() example
Object oriented style
setTime(14, 55);
echo $date->format('Y-m-d H:i:s') . "\n";
$date->setTime(14, 55, 24);
echo $date->format('Y-m-d H:i:s') . "\n";
?>
Procedural style
The above examples will output something similar to:
2000-01-01 14:55:00
2000-01-01 14:55:24
Example #2 Values exceeding ranges are added to their parent values
setTime(14, 55, 24);
echo $date->format('Y-m-d H:i:s') . "\n";
$date->setTime(14, 55, 65);
echo $date->format('Y-m-d H:i:s') . "\n";
$date->setTime(14, 65, 24);
echo $date->format('Y-m-d H:i:s') . "\n";
$date->setTime(25, 55, 24);
echo $date->format('Y-m-d H:i:s') . "\n";
?>
The above example will output:
2001-01-01 14:55:24
2001-01-01 14:56:05
2001-01-01 15:05:24
2001-01-02 01:55:24
See Also
* DateTime::setDate() - Sets the date
* DateTime::setISODate() - Sets the ISO date
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTime::setTimestamp
date_timestamp_set
(PHP 5 >= 5.3.0)
DateTime::setTimestamp -- date_timestamp_set - Sets the date and time
based on an Unix timestamp
Description
Object oriented style
public DateTime DateTime::setTimestamp ( int $unixtimestamp )
Procedural style
DateTime date_timestamp_set ( DateTime $object , int $unixtimestamp )
Sets the date and time based on an Unix timestamp.
Parameters
object
Procedural style only: A DateTime object returned by
date_create(). The function modifies this object.
unixtimestamp
Unix timestamp representing the date.
Return Values
Returns the DateTime object for method chaining or FALSE on failure.
Examples
Example #1 DateTime::setTimestamp() example
Object oriented style
format('U = Y-m-d H:i:s') . "\n";
$date->setTimestamp(1171502725);
echo $date->format('U = Y-m-d H:i:s') . "\n";
?>
Procedural style
The above examples will output something similar to:
1272508903 = 2010-04-28 22:41:43
1171502725 = 2007-02-14 20:25:25
Notes
Using the Unix timestamp format to construct a new DateTime object is an
alternative when using PHP 5.2, as shown in the example below.
Example #2 DateTime::setTimestamp() alternative in PHP 5.2
format('U = Y-m-d H:i:s') . "\n";
?>
The above example will output something similar to:
1171502725 = 2007-02-14 20:25:25
See Also
* DateTime::getTimestamp() - Gets the Unix timestamp
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTime::setTimezone
date_timezone_set
(PHP 5 >= 5.2.0)
DateTime::setTimezone -- date_timezone_set - Sets the time zone for the
DateTime object
Description
Object oriented style
public DateTime DateTime::setTimezone ( DateTimeZone $timezone )
Procedural style
DateTime date_timezone_set ( DateTime $object , DateTimeZone $timezone )
Parameters
object
Procedural style only: A DateTime object returned by
date_create(). The function modifies this object.
timezone
A DateTimeZone object representing the desired time zone.
Return Values
Returns the DateTime object for method chaining or FALSE on failure.
Changelog
Version Description
5.3.0 Changed the return value on success from NULL to DateTime.
Examples
Example #1 DateTime::setTimeZone() example
Object oriented style
format('Y-m-d H:i:sP') . "\n";
$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP') . "\n";
?>
Procedural style
The above examples will output:
2000-01-01 00:00:00+12:00
2000-01-01 01:45:00+13:45
See Also
* DateTime::getTimezone() - Return time zone relative to given DateTime
* DateTimeZone::__construct() - Creates new DateTimeZone object
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTime::sub
date_sub
(PHP 5 >= 5.3.0)
DateTime::sub -- date_sub - Subtracts an amount of days, months, years,
hours, minutes and seconds from a DateTime object
Description
Object oriented style
public DateTime DateTime::sub ( DateInterval $interval )
Procedural style
DateTime date_sub ( DateTime $object , DateInterval $interval )
Subtracts the specified DateInterval object from the specified DateTime
object.
Parameters
object
Procedural style only: A DateTime object returned by
date_create(). The function modifies this object.
interval
A DateInterval object
Return Values
Returns the DateTime object for method chaining or FALSE on failure.
Examples
Example #1 DateTime::sub() example
Object oriented style
sub(new DateInterval('P10D'));
echo $date->format('Y-m-d') . "\n";
?>
Procedural style
The above examples will output:
2000-01-10
Example #2 Further DateTime::sub() examples
sub(new DateInterval('PT10H30S'));
echo $date->format('Y-m-d H:i:s') . "\n";
$date = new DateTime('2000-01-20');
$date->sub(new DateInterval('P7Y5M4DT4H3M2S'));
echo $date->format('Y-m-d H:i:s') . "\n";
?>
The above example will output:
2000-01-19 13:59:30
1992-08-15 19:56:58
Example #3 Beware when subtracting months
sub($interval);
echo $date->format('Y-m-d') . "\n";
$date->sub($interval);
echo $date->format('Y-m-d') . "\n";
?>
The above example will output:
2001-03-30
2001-03-02
Notes
DateTime::modify() is an alternative when using PHP 5.2.
See Also
* DateTime::add() - Adds an amount of days, months, years, hours,
minutes and seconds to a DateTime object
* DateTime::diff() - Returns the difference between two DateTime objects
* DateTime::modify() - Alters the timestamp
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTime::__wakeup
(PHP 5 >= 5.2.0)
DateTime::__wakeup - The __wakeup handler
Description
public DateTime DateTime::__wakeup ( void )
The __wakeup handler.
Parameters
This function has no parameters.
Return Values
Initializes a DateTime object.
----------------------------------------------------------------------
Table of Contents
* DateTime::add - Adds an amount of days, months, years, hours, minutes
and seconds to a DateTime object
* DateTime::__construct - Returns new DateTime object
* DateTime::createFromFormat - Returns new DateTime object formatted
according to the specified format
* DateTime::diff - Returns the difference between two DateTime objects
* DateTime::format - Returns date formatted according to given format
* DateTime::getLastErrors - Returns the warnings and errors
* DateTime::getOffset - Returns the timezone offset
* DateTime::getTimestamp - Gets the Unix timestamp
* DateTime::getTimezone - Return time zone relative to given DateTime
* DateTime::modify - Alters the timestamp
* DateTime::__set_state - The __set_state handler
* DateTime::setDate - Sets the date
* DateTime::setISODate - Sets the ISO date
* DateTime::setTime - Sets the time
* DateTime::setTimestamp - Sets the date and time based on an Unix
timestamp
* DateTime::setTimezone - Sets the time zone for the DateTime object
* DateTime::sub - Subtracts an amount of days, months, years, hours,
minutes and seconds from a DateTime object
* DateTime::__wakeup - The __wakeup handler
----------------------------------------------------------------------
----------------------------------------------------------------------
The DateTimeZone class
Introduction
Representation of time zone.
Class synopsis
DateTimeZone {
/* Constants */
const integer AFRICA = 1 ;
const integer AMERICA = 2 ;
const integer ANTARCTICA = 4 ;
const integer ARCTIC = 8 ;
const integer ASIA = 16 ;
const integer ATLANTIC = 32 ;
const integer AUSTRALIA = 64 ;
const integer EUROPE = 128 ;
const integer INDIAN = 256 ;
const integer PACIFIC = 512 ;
const integer UTC = 1024 ;
const integer ALL = 2047 ;
const integer ALL_WITH_BC = 4095 ;
const integer PER_COUNTRY = 4096 ;
/* Methods */
public __construct ( string $timezone )
public array getLocation ( void )
public string getName ( void )
public int getOffset ( DateTime $datetime )
public array getTransitions ([ int $timestamp_begin [, int $timestamp_end
]] )
public static array listAbbreviations ( void )
public static array listIdentifiers ([ int $what = DateTimeZone::ALL [,
string $country = NULL ]] )
}
Predefined Constants
DateTimeZone Node Types
DateTimeZone::AFRICA
Africa time zones.
DateTimeZone::AMERICA
America time zones.
DateTimeZone::ANTARCTICA
Antarctica time zones.
DateTimeZone::ARCTIC
Arctic time zones.
DateTimeZone::ASIA
Asia time zones.
DateTimeZone::ATLANTIC
Atlantic time zones.
DateTimeZone::AUSTRALIA
Australia time zones.
DateTimeZone::EUROPE
Europe time zones.
DateTimeZone::INDIAN
Indian time zones.
DateTimeZone::PACIFIC
Pacific time zones.
DateTimeZone::UTC
UTC time zones.
DateTimeZone::ALL
All time zones.
DateTimeZone::ALL_WITH_BC
All time zones including backwards compatible.
DateTimeZone::PER_COUNTRY
Time zones per country.
----------------------------------------------------------------------
DateTimeZone::__construct
timezone_open
(PHP 5 >= 5.2.0)
DateTimeZone::__construct -- timezone_open - Creates new DateTimeZone
object
Description
Object oriented style
public DateTimeZone::__construct() ( string $timezone )
Procedural style
DateTimeZone timezone_open ( string $timezone )
Creates new DateTimeZone object.
Parameters
timezone
One of timezones.
Return Values
Returns DateTimeZone on success. Procedural style returns FALSE on
failure.
Errors/Exceptions
This method throws Exception if the timezone supplied is not recognised as
a valid timezone.
Examples
Example #1 Catching errors when instantiating DateTimeZone
getMessage() . ' ';
}
}
?>
The above example will output:
DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Mars/Phobos)
DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Jupiter/Europa)
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTimeZone::getLocation
timezone_location_get
(PHP 5 >= 5.3.0)
DateTimeZone::getLocation -- timezone_location_get - Returns location
information for a timezone
Description
Object oriented style
public array DateTimeZone::getLocation ( void )
Procedural style
array timezone_location_get ( DateTimeZone $object )
Returns location information for a timezone, including country code,
latitude/longitude and comments.
Parameters
object
Procedural style only: A DateTimeZone object returned by
timezone_open()
Return Values
Array containing location information about timezone.
Examples
Example #1 DateTimeZone::getLocation() example
getLocation());
print_r(timezone_location_get($tz));
?>
The above example will output:
Array
(
[country_code] => CZ
[latitude] => 50.08333
[longitude] => 14.43333
[comments] =>
)
Array
(
[country_code] => CZ
[latitude] => 50.08333
[longitude] => 14.43333
[comments] =>
)
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTimeZone::getName
timezone_name_get
(PHP 5 >= 5.2.0)
DateTimeZone::getName -- timezone_name_get - Returns the name of the
timezone
Description
Object oriented style
public string DateTimeZone::getName ( void )
Procedural style
string timezone_name_get ( DateTimeZone $object )
Returns the name of the timezone.
Parameters
object
The DateTimeZone for which to get a name.
Return Values
One of the timezone names in the list of timezones.
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTimeZone::getOffset
timezone_offset_get
(PHP 5 >= 5.2.0)
DateTimeZone::getOffset -- timezone_offset_get - Returns the timezone
offset from GMT
Description
Object oriented style
public int DateTimeZone::getOffset ( DateTime $datetime )
Procedural style
int timezone_offset_get ( DateTimeZone $object , DateTime $datetime )
This function returns the offset to GMT for the date/time specified in the
datetime parameter. The GMT offset is calculated with the timezone
information contained in the DateTimeZone object being used.
Parameters
object
Procedural style only: A DateTimeZone object returned by
timezone_open()
datetime
DateTime that contains the date/time to compute the offset from.
Return Values
Returns time zone offset in seconds on success or FALSE on failure.
Examples
Example #1 DateTimeZone::getOffset() examples
getOffset($dateTimeTaipei);
// Should show int(32400) (for dates after Sat Sep 8 01:00:00 1951 JST).
var_dump($timeOffset);
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTimeZone::getTransitions
timezone_transitions_get
(PHP 5 >= 5.2.0)
DateTimeZone::getTransitions -- timezone_transitions_get - Returns all
transitions for the timezone
Description
Object oriented style
public array DateTimeZone::getTransitions ([ int $timestamp_begin [, int
$timestamp_end ]] )
Procedural style
array timezone_transitions_get ( DateTimeZone $object [, int
$timestamp_begin [, int $timestamp_end ]] )
Parameters
object
Procedural style only: A DateTimeZone object returned by
timezone_open()
timestamp_begin
Begin timestamp.
timestamp_end
End timestamp.
Return Values
Returns numerically indexed array containing associative array with all
transitions on success or FALSE on failure.
Changelog
Version Description
5.3.0 The optional timestamp_begin and timestamp_end were added.
Examples
Example #1 A timezone_transitions_get() example
getTransitions();
print_r(array_slice($transitions, 0, 3));
?>
The above example will output something similar to:
Array
(
[0] => Array
(
[ts] => -9223372036854775808
[time] => -292277022657-01-27T08:29:52+0000
[offset] => 3600
[isdst] => 1
[abbr] => BST
)
[1] => Array
(
[ts] => -1691964000
[time] => 1916-05-21T02:00:00+0000
[offset] => 3600
[isdst] => 1
[abbr] => BST
)
[2] => Array
(
[ts] => -1680472800
[time] => 1916-10-01T02:00:00+0000
[offset] => 0
[isdst] =>
[abbr] => GMT
)
)
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTimeZone::listAbbreviations
timezone_abbreviations_list
(PHP 5 >= 5.2.0)
DateTimeZone::listAbbreviations -- timezone_abbreviations_list - Returns
associative array containing dst, offset and the timezone name
Description
Object oriented style
public static array DateTimeZone::listAbbreviations ( void )
Procedural style
array timezone_abbreviations_list ( void )
Return Values
Returns array on success or FALSE on failure.
Examples
Example #1 A timezone_abbreviations_list() example
The above example will output something similar to:
Array
(
[0] => Array
(
[dst] => 1
[offset] => -14400
[timezone_id] => America/Porto_Acre
)
[1] => Array
(
[dst] => 1
[offset] => -14400
[timezone_id] => America/Eirunepe
)
[2] => Array
(
[dst] => 1
[offset] => -14400
[timezone_id] => America/Rio_Branco
)
[3] => Array
(
[dst] => 1
[offset] => -14400
[timezone_id] => Brazil/Acre
)
)
See Also
* timezone_identifiers_list() - Alias of DateTimeZone::listIdentifiers
----------------------------------------------------------------------
----------------------------------------------------------------------
DateTimeZone::listIdentifiers
timezone_identifiers_list
(PHP 5 >= 5.2.0)
DateTimeZone::listIdentifiers -- timezone_identifiers_list - Returns
numerically index array with all timezone identifiers
Description
Object oriented style
public static array DateTimeZone::listIdentifiers ([ int $what =
DateTimeZone::ALL [, string $country = NULL ]] )
Procedural style
array timezone_identifiers_list ([ int $what = DateTimeZone::ALL [, string
$country = NULL ]] )
Parameters
what
One of DateTimeZone class constants.
country
A two-letter ISO 3166-1 compatible country code.
Note: This option is only used when what is set to
DateTimeZone::PER_COUNTRY.
Return Values
Returns array on success or FALSE on failure.
Changelog
Version Description
5.3.0 Added the optional what and country parameters.
Examples
Example #1 A timezone_identifiers_list() example
The above example will output something similar to:
Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara
See Also
* timezone_abbreviations_list() - Alias of
DateTimeZone::listAbbreviations
----------------------------------------------------------------------
Table of Contents
* DateTimeZone::__construct - Creates new DateTimeZone object
* DateTimeZone::getLocation - Returns location information for a
timezone
* DateTimeZone::getName - Returns the name of the timezone
* DateTimeZone::getOffset - Returns the timezone offset from GMT
* DateTimeZone::getTransitions - Returns all transitions for the
timezone
* DateTimeZone::listAbbreviations - Returns associative array containing
dst, offset and the timezone name
* DateTimeZone::listIdentifiers - Returns numerically index array with
all timezone identifiers
----------------------------------------------------------------------
----------------------------------------------------------------------
The DateInterval class
Introduction
Representation of date interval. A date interval stores either a fixed
amount of time (in years, months, days, hours etc) or a relative time
string in the format that DateTime's constructor supports.
Class synopsis
DateInterval {
/* Properties */
public integer $DateInterval->y ;
public integer $m ;
public integer $d ;
public integer $h ;
public integer $i ;
public integer $s ;
public integer $invert ;
public mixed $days ;
/* Methods */
public DateInterval::__construct ( string $interval_spec )
public static DateInterval DateInterval::createFromDateString ( string
$time )
public string DateInterval::format ( string $format )
}
Properties
y
Number of years.
m
Number of months.
d
Number of days.
h
Number of hours.
i
Number of minutes.
s
Number of seconds.
invert
Is 1 if the interval is inverted and 0 otherwise. See
DateInterval::format().
days
Total number of days the interval spans. If this is unknown, days
will be FALSE.
----------------------------------------------------------------------
DateInterval::__construct
(PHP 5 >= 5.3.0)
DateInterval::__construct - Creates new DateInterval object
Description
public DateInterval::__construct() ( string $interval_spec )
Creates new DateInterval object.
Parameters
interval_spec
Interval specification.
The format starts with the letter P, for "period." Each duration
period is represented by an integer value followed by a period
designator. If the duration contains time elements, that portion
of the specification is preceded by the letter T.
interval_spec Period Designators
Period Designator Description
Y years
M months
D days
W weeks. These get converted into days, so can not
be combined with D.
H hours
M minutes
S seconds
Here are some simple examples. Two days is P2D. Two seconds is
PT2S. Six years and five minutes is P6YT5M.
Note:
The unit types must be entered from the largest scale unit on
the left to the smallest scale unit on the right. So years
before months, months before days, days before minutes, etc.
Thus one year and four days must be represented as P1Y4D, not
P4D1Y.
The specification can also be represented as a date time. A sample
of one year and four days would be P0001-00-04T00:00:00. But the
values in this format can not exceed a given period's
roll-over-point (e.g. 25 hours is invalid).
These formats are based on the >> ISO 8601 duration specification.
Examples
Example #1 DateInterval example
The above example will output:
DateInterval Object
(
[y] => 2
[m] => 0
[d] => 4
[h] => 6
[i] => 8
[s] => 0
[invert] => 0
[days] => 0
)
See Also
* DateInterval::format() - Formats the interval
* DateTime::add() - Adds an amount of days, months, years, hours,
minutes and seconds to a DateTime object
* DateTime::sub() - Subtracts an amount of days, months, years, hours,
minutes and seconds from a DateTime object
* DateTime::diff() - Returns the difference between two DateTime objects
----------------------------------------------------------------------
----------------------------------------------------------------------
DateInterval::createFromDateString
(PHP 5 >= 5.3.0)
DateInterval::createFromDateString - Sets up a DateInterval from the
relative parts of the string
Description
public static DateInterval DateInterval::createFromDateString ( string
$time )
Uses the normal date parsers and sets up a DateInterval from the relative
parts of the parsed string.
Parameters
time
Date with relative parts.
Return Values
Returns new DateInterval instance if success.
----------------------------------------------------------------------
----------------------------------------------------------------------
DateInterval::format
(PHP 5 >= 5.3.0)
DateInterval::format - Formats the interval
Description
public string DateInterval::format ( string $format )
Formats the interval.
Parameters
format
The following characters are recognized in the format parameter
string. Each format character must be prefixed by a percent sign
(%).
format character Description Example values
% Literal % %
Y Years, numeric, at least 2 digits 01, 03
with leading 0
y Years, numeric 1, 3
M Months, numeric, at least 2 digits 01, 03, 12
with leading 0
m Months, numeric 1, 3, 12
D Days, numeric, at least 2 digits 01, 03, 31
with leading 0
d Days, numeric 1, 3, 31
a Total amount of days 4, 18, 8123
H Hours, numeric, at least 2 digits 01, 03, 23
with leading 0
h Hours, numeric 1, 3, 23
I Minutes, numeric, at least 2 01, 03, 59
digits with leading 0
i Minutes, numeric 1, 3, 59
S Seconds, numeric, at least 2 01, 03, 57
digits with leading 0
s Seconds, numeric 1, 3, 57
R Sign "-" when negative, "+" when -, +
positive
r Sign "-" when negative, empty when -,
positive
Return Values
Returns the formatted interval.
Notes
Note:
The DateInterval::format() method does not recalculate carry over points
in time strings nor in date segments. This is expected because it is not
possible to overflow values like "32 days" which could be interpreted as
anything from "1 month and 4 days" to "1 month and 1 day".
Examples
Example #1 DateInterval example
format('%d days');
?>
The above example will output:
4 days
Example #2 DateInterval and carry over points
format('%d days');
?>
The above example will output:
32 days
Example #3 DateInterval and DateTime::diff() with the %a and %d modifiers
diff($january);
// %a will output the total number of days.
echo $interval->format('%a total days')."\n";
// While %d will only output the number of days not already covered by the
// month.
echo $interval->format('%m month, %d days');
?>
The above example will output:
31 total days
1 month, 0 days
----------------------------------------------------------------------
Table of Contents
* DateInterval::__construct - Creates new DateInterval object
* DateInterval::createFromDateString - Sets up a DateInterval from the
relative parts of the string
* DateInterval::format - Formats the interval
----------------------------------------------------------------------
----------------------------------------------------------------------
The DatePeriod class
Introduction
Representation of date period.
Class synopsis
DatePeriod implements Traversable {
/* Constants */
const integer EXCLUDE_START_DATE = 1 ;
/* Methods */
public __construct ( DateTime $start , DateInterval $interval , int
$recurrences [, int $options ] )
public __construct ( DateTime $start , DateInterval $interval , DateTime
$end [, int $options ] )
public __construct ( string $isostr [, int $options ] )
}
Predefined Constants
DatePeriod Node Types
DatePeriod::EXCLUDE_START_DATE
Exclude start date, used in DatePeriod::__construct().
----------------------------------------------------------------------
DatePeriod::__construct
(PHP 5 >= 5.3.0)
DatePeriod::__construct - Creates new DatePeriod object
Description
public DatePeriod::__construct() ( DateTime $start , DateInterval
$interval , int $recurrences [, int $options ] )
public DatePeriod::__construct() ( DateTime $start , DateInterval
$interval , DateTime $end [, int $options ] )
public DatePeriod::__construct() ( string $isostr [, int $options ] )
Creates new DatePeriod object.
Parameters
start
Start date.
interval
Interval.
recurrences
Number of recurrences.
end
End date.
isostr
String containing the ISO interval.
options
Can be set to DatePeriod::EXCLUDE_START_DATE.
----------------------------------------------------------------------
Table of Contents
* DatePeriod::__construct - Creates new DatePeriod object
----------------------------------------------------------------------
----------------------------------------------------------------------
Date/Time Functions
----------------------------------------------------------------------
checkdate
(PHP 4, PHP 5)
checkdate - Validate a Gregorian date
Description
bool checkdate ( int $month , int $day , int $year )
Checks the validity of the date formed by the arguments. A date is
considered valid if each parameter is properly defined.
Parameters
month
The month is between 1 and 12 inclusive.
day
The day is within the allowed number of days for the given month.
Leap years are taken into consideration.
year
The year is between 1 and 32767 inclusive.
Return Values
Returns TRUE if the date given is valid; otherwise returns FALSE.
Examples
Example #1 checkdate() example
The above example will output:
bool(true)
bool(false)
See Also
* mktime() - Get Unix timestamp for a date
* strtotime() - Parse about any English textual datetime description
into a Unix timestamp
----------------------------------------------------------------------
----------------------------------------------------------------------
date_add
(PHP 5 >= 5.3.0)
date_add - Alias of DateTime::add()
Description
This function is an alias of: DateTime::add()
----------------------------------------------------------------------
----------------------------------------------------------------------
date_create_from_format
(PHP 5 >= 5.3.0)
date_create_from_format - Alias of DateTime::createFromFormat()
Description
This function is an alias of: DateTime::createFromFormat()
----------------------------------------------------------------------
----------------------------------------------------------------------
date_create
(PHP 5 >= 5.2.0)
date_create - Alias of DateTime::__construct()
Description
This function is an alias of: DateTime::__construct()
----------------------------------------------------------------------
----------------------------------------------------------------------
date_date_set
(PHP 5 >= 5.2.0)
date_date_set - Alias of DateTime::setDate()
Description
This function is an alias of: DateTime::setDate()
----------------------------------------------------------------------
----------------------------------------------------------------------
date_default_timezone_get
(PHP 5 >= 5.1.0)
date_default_timezone_get - Gets the default timezone used by all
date/time functions in a script
Description
string date_default_timezone_get ( void )
In order of preference, this function returns the default timezone by:
* Reading the timezone set using the date_default_timezone_set()
function (if any)
* Reading the TZ environment variable (if non empty) (Prior to PHP
5.3.0)
* Reading the value of the date.timezone ini option (if set)
* Querying the host operating system (if supported and allowed by the
OS). This uses an algorithm that has to guess the timezone. This is by
no means going to work correctly for every situation. A warning is
shown when this stage is reached. Do not rely on it to be guessed
correctly, and set date.timezone to the correct timezone instead.
If none of the above succeed, date_default_timezone_get() will return a
default timezone of UTC.
Return Values
Returns a string.
Changelog
Version Description
5.3.0 The TZ environment variable is no longer used to guess the
timezone.
Examples
Example #1 Getting the default timezone
';
}
if (ini_get('date.timezone')) {
echo 'date.timezone: ' . ini_get('date.timezone');
}
?>
The above example will output something similar to:
date_default_timezone_set: Europe/London
date.timezone: Europe/London
Example #2 Getting the abbreviation of a timezone
' . date('e') . ' => ' . date('T');
?>
The above example will output:
America/Los_Angeles => America/Los_Angeles => PST
See Also
* date_default_timezone_set() - Sets the default timezone used by all
date/time functions in a script
* List of Supported Timezones
----------------------------------------------------------------------
----------------------------------------------------------------------
date_default_timezone_set
(PHP 5 >= 5.1.0)
date_default_timezone_set - Sets the default timezone used by all
date/time functions in a script
Description
bool date_default_timezone_set ( string $timezone_identifier )
date_default_timezone_set() sets the default timezone used by all
date/time functions.
Note:
Since PHP 5.1.0 (when the date/time functions were rewritten), every
call to a date/time function will generate a E_NOTICE if the timezone
isn't valid, and/or a E_WARNING message if using the system settings or
the TZ environment variable.
Instead of using this function to set the default timezone in your script,
you can also use the INI setting date.timezone to set the default
timezone.
Parameters
timezone_identifier
The timezone identifier, like UTC or Europe/Lisbon. The list of
valid identifiers is available in the List of Supported Timezones.
Return Values
This function returns FALSE if the timezone_identifier isn't valid, or
TRUE otherwise.
Examples
Example #1 Getting the default timezone
Changelog
Version Description
5.3.0 Now throws E_WARNING rather than E_STRICT.
5.1.2 The function started to validate the timezone_identifier
parameter.
See Also
* date_default_timezone_get() - Gets the default timezone used by all
date/time functions in a script
* List of Supported Timezones
----------------------------------------------------------------------
----------------------------------------------------------------------
date_diff
(PHP 5 >= 5.3.0)
date_diff - Alias of DateTime::diff()
Description
This function is an alias of: DateTime::diff()
----------------------------------------------------------------------
----------------------------------------------------------------------
date_format
(PHP 5 >= 5.2.0)
date_format - Alias of DateTime::format()
Description
This function is an alias of: DateTime::format()
----------------------------------------------------------------------
----------------------------------------------------------------------
date_get_last_errors
(PHP 5 >= 5.3.0)
date_get_last_errors - Alias of DateTime::getLastErrors()
Description
This function is an alias of: DateTime::getLastErrors()
----------------------------------------------------------------------
----------------------------------------------------------------------
date_interval_create_from_date_string
(PHP 5 >= 5.3.0)
date_interval_create_from_date_string - Alias of
DateInterval::createFromDateString()
Description
This function is an alias of: DateInterval::createFromDateString()
----------------------------------------------------------------------
----------------------------------------------------------------------
date_interval_format
(PHP 5 >= 5.3.0)
date_interval_format - Alias of DateInterval::format()
Description
This function is an alias of: DateInterval::format()
----------------------------------------------------------------------
----------------------------------------------------------------------
date_isodate_set
(PHP 5 >= 5.2.0)
date_isodate_set - Alias of DateTime::setISODate()
Description
This function is an alias of: DateTime::setISODate()
----------------------------------------------------------------------
----------------------------------------------------------------------
date_modify
(PHP 5 >= 5.2.0)
date_modify - Alias of DateTime::modify()
Description
This function is an alias of: DateTime::modify()
----------------------------------------------------------------------
----------------------------------------------------------------------
date_offset_get
(PHP 5 >= 5.2.0)
date_offset_get - Alias of DateTime::getOffset()
Description
This function is an alias of: DateTime::getOffset()
----------------------------------------------------------------------
----------------------------------------------------------------------
date_parse_from_format
(PHP 5 >= 5.3.0)
date_parse_from_format - Get info about given date formatted according to
the specified format
Description
array date_parse_from_format ( string $format , string $date )
Returns associative array with detailed info about given date.
Parameters
format
Format accepted by DateTime::createFromFormat().
date
String representing the date.
Return Values
Returns associative array with detailed info about given date.
Examples
Example #1 date_parse_from_format() example
The above example will output:
Array
(
[year] => 2009
[month] => 1
[day] => 6
[hour] => 13
[minute] => 0
[second] => 0
[fraction] =>
[warning_count] => 0
[warnings] => Array
(
)
[error_count] => 0
[errors] => Array
(
)
[is_localtime] => 1
[zone_type] => 1
[zone] => -60
[is_dst] =>
)
See Also
* DateTime::createFromFormat() - Returns new DateTime object formatted
according to the specified format
* checkdate() - Validate a Gregorian date
----------------------------------------------------------------------
----------------------------------------------------------------------
date_parse
(PHP 5 >= 5.2.0)
date_parse - Returns associative array with detailed info about given date
Description
array date_parse ( string $date )
Parameters
date
Date in format accepted by strtotime().
Return Values
Returns array with information about the parsed date on success or FALSE
on failure.
Errors/Exceptions
In case the date format has an error, the element 'errors' will contains
the error messages.
Examples
Example #1 A date_parse() example
The above example will output:
Array
(
[year] => 2006
[month] => 12
[day] => 12
[hour] => 10
[minute] => 0
[second] => 0
[fraction] => 0.5
[warning_count] => 0
[warnings] => Array()
[error_count] => 0
[errors] => Array()
[is_localtime] =>
)
See Also
* checkdate() - Validate a Gregorian date
* getdate() - Get date/time information
----------------------------------------------------------------------
----------------------------------------------------------------------
date_sub
(PHP 5 >= 5.3.0)
date_sub - Alias of DateTime::sub()
Description
This function is an alias of: DateTime::sub()
----------------------------------------------------------------------
----------------------------------------------------------------------
date_sun_info
(PHP 5 >= 5.1.2)
date_sun_info - Returns an array with information about sunset/sunrise and
twilight begin/end
Description
array date_sun_info ( int $time , float $latitude , float $longitude )
Parameters
time
Timestamp.
latitude
Latitude in degrees.
longitude
Longitude in degrees.
Return Values
Returns array on success or FALSE on failure.
Examples
Example #1 A date_sun_info() example
$val) {
echo "$key: " . date("H:i:s", $val) . "\n";
}
?>
The above example will output:
sunrise: 05:52:11
sunset: 15:41:21
transit: 10:46:46
civil_twilight_begin: 05:24:08
civil_twilight_end: 16:09:24
nautical_twilight_begin: 04:52:25
nautical_twilight_end: 16:41:06
astronomical_twilight_begin: 04:21:32
astronomical_twilight_end: 17:12:00
See Also
* date_sunrise() - Returns time of sunrise for a given day and location
* date_sunset() - Returns time of sunset for a given day and location
----------------------------------------------------------------------
----------------------------------------------------------------------
date_sunrise
(PHP 5)
date_sunrise - Returns time of sunrise for a given day and location
Description
mixed date_sunrise ( int $timestamp [, int $format = SUNFUNCS_RET_STRING
[, float $latitude = ini_get("date.default_latitude") [, float $longitude
= ini_get("date.default_longitude") [, float $zenith =
ini_get("date.sunrise_zenith") [, float $gmt_offset = 0 ]]]]] )
date_sunrise() returns the sunrise time for a given day (specified as a
timestamp) and location.
Parameters
timestamp
The timestamp of the day from which the sunrise time is taken.
format
format constants
constant description example
SUNFUNCS_RET_STRING returns the result as string 16:46
SUNFUNCS_RET_DOUBLE returns the result as float 16.78243132
SUNFUNCS_RET_TIMESTAMP returns the result as integer 1095034606
(timestamp)
latitude
Defaults to North, pass in a negative value for South. See also:
date.default_latitude
longitude
Defaults to East, pass in a negative value for West. See also:
date.default_longitude
zenith
Default: date.sunrise_zenith
gmtoffset
Specified in hours.
Return Values
Returns the sunrise time in a specified format on success or FALSE on
failure.
Errors/Exceptions
Every call to a date/time function will generate a E_NOTICE if the time
zone is not valid, and/or a E_STRICT or E_WARNING message if using the
system settings or the TZ environment variable. See also
date_default_timezone_set()
Changelog
Version Description
5.1.0 Now issues the E_STRICT and E_NOTICE time zone errors.
Examples
Example #1 date_sunrise() example
The above example will output something similar to:
Mon Dec 20 2004, sunrise time : 08:54
See Also
* date_sunset() - Returns time of sunset for a given day and location
----------------------------------------------------------------------
----------------------------------------------------------------------
date_sunset
(PHP 5)
date_sunset - Returns time of sunset for a given day and location
Description
mixed date_sunset ( int $timestamp [, int $format = SUNFUNCS_RET_STRING [,
float $latitude = ini_get("date.default_latitude") [, float $longitude =
ini_get("date.default_longitude") [, float $zenith =
ini_get("date.sunset_zenith") [, float $gmt_offset = 0 ]]]]] )
date_sunset() returns the sunset time for a given day (specified as a
timestamp) and location.
Parameters
timestamp
The timestamp of the day from which the sunset time is taken.
format
format constants
constant description example
SUNFUNCS_RET_STRING returns the result as string 16:46
SUNFUNCS_RET_DOUBLE returns the result as float 16.78243132
SUNFUNCS_RET_TIMESTAMP returns the result as integer 1095034606
(timestamp)
latitude
Defaults to North, pass in a negative value for South. See also:
date.default_latitude
longitude
Defaults to East, pass in a negative value for West. See also:
date.default_longitude
zenith
Default: date.sunset_zenith
gmtoffset
Specified in hours.
Errors/Exceptions
Every call to a date/time function will generate a E_NOTICE if the time
zone is not valid, and/or a E_STRICT or E_WARNING message if using the
system settings or the TZ environment variable. See also
date_default_timezone_set()
Changelog
Version Description
5.1.0 Now issues the E_STRICT and E_NOTICE time zone errors.
Return Values
Returns the sunset time in a specified format on success or FALSE on
failure.
Examples
Example #1 date_sunset() example
The above example will output something similar to:
Mon Dec 20 2004, sunset time : 18:13
See Also
* date_sunrise() - Returns time of sunrise for a given day and location
----------------------------------------------------------------------
----------------------------------------------------------------------
date_time_set
(PHP 5 >= 5.2.0)
date_time_set - Alias of DateTime::setTime()
Description
This function is an alias of: DateTime::setTime()
----------------------------------------------------------------------
----------------------------------------------------------------------
date_timestamp_get
(PHP 5 >= 5.3.0)
date_timestamp_get - Alias of DateTime::getTimestamp()
Description
This function is an alias of: DateTime::getTimestamp()
----------------------------------------------------------------------
----------------------------------------------------------------------
date_timestamp_set
(PHP 5 >= 5.3.0)
date_timestamp_set - Alias of DateTime::setTimestamp()
Description
This function is an alias of: DateTime::setTimestamp()
----------------------------------------------------------------------
----------------------------------------------------------------------
date_timezone_get
(PHP 5 >= 5.2.0)
date_timezone_get - Alias of DateTime::getTimezone()
Description
This function is an alias of: DateTime::getTimezone()
----------------------------------------------------------------------
----------------------------------------------------------------------
date_timezone_set
(PHP 5 >= 5.2.0)
date_timezone_set - Alias of DateTime::setTimezone()
Description
This function is an alias of: DateTime::setTimezone()
----------------------------------------------------------------------
----------------------------------------------------------------------
date
(PHP 4, PHP 5)
date - Format a local time/date
Description
string date ( string $format [, int $timestamp = time() ] )
Returns a string formatted according to the given format string using the
given integer timestamp or the current time if no timestamp is given. In
other words, timestamp is optional and defaults to the value of time().
Parameters
format
The format of the outputted date string. See the formatting
options below. There are also several predefined date constants
that may be used instead, so for example DATE_RSS contains the
format string 'D, d M Y H:i:s'.
The following characters are recognized in the format parameter
string
format Description Example returned values
character
Day --- ---
Day of the month, 2
d digits with leading 01 to 31
zeros
A textual
D representation of a Mon through Sun
day, three letters
j Day of the month 1 to 31
without leading zeros
l (lowercase A full textual
'L') representation of the Sunday through Saturday
day of the week
ISO-8601 numeric
N representation of the 1 (for Monday) through 7
day of the week (added (for Sunday)
in PHP 5.1.0)
English ordinal suffix st, nd, rd or th. Works well
S for the day of the with j
month, 2 characters
w Numeric representation 0 (for Sunday) through 6
of the day of the week (for Saturday)
z The day of the year 0 through 365
(starting from 0)
Week --- ---
ISO-8601 week number of
W year, weeks starting on Example: 42 (the 42nd week
Monday (added in PHP in the year)
4.1.0)
Month --- ---
A full textual
F representation of a January through December
month, such as January
or March
Numeric representation
m of a month, with 01 through 12
leading zeros
A short textual
M representation of a Jan through Dec
month, three letters
Numeric representation
n of a month, without 1 through 12
leading zeros
t Number of days in the 28 through 31
given month
Year --- ---
L Whether it's a leap 1 if it is a leap year, 0
year otherwise.
ISO-8601 year number.
This has the same value
as Y, except that if
o the ISO week number (W) Examples: 1999 or 2003
belongs to the previous
or next year, that year
is used instead. (added
in PHP 5.1.0)
A full numeric
Y representation of a Examples: 1999 or 2003
year, 4 digits
A two digit
y representation of a Examples: 99 or 03
year
Time --- ---
a Lowercase Ante meridiem am or pm
and Post meridiem
A Uppercase Ante meridiem AM or PM
and Post meridiem
B Swatch Internet time 000 through 999
12-hour format of an
g hour without leading 1 through 12
zeros
24-hour format of an
G hour without leading 0 through 23
zeros
h 12-hour format of an 01 through 12
hour with leading zeros
H 24-hour format of an 00 through 23
hour with leading zeros
i Minutes with leading 00 to 59
zeros
s Seconds, with leading 00 through 59
zeros
u Microseconds (added in Example: 654321
PHP 5.2.2)
Timezone --- ---
e Timezone identifier Examples: UTC, GMT,
(added in PHP 5.1.0) Atlantic/Azores
Whether or not the date 1 if Daylight Saving Time, 0
I (capital i) is in daylight saving otherwise.
time
O Difference to Greenwich Example: +0200
time (GMT) in hours
Difference to Greenwich
time (GMT) with colon
P between hours and Example: +02:00
minutes (added in PHP
5.1.3)
T Timezone abbreviation Examples: EST, MDT ...
Timezone offset in
seconds. The offset for
Z timezones west of UTC -43200 through 50400
is always negative, and
for those east of UTC
is always positive.
Full --- ---
Date/Time
c ISO 8601 date (added in 2004-02-12T15:19:21+00:00
PHP 5)
r >> RFC 2822 formatted Example: Thu, 21 Dec 2000
date 16:01:07 +0200
Seconds since the Unix
U Epoch (January 1 1970 See also time()
00:00:00 GMT)
Unrecognized characters in the format string will be printed
as-is. The Z format will always return 0 when using gmdate().
Note:
Since this function only accepts integer timestamps the u format
character is only useful when using the date_format() function
with user based timestamps created with date_create().
timestamp
The optional timestamp parameter is an integer Unix timestamp that
defaults to the current local time if a timestamp is not given. In
other words, it defaults to the value of time().
Return Values
Returns a formatted date string. If a non-numeric value is used for
timestamp, FALSE is returned and an E_WARNING level error is emitted.
Errors/Exceptions
Every call to a date/time function will generate a E_NOTICE if the time
zone is not valid, and/or a E_STRICT or E_WARNING message if using the
system settings or the TZ environment variable. See also
date_default_timezone_set()
Changelog
Version Description
The valid range of a timestamp is typically from Fri, 13 Dec 1901
20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the
5.1.0 dates that correspond to the minimum and maximum values for a
32-bit signed integer). However, before PHP 5.1.0 this range was
limited from 01-01-1970 to 19-01-2038 on some systems (e.g.
Windows).
5.1.0 Now issues the E_STRICT and E_NOTICE time zone errors.
5.1.1 There are useful constants of standard date/time formats that can
be used to specify the format parameter.
Examples
Example #1 date() examples
You can prevent a recognized character in the format string from being
expanded by escaping it with a preceding backslash. If the character with
a backslash is already a special sequence, you may need to also escape the
backslash.
Example #2 Escaping characters in date()
It is possible to use date() and mktime() together to find dates in the
future or the past.
Example #3 date() and mktime() example
Note:
This can be more reliable than simply adding or subtracting the number
of seconds in a day or month to a timestamp because of daylight saving
time.
Some examples of date() formatting. Note that you should escape any other
characters, as any which currently have a special meaning will produce
undesirable results, and other characters may be assigned meaning in
future PHP versions. When escaping, be sure to use single quotes to
prevent characters like \n from becoming newlines.
Example #4 date() Formatting
To format dates in other languages, you should use the setlocale() and
strftime() functions instead of date().
Notes
Note:
To generate a timestamp from a string representation of the date, you
may be able to use strtotime(). Additionally, some databases have
functions to convert their date formats into timestamps (such as MySQL's
>> UNIX_TIMESTAMP function).
Tip
Timestamp of the start of the request is available in
$_SERVER['REQUEST_TIME'] since PHP 5.1.
See Also
* gmdate() - Format a GMT/UTC date/time
* idate() - Format a local time/date as integer
* getdate() - Get date/time information
* getlastmod() - Gets time of last page modification
* mktime() - Get Unix timestamp for a date
* strftime() - Format a local time/date according to locale settings
* time() - Return current Unix timestamp
* strtotime() - Parse about any English textual datetime description
into a Unix timestamp
* Predefined DateTime Constants
----------------------------------------------------------------------
----------------------------------------------------------------------
getdate
(PHP 4, PHP 5)
getdate - Get date/time information
Description
array getdate ([ int $timestamp = time() ] )
Returns an associative array containing the date information of the
timestamp, or the current local time if no timestamp is given.
Parameters
timestamp
The optional timestamp parameter is an integer Unix timestamp that
defaults to the current local time if a timestamp is not given. In
other words, it defaults to the value of time().
Return Values
Returns an associative array of information related to the timestamp.
Elements from the returned associative array are as follows:
Key elements of the returned associative array
Key Description Example returned values
"seconds" Numeric representation of seconds 0 to 59
"minutes" Numeric representation of minutes 0 to 59
"hours" Numeric representation of hours 0 to 23
"mday" Numeric representation of the day of 1 to 31
the month
"wday" Numeric representation of the day of 0 (for Sunday) through 6
the week (for Saturday)
"mon" Numeric representation of a month 1 through 12
"year" A full numeric representation of a Examples: 1999 or 2003
year, 4 digits
"yday" Numeric representation of the day of 0 through 365
the year
"weekday" A full textual representation of the Sunday through Saturday
day of the week
"month" A full textual representation of a January through December
month, such as January or March
Seconds since the Unix Epoch, System Dependent, typically
0 similar to the values returned by -2147483648 through
time() and used by date(). 2147483647.
Examples
Example #1 getdate() example
The above example will output something similar to:
Array
(
[seconds] => 40
[minutes] => 58
[hours] => 21
[mday] => 17
[wday] => 2
[mon] => 6
[year] => 2003
[yday] => 167
[weekday] => Tuesday
[month] => June
[0] => 1055901520
)
See Also
* date() - Format a local time/date
* idate() - Format a local time/date as integer
* localtime() - Get the local time
* time() - Return current Unix timestamp
* setlocale() - Set locale information
----------------------------------------------------------------------
----------------------------------------------------------------------
gettimeofday
(PHP 4, PHP 5)
gettimeofday - Get current time
Description
mixed gettimeofday ([ bool $return_float = false ] )
This is an interface to gettimeofday(2). It returns an associative array
containing the data returned from the system call.
Parameters
return_float
When set to TRUE, a float instead of an array is returned.
Return Values
By default an array is returned. If return_float is set, then a float is
returned.
Array keys:
* "sec" - seconds since the Unix Epoch
* "usec" - microseconds
* "minuteswest" - minutes west of Greenwich
* "dsttime" - type of dst correction
Changelog
Version Description
5.1.0 The return_float parameter was added.
Examples
Example #1 gettimeofday() example
The above example will output something similar to:
Array
(
[sec] => 1073504408
[usec] => 238215
[minuteswest] => 0
[dsttime] => 1
)
1073504408.23910
----------------------------------------------------------------------
----------------------------------------------------------------------
gmdate
(PHP 4, PHP 5)
gmdate - Format a GMT/UTC date/time
Description
string gmdate ( string $format [, int $timestamp = time() ] )
Identical to the date() function except that the time returned is
Greenwich Mean Time (GMT).
Parameters
format
The format of the outputted date string. See the formatting
options for the date() function.
timestamp
The optional timestamp parameter is an integer Unix timestamp that
defaults to the current local time if a timestamp is not given. In
other words, it defaults to the value of time().
Return Values
Returns a formatted date string. If a non-numeric value is used for
timestamp, FALSE is returned and an E_WARNING level error is emitted.
Changelog
Version Description
The valid range of a timestamp is typically from Fri, 13 Dec 1901
20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the
5.1.0 dates that correspond to the minimum and maximum values for a
32-bit signed integer). However, before PHP 5.1.0 this range was
limited from 01-01-1970 to 19-01-2038 on some systems (e.g.
Windows).
5.1.1 There are useful constants of standard date/time formats that can
be used to specify the format parameter.
Examples
Example #1 gmdate() example
When run in Finland (GMT +0200), the first line below prints "Jan 01 1998
00:00:00", while the second prints "Dec 31 1997 22:00:00".
See Also
* date() - Format a local time/date
* mktime() - Get Unix timestamp for a date
* gmmktime() - Get Unix timestamp for a GMT date
* strftime() - Format a local time/date according to locale settings
----------------------------------------------------------------------
----------------------------------------------------------------------
gmmktime
(PHP 4, PHP 5)
gmmktime - Get Unix timestamp for a GMT date
Description
int gmmktime ([ int $hour = gmdate("H") [, int $minute = gmdate("i") [,
int $second = gmdate("s") [, int $month = gmdate("n") [, int $day =
gmdate("j") [, int $year = gmdate("Y") [, int $is_dst = -1 ]]]]]]] )
Identical to mktime() except the passed parameters represents a GMT date.
gmmktime() internally uses mktime() so only times valid in derived local
time can be used.
Like mktime(), arguments may be left out in order from right to left, with
any omitted arguments being set to the current corresponding GMT value.
Parameters
hour
The number of the hour relevant to the start of the day determined
by month, day and year. Negative values reference the hour before
midnight of the day in question. Values greater than 23 reference
the appropriate hour in the following day(s).
minute
The number of the minute relevant to the start of the hour.
Negative values reference the minute in the previous hour. Values
greater than 59 reference the appropriate minute in the following
hour(s).
second
The number of seconds relevant to the start of the minute.
Negative values reference the second in the previous minute.
Values greater than 59 reference the appropriate second in the
following minute(s).
month
The number of the month relevant to the end of the previous year.
Values 1 to 12 reference the normal calendar months of the year in
question. Values less than 1 (including negative values) reference
the months in the previous year in reverse order, so 0 is
December, -1 is November, etc. Values greater than 12 reference
the appropriate month in the following year(s).
day
The number of the day relevant to the end of the previous month.
Values 1 to 28, 29, 30 or 31 (depending upon the month) reference
the normal days in the relevant month. Values less than 1
(including negative values) reference the days in the previous
month, so 0 is the last day of the previous month, -1 is the day
before that, etc. Values greater than the number of days in the
relevant month reference the appropriate day in the following
month(s).
year
The year
is_dst
Parameters always represent a GMT date so is_dst doesn't influence
the result.
Return Values
Returns a integer Unix timestamp.
Changelog
Version Description
5.1.0 As of PHP 5.1.0, the is_dst parameter became deprecated. As a
result, the new timezone handling features should be used instead.
Examples
Example #1 gmmktime() on Windows boundary
See Also
* mktime() - Get Unix timestamp for a date
* date() - Format a local time/date
* time() - Return current Unix timestamp
----------------------------------------------------------------------
----------------------------------------------------------------------
gmstrftime
(PHP 4, PHP 5)
gmstrftime - Format a GMT/UTC time/date according to locale settings
Description
string gmstrftime ( string $format [, int $timestamp = time() ] )
Behaves the same as strftime() except that the time returned is Greenwich
Mean Time (GMT). For example, when run in Eastern Standard Time (GMT
-0500), the first line below prints "Dec 31 1998 20:00:00", while the
second prints "Jan 01 1999 01:00:00".
Parameters
format
See description in strftime().
timestamp
The optional timestamp parameter is an integer Unix timestamp that
defaults to the current local time if a timestamp is not given. In
other words, it defaults to the value of time().
Return Values
Returns a string formatted according to the given format string using the
given timestamp or the current local time if no timestamp is given. Month
and weekday names and other language dependent strings respect the current
locale set with setlocale().
Examples
Example #1 gmstrftime() example
See Also
* strftime() - Format a local time/date according to locale settings
----------------------------------------------------------------------
----------------------------------------------------------------------
idate
(PHP 5)
idate - Format a local time/date as integer
Description
int idate ( string $format [, int $timestamp = time() ] )
Returns a number formatted according to the given format string using the
given integer timestamp or the current local time if no timestamp is
given. In other words, timestamp is optional and defaults to the value of
time().
Unlike the function date(), idate() accepts just one char in the format
parameter.
Parameters
format
The following characters are recognized in the format parameter
string
format character Description
B Swatch Beat/Internet Time
d Day of the month
h Hour (12 hour format)
H Hour (24 hour format)
i Minutes
I (uppercase i) returns 1 if DST is activated, 0 otherwise
L (uppercase l) returns 1 for leap year, 0 otherwise
m Month number
s Seconds
t Days in current month
U Seconds since the Unix Epoch - January 1 1970
00:00:00 UTC - this is the same as time()
w Day of the week (0 on Sunday)
W ISO-8601 week number of year, weeks starting on
Monday
y Year (1 or 2 digits - check note below)
Y Year (4 digits)
z Day of the year
Z Timezone offset in seconds
timestamp
The optional timestamp parameter is an integer Unix timestamp that
defaults to the current local time if a timestamp is not given. In
other words, it defaults to the value of time().
Return Values
Returns an integer.
As idate() always returns an integer and as they can't start with a "0",
idate() may return fewer digits than you would expect. See the example
below.
Errors/Exceptions
Every call to a date/time function will generate a E_NOTICE if the time
zone is not valid, and/or a E_STRICT or E_WARNING message if using the
system settings or the TZ environment variable. See also
date_default_timezone_set()
Changelog
Version Description
5.1.0 Now issues the E_STRICT and E_NOTICE time zone errors.
Examples
Example #1 idate() example
See Also
* date() - Format a local time/date
* getdate() - Get date/time information
* time() - Return current Unix timestamp
----------------------------------------------------------------------
----------------------------------------------------------------------
localtime
(PHP 4, PHP 5)
localtime - Get the local time
Description
array localtime ([ int $timestamp = time() [, bool $is_associative = false
]] )
The localtime() function returns an array identical to that of the
structure returned by the C function call.
Parameters
timestamp
The optional timestamp parameter is an integer Unix timestamp that
defaults to the current local time if a timestamp is not given. In
other words, it defaults to the value of time().
is_associative
If set to FALSE or not supplied then the array is returned as a
regular, numerically indexed array. If the argument is set to TRUE
then localtime() returns an associative array containing all the
different elements of the structure returned by the C function
call to localtime. The names of the different keys of the
associative array are as follows:
* "tm_sec" - seconds, 0 to 59
* "tm_min" - minutes, 0 to 59
* "tm_hour" - hours, 0 to 23
* "tm_mday" - day of the month, 1 to 31
* "tm_mon" - month of the year, 0 (Jan) to 11 (Dec)
* "tm_year" - years since 1900
* "tm_wday" - day of the week, 0 (Sun) to 6 (Sat)
* "tm_yday" - day of the year, 0 to 365
* "tm_isdst" - is daylight savings time in effect? Positive if
yes, 0 if not, negative if unknown.
Errors/Exceptions
Every call to a date/time function will generate a E_NOTICE if the time
zone is not valid, and/or a E_STRICT or E_WARNING message if using the
system settings or the TZ environment variable. See also
date_default_timezone_set()
Changelog
Version Description
5.1.0 Now issues the E_STRICT and E_NOTICE time zone errors.
Examples
Example #1 localtime() example
The above example will output something similar to:
Array
(
[0] => 24
[1] => 3
[2] => 19
[3] => 3
[4] => 3
[5] => 105
[6] => 0
[7] => 92
[8] => 1
)
Array
(
[tm_sec] => 24
[tm_min] => 3
[tm_hour] => 19
[tm_mday] => 3
[tm_mon] => 3
[tm_year] => 105
[tm_wday] => 0
[tm_yday] => 92
[tm_isdst] => 1
)
See Also
* getdate() - Get date/time information
----------------------------------------------------------------------
----------------------------------------------------------------------
microtime
(PHP 4, PHP 5)
microtime - Return current Unix timestamp with microseconds
Description
mixed microtime ([ bool $get_as_float = false ] )
microtime() returns the current Unix timestamp with microseconds. This
function is only available on operating systems that support the
gettimeofday() system call.
Parameters
get_as_float
If used and set to TRUE, microtime() will return a float instead
of a string, as described in the return values section below.
Return Values
By default, microtime() returns a string in the form "msec sec", where sec
is the current time measured in the number of seconds since the Unix epoch
(0:00:00 January 1, 1970 GMT), and msec is the number of microseconds that
have elapsed since sec expressed in seconds.
If get_as_float is set to TRUE, then microtime() returns a float, which
represents the current time in seconds since the Unix epoch accurate to
the nearest microsecond.
Changelog
Version Description
5.0.0 The get_as_float parameter was added.
Examples
Example #1 Timing script execution with microtime()
Example #2 Timing script execution in PHP 5
See Also
* time() - Return current Unix timestamp
----------------------------------------------------------------------
----------------------------------------------------------------------
mktime
(PHP 4, PHP 5)
mktime - Get Unix timestamp for a date
Description
int mktime ([ int $hour = date("H") [, int $minute = date("i") [, int
$second = date("s") [, int $month = date("n") [, int $day = date("j") [,
int $year = date("Y") [, int $is_dst = -1 ]]]]]]] )
Returns the Unix timestamp corresponding to the arguments given. This
timestamp is a long integer containing the number of seconds between the
Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.
Arguments may be left out in order from right to left; any arguments thus
omitted will be set to the current value according to the local date and
time.
Notes
Note:
As of PHP 5.1, when called with no arguments, mktime() throws an
E_STRICT notice: use the time() function instead.
Parameters
hour
The number of the hour relevant to the start of the day determined
by month, day and year. Negative values reference the hour before
midnight of the day in question. Values greater than 23 reference
the appropriate hour in the following day(s).
minute
The number of the minute relevant to the start of the hour.
Negative values reference the minute in the previous hour. Values
greater than 59 reference the appropriate minute in the following
hour(s).
second
The number of seconds relevant to the start of the minute.
Negative values reference the second in the previous minute.
Values greater than 59 reference the appropriate second in the
following minute(s).
month
The number of the month relevant to the end of the previous year.
Values 1 to 12 reference the normal calendar months of the year in
question. Values less than 1 (including negative values) reference
the months in the previous year in reverse order, so 0 is
December, -1 is November, etc. Values greater than 12 reference
the appropriate month in the following year(s).
day
The number of the day relevant to the end of the previous month.
Values 1 to 28, 29, 30 or 31 (depending upon the month) reference
the normal days in the relevant month. Values less than 1
(including negative values) reference the days in the previous
month, so 0 is the last day of the previous month, -1 is the day
before that, etc. Values greater than the number of days in the
relevant month reference the appropriate day in the following
month(s).
year
The number of the year, may be a two or four digit value, with
values between 0-69 mapping to 2000-2069 and 70-100 to 1970-2000.
On systems where time_t is a 32bit signed integer, as most common
today, the valid range for year is somewhere between 1901 and
2038. However, before PHP 5.1.0 this range was limited from 1970
to 2038 on some systems (e.g. Windows).
is_dst
This parameter can be set to 1 if the time is during daylight
savings time (DST), 0 if it is not, or -1 (the default) if it is
unknown whether the time is within daylight savings time or not.
If it's unknown, PHP tries to figure it out itself. This can cause
unexpected (but not incorrect) results. Some times are invalid if
DST is enabled on the system PHP is running on or is_dst is set to
1. If DST is enabled in e.g. 2:00, all times between 2:00 and 3:00
are invalid and mktime() returns an undefined (usually negative)
value. Some systems (e.g. Solaris 8) enable DST at midnight so
time 0:30 of the day when DST is enabled is evaluated as 23:30 of
the previous day.
Note:
As of PHP 5.1.0, this parameter became deprecated. As a result,
the new timezone handling features should be used instead.
Return Values
mktime() returns the Unix timestamp of the arguments given. If the
arguments are invalid, the function returns FALSE (before PHP 5.1 it
returned -1).
Errors/Exceptions
Every call to a date/time function will generate a E_NOTICE if the time
zone is not valid, and/or a E_STRICT or E_WARNING message if using the
system settings or the TZ environment variable. See also
date_default_timezone_set()
Changelog
Version Description
5.3.0 mktime() now throws E_DEPRECATED notice if the is_dst parameter is
used.
The is_dst parameter became deprecated. Made the function return
5.1.0 FALSE on error, instead of -1. Fixed the function to accept the
year, month and day to be all passed as zero.
5.1.0 When called with no arguments, mktime() throws E_STRICT notice.
Use the time() function instead.
5.1.0 Now issues the E_STRICT and E_NOTICE time zone errors.
Examples
Example #1 mktime() basic example
Example #2 mktime() example
mktime() is useful for doing date arithmetic and validation, as it will
automatically calculate the correct value for out-of-range input. For
example, each of the following lines produces the string "Jan-01-1998".
Example #3 Last day of next month
The last day of any given month can be expressed as the "0" day of the
next month, not the -1 day. Both of the following examples will produce
the string "The last day in Feb 2000 is: 29".
Notes
Caution
Before PHP 5.1.0, negative timestamps were not supported under any known
version of Windows and some other systems as well. Therefore the range of
valid years was limited to 1970 through 2038.
See Also
* checkdate() - Validate a Gregorian date
* gmmktime() - Get Unix timestamp for a GMT date
* date() - Format a local time/date
* time() - Return current Unix timestamp
----------------------------------------------------------------------
----------------------------------------------------------------------
strftime
(PHP 4, PHP 5)
strftime - Format a local time/date according to locale settings
Description
string strftime ( string $format [, int $timestamp = time() ] )
Format the time and/or date according to locale settings. Month and
weekday names and other language-dependent strings respect the current
locale set with setlocale().
Not all conversion specifiers may be supported by your C library, in which
case they will not be supported by PHP's strftime(). Additionally, not all
platforms support negative timestamps, so your date range may be limited
to no earlier than the Unix epoch. This means that %e, %T, %R and, %D (and
possibly others) - as well as dates prior to Jan 1, 1970 - will not work
on Windows, some Linux distributions, and a few other operating systems.
For Windows systems, a complete overview of supported conversion
specifiers can be found at >> MSDN.
Parameters
format
The following characters are recognized in the format parameter
string
format Description Example returned
values
Day --- ---
%a An abbreviated textual Sun through Sat
representation of the day
%A A full textual representation of Sunday through
the day Saturday
%d Two-digit day of the month (with 01 to 31
leading zeros)
Day of the month, with a space
preceding single digits. Not
%e implemented as described on 1 to 31
Windows. See below for more
information.
%j Day of the year, 3 digits with 001 to 366
leading zeros
ISO-8601 numeric representation 1 (for Monday)
%u of the day of the week though 7 (for
Sunday)
Numeric representation of the day 0 (for Sunday)
%w of the week through 6 (for
Saturday)
Week --- ---
Week number of the given year, 13 (for the 13th
%U starting with the first Sunday as full week of the
the first week year)
ISO-8601:1988 week number of the 01 through 53
given year, starting with the (where 53
%V first week of the year with at accounts for an
least 4 weekdays, with Monday overlapping week)
being the start of the week
A numeric representation of the 46 (for the 46th
%W week of the year, starting with week of the year
the first Monday as the first beginning with a
week Monday)
Month --- ---
%b Abbreviated month name, based on Jan through Dec
the locale
%B Full month name, based on the January through
locale December
%h Abbreviated month name, based on Jan through Dec
the locale (an alias of %b)
Two digit representation of the 01 (for January)
%m month through 12 (for
December)
Year --- ---
Two digit representation of the 19 for the 20th
%C century (year divided by 100, Century
truncated to an integer)
Two digit representation of the Example: 09 for
%g year going by ISO-8601:1988 the week of
standards (see %V) January 6, 2009
Example: 2008 for
%G The full four-digit version of %g the week of
January 3, 2009
%y Two digit representation of the Example: 09 for
year 2009, 79 for 1979
%Y Four digit representation for the Example: 2038
year
Time --- ---
%H Two digit representation of the 00 through 23
hour in 24-hour format
%I Two digit representation of the 01 through 12
hour in 12-hour format
%l (lower-case Hour in 12-hour format, with a 1 through 12
'L') space preceeding single digits
%M Two digit representation of the 00 through 59
minute
UPPER-CASE 'AM' or 'PM' based on Example: AM for
%p the given time 00:31, PM for
22:23
lower-case 'am' or 'pm' based on Example: am for
%P the given time 00:31, pm for
22:23
%r Same as "%I:%M:%S %p" Example: 09:34:17
PM for 21:34:17
Example: 00:35
%R Same as "%H:%M" for 12:35 AM,
16:44 for 4:44 PM
%S Two digit representation of the 00 through 59
second
%T Same as "%H:%M:%S" Example: 21:34:17
for 09:34:17 PM
%X Preferred time representation Example: 03:59:16
based on locale, without the date or 15:59:16
Either the time zone offset from Example: -0500 or
%z UTC or the abbreviation (depends EST for Eastern
on operating system) Time
The time zone offset/abbreviation Example: -0500 or
%Z option NOT given by %z (depends EST for Eastern
on operating system) Time
Time and Date --- ---
Stamps
Example: Tue Feb
Preferred date and time stamp 5 00:45:10 2009
%c based on local for February 5,
2009 at 12:45:10
AM
Example: 02/05/09
%D Same as "%m/%d/%y" for February 5,
2009
Same as "%Y-%m-%d" (commonly used Example:
%F in database datestamps) 2009-02-05 for
February 5, 2009
Example:
%s Unix Epoch Time timestamp (same 305815200 for
as the time() function) September 10,
1979 08:40:00 AM
Preferred date representation Example: 02/05/09
%x based on locale, without the time for February 5,
2009
Miscellaneous --- ---
%n A newline character ("\n") ---
%t A Tab character ("\t") ---
%% A literal percentage character ---
("%")
Maximum length of this parameter is 1023 characters.
Warning
Contrary to ISO-9899:1999, Sun Solaris starts with Sunday as 1. As
a result, %u may not function as described in this manual.
Warning
Windows only: The %e modifier is not supported in the Windows
implementation of this function. To achieve this value, the %#d
modifier can be used instead. The example below illustrates how to
write a cross platform compatible function.
Warning
Mac OS X only: The %P modifier is not supported in the Mac OS X
implementation of this function.
timestamp
The optional timestamp parameter is an integer Unix timestamp that
defaults to the current local time if a timestamp is not given. In
other words, it defaults to the value of time().
Return Values
Returns a string formatted according format using the given timestamp or
the current local time if no timestamp is given. Month and weekday names
and other language-dependent strings respect the current locale set with
setlocale().
Errors/Exceptions
Every call to a date/time function will generate a E_NOTICE if the time
zone is not valid, and/or a E_STRICT or E_WARNING message if using the
system settings or the TZ environment variable. See also
date_default_timezone_set()
As the output is dependent upon the underlying C library, some conversion
specifiers are not supported. On Windows, supplying unknown conversion
specifiers will result in 5 E_WARNING messages and return FALSE. On other
operating systems you may not get any E_WARNING messages and the output
may contain the conversion specifiers unconverted.
Changelog
Version Description
5.1.0 Now issues the E_STRICT and E_NOTICE time zone errors.
Examples
This example will work if you have the respective locales installed in
your system.
Example #1 strftime() locale examples
Example #2 ISO 8601:1988 week number example
Example #3 Cross platform compatible example using the %e modifier
Example #4 Display all known and unknown formats.
'A full textual representation of the day',
'B' => 'Full month name, based on the locale',
'C' => 'Two digit representation of the century (year divided by 100, truncated to an integer)',
'D' => 'Same as "%m/%d/%y"',
'E' => '',
'F' => 'Same as "%Y-%m-%d"',
'G' => 'The full four-digit version of %g',
'H' => 'Two digit representation of the hour in 24-hour format',
'I' => 'Two digit representation of the hour in 12-hour format',
'J' => '',
'K' => '',
'L' => '',
'M' => 'Two digit representation of the minute',
'N' => '',
'O' => '',
'P' => 'lower-case "am" or "pm" based on the given time',
'Q' => '',
'R' => 'Same as "%H:%M"',
'S' => 'Two digit representation of the second',
'T' => 'Same as "%H:%M:%S"',
'U' => 'Week number of the given year, starting with the first Sunday as the first week',
'V' => 'ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week',
'W' => 'A numeric representation of the week of the year, starting with the first Monday as the first week',
'X' => 'Preferred time representation based on locale, without the date',
'Y' => 'Four digit representation for the year',
'Z' => 'The time zone offset/abbreviation option NOT given by %z (depends on operating system)',
'a' => 'An abbreviated textual representation of the day',
'b' => 'Abbreviated month name, based on the locale',
'c' => 'Preferred date and time stamp based on local',
'd' => 'Two-digit day of the month (with leading zeros)',
'e' => 'Day of the month, with a space preceding single digits',
'f' => '',
'g' => 'Two digit representation of the year going by ISO-8601:1988 standards (see %V)',
'h' => 'Abbreviated month name, based on the locale (an alias of %b)',
'i' => '',
'j' => 'Day of the year, 3 digits with leading zeros',
'k' => '',
'l' => 'Hour in 12-hour format, with a space preceeding single digits',
'm' => 'Two digit representation of the month',
'n' => 'A newline character ("\n")',
'o' => '',
'p' => 'UPPER-CASE "AM" or "PM" based on the given time',
'q' => '',
'r' => 'Same as "%I:%M:%S %p"',
's' => 'Unix Epoch Time timestamp',
't' => 'A Tab character ("\t")',
'u' => 'ISO-8601 numeric representation of the day of the week',
'v' => '',
'w' => 'Numeric representation of the day of the week',
'x' => 'Preferred date representation based on locale, without the time',
'y' => 'Two digit representation of the year',
'z' => 'Either the time zone offset from UTC or the abbreviation (depends on operating system)',
'%' => 'A literal percentage character ("%")',
);
// Results.
$strftimeValues = array();
// Evaluate the formats whilst suppressing any errors.
foreach($strftimeFormats as $format => $description){
if (False !== ($value = @strftime("%{$format}"))){
$strftimeValues[$format] = $value;
}
}
// Find the longest value.
$maxValueLength = 2 + max(array_map('strlen', $strftimeValues));
// Report known formats.
foreach($strftimeValues as $format => $value){
echo "Known format : '{$format}' = ", str_pad("'{$value}'", $maxValueLength), " ( {$strftimeFormats[$format]} )\n";
}
// Report unknown formats.
foreach(array_diff_key($strftimeFormats, $strftimeValues) as $format => $description){
echo "Unknown format : '{$format}' ", str_pad(' ', $maxValueLength), ($description ? " ( {$description} )" : ''), "\n";
}
The above example will output something similar to:
Known format : 'A' = 'Friday' ( A full textual representation of the day )
Known format : 'B' = 'December' ( Full month name, based on the locale )
Known format : 'H' = '11' ( Two digit representation of the hour in 24-hour format )
Known format : 'I' = '11' ( Two digit representation of the hour in 12-hour format )
Known format : 'M' = '24' ( Two digit representation of the minute )
Known format : 'S' = '44' ( Two digit representation of the second )
Known format : 'U' = '48' ( Week number of the given year, starting with the first Sunday as the first week )
Known format : 'W' = '48' ( A numeric representation of the week of the year, starting with the first Monday as the first week )
Known format : 'X' = '11:24:44' ( Preferred time representation based on locale, without the date )
Known format : 'Y' = '2010' ( Four digit representation for the year )
Known format : 'Z' = 'GMT Standard Time' ( The time zone offset/abbreviation option NOT given by %z (depends on operating system) )
Known format : 'a' = 'Fri' ( An abbreviated textual representation of the day )
Known format : 'b' = 'Dec' ( Abbreviated month name, based on the locale )
Known format : 'c' = '12/03/10 11:24:44' ( Preferred date and time stamp based on local )
Known format : 'd' = '03' ( Two-digit day of the month (with leading zeros) )
Known format : 'j' = '337' ( Day of the year, 3 digits with leading zeros )
Known format : 'm' = '12' ( Two digit representation of the month )
Known format : 'p' = 'AM' ( UPPER-CASE "AM" or "PM" based on the given time )
Known format : 'w' = '5' ( Numeric representation of the day of the week )
Known format : 'x' = '12/03/10' ( Preferred date representation based on locale, without the time )
Known format : 'y' = '10' ( Two digit representation of the year )
Known format : 'z' = 'GMT Standard Time' ( Either the time zone offset from UTC or the abbreviation (depends on operating system) )
Known format : '%' = '%' ( A literal percentage character ("%") )
Unknown format : 'C' ( Two digit representation of the century (year divided by 100, truncated to an integer) )
Unknown format : 'D' ( Same as "%m/%d/%y" )
Unknown format : 'E'
Unknown format : 'F' ( Same as "%Y-%m-%d" )
Unknown format : 'G' ( The full four-digit version of %g )
Unknown format : 'J'
Unknown format : 'K'
Unknown format : 'L'
Unknown format : 'N'
Unknown format : 'O'
Unknown format : 'P' ( lower-case "am" or "pm" based on the given time )
Unknown format : 'Q'
Unknown format : 'R' ( Same as "%H:%M" )
Unknown format : 'T' ( Same as "%H:%M:%S" )
Unknown format : 'V' ( ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week )
Unknown format : 'e' ( Day of the month, with a space preceding single digits )
Unknown format : 'f'
Unknown format : 'g' ( Two digit representation of the year going by ISO-8601:1988 standards (see %V) )
Unknown format : 'h' ( Abbreviated month name, based on the locale (an alias of %b) )
Unknown format : 'i'
Unknown format : 'k'
Unknown format : 'l' ( Hour in 12-hour format, with a space preceeding single digits )
Unknown format : 'n' ( A newline character ("\n") )
Unknown format : 'o'
Unknown format : 'q'
Unknown format : 'r' ( Same as "%I:%M:%S %p" )
Unknown format : 's' ( Unix Epoch Time timestamp )
Unknown format : 't' ( A Tab character ("\t") )
Unknown format : 'u' ( ISO-8601 numeric representation of the day of the week )
Unknown format : 'v'
Notes
Note: %G and %V, which are based on ISO 8601:1988 week numbers can give
unexpected (albeit correct) results if the numbering system is not
thoroughly understood. See %V examples in this manual page.
See Also
* setlocale() - Set locale information
* mktime() - Get Unix timestamp for a date
* strptime() - Parse a time/date generated with strftime
* gmstrftime() - Format a GMT/UTC time/date according to locale settings
* >> Open Group specification of strftime()
----------------------------------------------------------------------
----------------------------------------------------------------------
strptime
(PHP 5 >= 5.1.0)
strptime - Parse a time/date generated with strftime()
Description
array strptime ( string $date , string $format )
strptime() returns an array with the date parsed, or FALSE on error.
Month and weekday names and other language dependent strings respect the
current locale set with setlocale() (LC_TIME).
Parameters
date (string)
The string to parse (e.g. returned from strftime()).
format (string)
The format used in date (e.g. the same as used in strftime()).
Note that some of the format options available to strftime() may
not have any effect within strptime(); the exact subset that are
supported will vary based on the operating system and C library in
use.
For more information about the format options, read the strftime()
page.
Return Values
Returns an array or FALSE on failure.
The following parameters are returned in the array
parameters Description
"tm_sec" Seconds after the minute (0-61)
"tm_min" Minutes after the hour (0-59)
"tm_hour" Hour since midnight (0-23)
"tm_mday" Day of the month (1-31)
"tm_mon" Months since January (0-11)
"tm_year" Years since 1900
"tm_wday" Days since Sunday (0-6)
"tm_yday" Days since January 1 (0-365)
"unparsed" the date part which was not recognized using the specified
format
Examples
Example #1 strptime() example
The above example will output something similar to:
03/10/2004 15:54:19
Array
(
[tm_sec] => 19
[tm_min] => 54
[tm_hour] => 15
[tm_mday] => 3
[tm_mon] => 9
[tm_year] => 104
[tm_wday] => 0
[tm_yday] => 276
[unparsed] =>
)
Notes
Note: This function is not implemented on Windows platforms.
Note:
Internally, this function calls the strptime() function provided by the
system's C library. This function can exhibit noticeably different
behaviour across different operating systems. The use of
date_parse_from_format(), which does not suffer from these issues, is
recommended on PHP 5.3.0 and later.
Note:
"tm_sec" includes any leap seconds (currently upto 2 a year). For more
information on leap seconds, see the >> Wikipedia article on leap
seconds.
Note:
Prior to PHP 5.2.0, this function could return undefined behaviour.
Notably, the "tm_sec", "tm_min" and "tm_hour" entries would return
undefined values.
See Also
* checkdate() - Validate a Gregorian date
* strftime() - Format a local time/date according to locale settings
----------------------------------------------------------------------
----------------------------------------------------------------------
strtotime
(PHP 4, PHP 5)
strtotime - Parse about any English textual datetime description into a
Unix timestamp
Description
int strtotime ( string $time [, int $now ] )
The function expects to be given a string containing an English date
format and will try to parse that format into a Unix timestamp (the number
of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp
given in now, or the current time if now is not supplied.
This function will use the TZ environment variable (if available) to
calculate the timestamp. Since PHP 5.1.0 there are easier ways to define
the timezone that is used across all date/time functions. That process is
explained in the date_default_timezone_get() function page.
Parameters
time
A date/time string. Valid formats are explained in Date and Time
Formats.
now
The timestamp which is used as a base for the calculation of
relative dates.
Return Values
Returns a timestamp on success, FALSE otherwise. Previous to PHP 5.1.0,
this function would return -1 on failure.
Errors/Exceptions
Every call to a date/time function will generate a E_NOTICE if the time
zone is not valid, and/or a E_STRICT or E_WARNING message if using the
system settings or the TZ environment variable. See also
date_default_timezone_set()
Changelog
Version Description
5.3.0 Prior to PHP 5.3.0, 24:00 was not a valid format and strtotime()
returned FALSE.
In PHP 5 prior to 5.2.7, requesting a given occurrence of a given
5.2.7 weekday in a month where that weekday was the first day of the
month would incorrectly add one week to the returned timestamp.
This has been corrected in 5.2.7 and later versions.
5.1.0 Now returns FALSE on failure, instead of -1.
5.1.0 Now issues the E_STRICT and E_NOTICE time zone errors.
In PHP 5 up to 5.0.2, "now" and other relative times are wrongly
5.0.2 computed from today's midnight. This differs from other versions
where it is correctly computed from current time.
5.0.0 Microseconds began to be allowed, but they are ignored.
4.4.0 In PHP versions prior to 4.4.0, "next" is incorrectly computed as
+2. A typical solution to this is to use "+1".
Examples
Example #1 A strtotime() example
Example #2 Checking for failure
Notes
Note:
If the number of the year is specified in a two digit format, the values
between 00-69 are mapped to 2000-2069 and 70-99 to 1970-1999. See the
notes below for possible differences on 32bit systems (possible dates
might end on 2038-01-19 03:14:07).
Note:
The valid range of a timestamp is typically from Fri, 13 Dec 1901
20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC. (These are the dates that
correspond to the minimum and maximum values for a 32-bit signed
integer.) Additionally, not all platforms support negative timestamps,
therefore your date range may be limited to no earlier than the Unix
epoch. This means that e.g. dates prior to Jan 1, 1970 will not work on
Windows, some Linux distributions, and a few other operating systems.
PHP 5.1.0 and newer versions overcome this limitation though.
For 64-bit versions of PHP, the valid range of a timestamp is
effectively infinite, as 64 bits can represent approximately 293 billion
years in either direction.
Note:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the
separator between the various components: if the separator is a slash
(/), then the American m/d/y is assumed; whereas if the separator is a
dash (-) or a dot (.), then the European d-m-y format is assumed.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD)
dates or DateTime::createFromFormat() when possible.
See Also
* DateTime::createFromFormat() - Returns new DateTime object formatted
according to the specified format
* checkdate() - Validate a Gregorian date
* strptime() - Parse a time/date generated with strftime
----------------------------------------------------------------------
----------------------------------------------------------------------
time
(PHP 4, PHP 5)
time - Return current Unix timestamp
Description
int time ( void )
Returns the current time measured in the number of seconds since the Unix
Epoch (January 1 1970 00:00:00 GMT).
Examples
Example #1 time() example
The above example will output something similar to:
Now: 2005-03-30
Next Week: 2005-04-06
Next Week: 2005-04-06
Notes
Tip
Timestamp of the start of the request is available in
$_SERVER['REQUEST_TIME'] since PHP 5.1.
See Also
* date() - Format a local time/date
* microtime() - Return current Unix timestamp with microseconds
----------------------------------------------------------------------
----------------------------------------------------------------------
timezone_abbreviations_list
(PHP 5 >= 5.2.0)
timezone_abbreviations_list - Alias of DateTimeZone::listAbbreviations()
Description
This function is an alias of: DateTimeZone::listAbbreviations()
----------------------------------------------------------------------
----------------------------------------------------------------------
timezone_identifiers_list
(PHP 5 >= 5.2.0)
timezone_identifiers_list - Alias of DateTimeZone::listIdentifiers()
Description
This function is an alias of: DateTimeZone::listIdentifiers()
----------------------------------------------------------------------
----------------------------------------------------------------------
timezone_location_get
(PHP 5 >= 5.3.0)
timezone_location_get - Alias of DateTimeZone::getLocation()
Description
This function is an alias of: DateTimeZone::getLocation()
----------------------------------------------------------------------
----------------------------------------------------------------------
timezone_name_from_abbr
(PHP 5 >= 5.1.3)
timezone_name_from_abbr - Returns the timezone name from abbreviation
Description
string timezone_name_from_abbr ( string $abbr [, int $gmtOffset = -1 [,
int $isdst = -1 ]] )
Parameters
abbr
Time zone abbreviation.
gmtOffset
Offset from GMT in seconds. Defaults to -1 which means that first
found time zone corresponding to abbr is returned. Otherwise exact
offset is searched and only if not found then the first time zone
with any offset is returned.
isdst
Daylight saving time indicator. Defaults to -1, which means that
whether the time zone has daylight saving or not is not taken into
consideration when searching. If this is set to 1, then the
gmtOffset is assumed to be an offset with daylight saving in
effect; if 0, then gmtOffset is assumed to be an offset without
daylight saving in effect. If abbr doesn't exist then the time
zone is searched solely by the gmtOffset and isdst.
Return Values
Returns time zone name on success or FALSE on failure.
Examples
Example #1 A timezone_name_from_abbr() example
The above example will output something similar to:
Europe/Berlin
Europe/Paris
See Also
* timezone_abbreviations_list() - Alias of
DateTimeZone::listAbbreviations
----------------------------------------------------------------------
----------------------------------------------------------------------
timezone_name_get
(PHP 5 >= 5.2.0)
timezone_name_get - Alias of DateTimeZone::getName()
Description
This function is an alias of: DateTimeZone::getName()
----------------------------------------------------------------------
----------------------------------------------------------------------
timezone_offset_get
(PHP 5 >= 5.2.0)
timezone_offset_get - Alias of DateTimeZone::getOffset()
Description
This function is an alias of: DateTimeZone::getOffset()
----------------------------------------------------------------------
----------------------------------------------------------------------
timezone_open
(PHP 5 >= 5.2.0)
timezone_open - Alias of DateTimeZone::__construct()
Description
This function is an alias of: DateTimeZone::__construct()
----------------------------------------------------------------------
----------------------------------------------------------------------
timezone_transitions_get
(PHP 5 >= 5.2.0)
timezone_transitions_get - Alias of DateTimeZone::getTransitions()
Description
This function is an alias of: DateTimeZone::getTransitions()
----------------------------------------------------------------------
----------------------------------------------------------------------
timezone_version_get
(PHP 5 >= 5.3.0)
timezone_version_get - Gets the version of the timezonedb
Description
string timezone_version_get ( void )
Returns the current version of the timezonedb.
Return Values
Returns a string.
Examples
Example #1 Getting the timezonedb version
The above example will output something similar to:
2009.7
See Also
* List of Supported Timezones
----------------------------------------------------------------------
Table of Contents
* checkdate - Validate a Gregorian date
* date_add - Alias of DateTime::add
* date_create_from_format - Alias of DateTime::createFromFormat
* date_create - Alias of DateTime::__construct
* date_date_set - Alias of DateTime::setDate
* date_default_timezone_get - Gets the default timezone used by all
date/time functions in a script
* date_default_timezone_set - Sets the default timezone used by all
date/time functions in a script
* date_diff - Alias of DateTime::diff
* date_format - Alias of DateTime::format
* date_get_last_errors - Alias of DateTime::getLastErrors
* date_interval_create_from_date_string - Alias of
DateInterval::createFromDateString
* date_interval_format - Alias of DateInterval::format
* date_isodate_set - Alias of DateTime::setISODate
* date_modify - Alias of DateTime::modify
* date_offset_get - Alias of DateTime::getOffset
* date_parse_from_format - Get info about given date formatted according
to the specified format
* date_parse - Returns associative array with detailed info about given
date
* date_sub - Alias of DateTime::sub
* date_sun_info - Returns an array with information about sunset/sunrise
and twilight begin/end
* date_sunrise - Returns time of sunrise for a given day and location
* date_sunset - Returns time of sunset for a given day and location
* date_time_set - Alias of DateTime::setTime
* date_timestamp_get - Alias of DateTime::getTimestamp
* date_timestamp_set - Alias of DateTime::setTimestamp
* date_timezone_get - Alias of DateTime::getTimezone
* date_timezone_set - Alias of DateTime::setTimezone
* date - Format a local time/date
* getdate - Get date/time information
* gettimeofday - Get current time
* gmdate - Format a GMT/UTC date/time
* gmmktime - Get Unix timestamp for a GMT date
* gmstrftime - Format a GMT/UTC time/date according to locale settings
* idate - Format a local time/date as integer
* localtime - Get the local time
* microtime - Return current Unix timestamp with microseconds
* mktime - Get Unix timestamp for a date
* strftime - Format a local time/date according to locale settings
* strptime - Parse a time/date generated with strftime
* strtotime - Parse about any English textual datetime description into
a Unix timestamp
* time - Return current Unix timestamp
* timezone_abbreviations_list - Alias of DateTimeZone::listAbbreviations
* timezone_identifiers_list - Alias of DateTimeZone::listIdentifiers
* timezone_location_get - Alias of DateTimeZone::getLocation
* timezone_name_from_abbr - Returns the timezone name from abbreviation
* timezone_name_get - Alias of DateTimeZone::getName
* timezone_offset_get - Alias of DateTimeZone::getOffset
* timezone_open - Alias of DateTimeZone::__construct
* timezone_transitions_get - Alias of DateTimeZone::getTransitions
* timezone_version_get - Gets the version of the timezonedb
----------------------------------------------------------------------
----------------------------------------------------------------------
Supported Date and Time Formats
Table of Contents
* Time Formats
* Date Formats
* Compound Formats
* Relative Formats
This section describes all the different formats that the strtotime(),
DateTime and date_create() parser understands. The formats are grouped by
section. In most cases formats from different sections can be used in the
same date/time string. For each of the supported formats, one or more
examples are given, as well as a description for the format. Characters in
single quotes in the formats are case-insensitive ('t' could be t or T),
characters in double quotes are case-sensitive ("T" is only T).
----------------------------------------------------------------------
Time Formats
Used Symbols
Description Formats Examples
frac . [0-9]+ ".21342", ".85"
hh "0"?[1-9] | "1"[0-2] "04", "7", "12"
HH [01][0-9] | "2"[0-4] "04", "7", "19"
meridian [AaPp] .? [Mm] .? [\0\t ] "A.m.", "pM", "am."
MM [0-5][0-9] "00", "12", "59"
II [0-5][0-9] "00", "12", "59"
space [ \t]
"("? [A-Za-z]{1,6} ")"? | "CEST",
tz [A-Z][a-z]+([_/][A-Z][a-z]+)+ "Europe/Amsterdam",
"America/Indiana/Knox"
tzcorrection "GMT"? [+-] hh ":"? MM? "+0400", "GMT-07:00",
"-07:00"
12 Hour Notation
Description Format Examples
Hour only, with meridian hh space? meridian "4 am", "5PM"
Hour and minutes, with meridian hh [.:] MM space? "4:08 am", "7:19P.M."
meridian
Hour, minutes and seconds, with hh [.:] MM [.:] II "4:08:37 am",
meridian space? meridian "7:19:19P.M."
MS SQL (Hour, minutes, seconds hh ":" MM ":" II
and fraction with meridian), PHP [.:] [0-9]+ "4:08:39:12313am"
5.3 and later only meridian
24 Hour Notation
Description Format Examples
Hour and minutes 't'? HH [.:] MM "04:08", "19.19", "T23:43"
Hour and minutes, no 't'? HH MM "0408", "t1919", "T2343"
colon
Hour, minutes and 't'? HH [.:] MM [.:] II "04.08.37", "t19:19:19"
seconds
Hour, minutes and 't'? HH MM II "040837", "T191919"
seconds, no colon
Hour, minutes, 't'? HH [.:] MM [.:] II
seconds and timezone space? ( tzcorrection | "040837CEST", "T191919-0700"
tz )
Hour, minutes, 't'? HH [.:] MM [.:] II "04.08.37.81412",
seconds and fraction frac "19:19:19.532453"
Time zone tz | tzcorrection "CEST", "Europe/Amsterdam",
information "+0430", "GMT-06:00"
----------------------------------------------------------------------
----------------------------------------------------------------------
Date Formats
Used Symbols
Description Format Examples
daysuf "st" | "nd" | "rd" | "th"
dd ([0-2]?[0-9] | "3"[01]) daysuf? "7th", "22nd",
"31"
DD "0" [0-9] | [1-2][0-9] | "3" [01] "07", "31"
'january' | 'february' | 'march' | 'april' |
'may' | 'june' | 'july' | 'august' |
'september' | 'october' | 'november' |
m 'december' | 'jan' | 'feb' | 'mar' | 'apr' |
'may' | 'jun' | 'jul' | 'aug' | 'sep' |
'sept' | 'oct' | 'nov' | 'dec' | "I" | "II"
| "III" | "IV" | "V" | "VI" | "VII" | "VIII"
| "IX" | "X" | "XI" | "XII"
'jan' | 'feb' | 'mar' | 'apr' | 'may' |
M 'jun' | 'jul' | 'aug' | 'sep' | 'sept' |
'oct' | 'nov' | 'dec'
mm "0"? [0-9] | "1"[0-2] "0", "04", "7",
"12"
MM "0" [0-9] | "1"[0-2] "00", "04", "07",
"12"
y [0-9]{1,4} "00", "78", "08",
"8", "2008"
yy [0-9]{2} "00", "08", "78"
YY [0-9]{4} "2000", "2008",
"1978"
Localized Notations
Description Format Examples
American month and day mm "/" dd "5/12", "10/27"
American month, day and year mm "/" dd "/" y "12/22/78", "1/17/2006",
"1/17/6"
Four digit year, month and YY "/" mm "/" dd "2008/6/30",
day with slashes "1978/12/22"
Four digit year and month YY "-" mm "2008-6", "2008-06",
(GNU) "1978-12"
Year, month and day with y "-" mm "-" dd "2008-6-30", "78-12-22",
dashes "8-6-21"
Day, month and four digit "30-6-2008",
year, with dots, tabs or dd [.\t-] mm [.-] YY "22.12\t1978"
dashes
Day, month and two digit dd [.\t] mm "." yy "30.6.08", "22\t12\t78"
year, with dots or tabs
Day, textual month and year dd ([ \t.-])* m ([ "30-June 2008",
\t.-])* y "22DEC78", "14 III 1879"
Textual month and four digit m ([ \t.-])* YY "June 2008", "DEC1978",
year (Day reset to 1) "March 1879"
Four digit year and textual YY ([ \t.-])* m "2008 June", "1978-XII",
month (Day reset to 1) "1879.MArCH"
Textual month, day and year m ([ .\t-])* dd "July 1st, 2008", "April
[,.stndrh\t ]+ y 17, 1790", "May.9,78"
Textual month and day m ([ .\t-])* dd "July 1st,", "Apr 17",
[,.stndrh\t ]* "May.9"
Day and textual month d ([ .\t-])* m "1 July", "17 Apr",
"9.May"
Month abbreviation, day and M "-" DD "-" y "May-09-78",
year "Apr-17-1790"
Year, month abbreviation and y "-" M "-" DD "78-Dec-22",
day "1814-MAY-17"
Year (and just the year) YY "1978", "2008"
Textual month (and just the m "March", "jun", "DEC"
month)
ISO8601 Notations
Description Format Examples
Eight digit year, month and YY MM DD "15810726", "19780417",
day "18140517"
Four digit year, month and YY "/" MM "/" DD "2008/06/30", "1978/12/22"
day with slashes
Two digit year, month and day yy "-" MM "-" DD "08-06-30", "78-12-22"
with dashes
Four digit year with optional [+-]? YY "-" MM "-0002-07-26",
sign, month and day "-" DD "+1978-04-17", "1814-05-17"
Note:
For the y and yy formats, years below 100 are handled in a special way
when the y or yy symbol is used. If the year falls in the range 0
(inclusive) to 69 (inclusive), 2000 is added. If the year falls in the
range 70 (inclusive) to 99 (inclusive) then 1900 is added. This means
that "00-01-01" is interpreted as "2000-01-01".
Note:
The "Day, month and two digit year, with dots or tabs" format (dd [.\t]
mm "." yy) only works for the year values 61 (inclusive) to 99
(inclusive) - outside those years the time format "HH [.:] MM [.:] SS"
has precedence.
Note:
The "Year (and just the year)" format only works if a time string has
already been found -- otherwise this format is recognised as HH MM.
Note:
It is possible to over- and underflow the dd and DD format. Day 0 means
the last day of previous month, whereas overflows count into the next
month. This makes "2008-08-00" equivalent to "2008-07-31" and
"2008-06-31" equivalent to "2008-07-01" (June only has 30 days).
It is also possible to underflow the mm and MM formats with the value 0.
A month value of 0 means December of the previous year. As example
"2008-00-22" is equivalent to "2007-12-22".
If you combine the previous two facts and underflow both the day and the
month, the following happens: "2008-00-00" first gets converted to
"2007-12-00" which then gets converted to "2007-11-30". This also
happens with the string "0000-00-00", which gets transformed into
"-0001-11-30" (the year -1 in the ISO 8601 calendar, which is 2 BC in
the proleptic Gregorian calendar).
----------------------------------------------------------------------
----------------------------------------------------------------------
Compound Formats
Used Symbols
Description Formats Examples
DD "0" [0-9] | [1-2][0-9] | "3" [01] "02", "12", "31"
"00"[1-9] | "0"[1-9][0-9] | "36"[0-6] "000",
doy [1-2][0-9][0-9] | "3"[0-5][0-9] | "012", "366"
"36"[0-6]
frac . [0-9]+ ".21342", ".85"
hh "0"?[1-9] | "1"[0-2] "04", "7", "12"
HH [01][0-9] | "2"[0-4] "04", "7", "19"
meridian [AaPp] .? [Mm] .? [\0\t ] "A.m.", "pM", "am."
ii [0-5][0-9] "04", "8", "59"
II [0-5][0-9] "04", "08", "59"
'jan' | 'feb' | 'mar' | 'apr' | 'may'
M | 'jun' | 'jul' | 'aug' | 'sep' |
'sept' | 'oct' | 'nov' | 'dec'
MM [0-5][0-9] "00", "12", "59"
space [ \t]
ss [0-5][0-9] "04", "8", "59"
SS [0-5][0-9] "04", "08", "59"
W "0"[1-9] | [1-4][0-9] | "5"[0-3] "05", "17", "53"
tzcorrection "GMT"? [+-] hh ":"? MM? "+0400", "GMT-07:00",
"-07:00"
YY [0-9]{4} "2000", "2008", "1978"
Localized Notations
Description Format Examples
Common Log dd "/" M "/" YY : HH
Format ":" II ":" SS space "10/Oct/2000:13:55:36 -0700"
tzcorrection
EXIF YY ":" MM ":" DD " " "2008:08:07 18:11:31"
HH ":" II ":" SS
ISO year with YY "-"? "W" W "2008W27", "2008-W28"
ISO week
ISO year with YY "-"? "W" W "-"? "2008W273", "2008-W28-3"
ISO week and day [0-7]
MySQL YY "-" MM "-" DD " " "2008-08-07 18:11:31"
HH ":" II ":" SS
PostgreSQL: Year YY "."? doy "2008.197", "2008197"
with day-of-year
YY "-" MM "-" DD "T" "2008-07-01T22:35:17.02",
SOAP HH ":" II ":" SS "2008-07-01T22:35:17.03+08:00"
frac tzcorrection?
Unix Timestamp "@" "-"? [0-9]+ "@1215282385"
XMLRPC YY MM DD "T" hh ":" "20080701T22:38:07",
II ":" SS "20080701T9:38:07"
XMLRPC (Compact) YY MM DD 't' hh II "20080701t223807", "20080701T093807"
SS
WDDX YY "-" mm "-" dd "T" "2008-7-1T9:3:37"
hh ":" ii ":" ss
Note:
The "W" in the "ISO year with ISO week" and "ISO year with ISO week and
day" formats is case-sensitive, you can only use the upper case "W".
The "T" in the SOAP, XMRPC and WDDX formats is case-sensitive, you can
only use the upper case "T".
----------------------------------------------------------------------
----------------------------------------------------------------------
Relative Formats
Used Symbols
Description Format
'sunday' | 'monday' | 'tuesday' | 'wednesday' | 'thursday' |
dayname 'friday' | 'saturday' | 'sun' | 'mon' | 'tue' | 'wed' | 'thu'
| 'fri' | 'sat' | 'sun'
daytext 'weekday' | 'weekdays'
number [+-]?[0-9]+
'first' | 'second' | 'third' | 'fourth' | 'fifth' | 'sixth' |
ordinal 'seventh' | 'eighth' | 'ninth' | 'tenth' | 'eleventh' |
'twelfth' | 'next' | 'last' | 'previous' | 'this'
reltext 'next' | 'last' | 'previous' | 'this'
space [ \t]+
(('sec' | 'second' | 'min' | 'minute' | 'hour' | 'day' |
unit 'fortnight' | 'forthnight' | 'month' | 'year') 's'?) | 'weeks'
| daytext
Day-based Notations
Format Description Examples
'yesterday' Midnight of yesterday "yesterday 14:00"
'midnight' The time is set to 00:00:00
'today' The time is set to 00:00:00
'now' Now - this is simply ignored
'noon' The time is set to 12:00:00 "yesterday noon"
'tomorrow' Midnight of tomorrow
'back of' hour 15 minutes past the specified "back of 7pm", "back of
hour 15"
'front of' hour 15 minutes before the "front of 5am", "front
specified hour of 23"
Sets the day of the first of
'first day' ' of'? the current month. This phrase "first day of January
is best used together with a 2008"
month name following it.
Sets the day to the last day
of the current month. This "last day of next
'last day' ' of'? phrase is best used together month"
with a month name following
it.
ordinal space Calculates the x-th week day "first sat of July
dayname space 'of' of the current month. 2008"
'last' space Calculates the last week day "last sat of July 2008"
dayname space 'of' of the current month.
number space? (unit Handles relative time items "+5 weeks", "12 day",
| 'week') where the value is a number. "-7 weekdays"
ordinal space unit Handles relative time items "fifth day", "second
where the value is text. month"
"2 days ago", "8 days
Negates all the values of ago 14:00", "2 months 5
'ago' previously found relative time days ago", "2 months
items. ago 5 days", "2 days
ago ago"
dayname Moves to the next day of this "Monday"
name.
reltext space Handles the special format
'week' "weekday + last/this/next "Monday next week"
week".
Note:
Relative statements are always processed after non-relative statements.
This makes "+1 week july 2008" and "july 2008 +1 week" equivalent.
Exceptions to this rule are: "yesterday", "midnight", "today", "noon"
and "tomorrow". Note that "tomorrow 11:00" and "11:00 tomorrow" are
different. Considering today's date of "July 23rd, 2008" the first one
produces "2008-07-24 11:00" where as the second one produces "2008-07-24
00:00". The reason for this is that those five statements directly
influence the current time.
Note:
Observe the following remarks when the current day-of-week is the same
as the day-of-week used in the date/time string. The current day-of-week
could have been (re-)calculated by non-relative parts of the date/time
string however.
1. "dayname" does not advance to another day. (Example: "Wed July 23rd,
2008" means "2008-07-23").
2. "number dayname" does not advance to another day. (Example: "1
wednesday july 23rd, 2008" means "2008-07-23").
3. "number week dayname" will first add the number of weeks, but does
not advance to another day. In this case "number week" and "dayname"
are two distinct blocks. (Example: "+1 week wednesday july 23rd,
2008" means "2008-07-30").
4. "ordinal dayname" does advance to another day. (Example "first
wednesday july 23rd, 2008" means "2008-07-30").
5. "number week ordinal dayname" will first add the number of weeks,
and then advances to another day. In this case "number week" and
"ordinal dayname" are two distinct blocks. (Example: "+1 week first
wednesday july 23rd, 2008" means "2008-08-06").
6. "ordinal dayname does does advance to another day. (Example "first
wednesday july 23rd, 2008" means "2008-07-30").
7. "ordinal dayname 'of' " does not advance to another day. (Example:
"first wednesday of july 23rd, 2008" means "2008-07-02" because the
specific phrase with 'of' resets the day-of-month to '1' and the
'23rd' is ignored here).
Also observe that the "of" in "ordinal space dayname space 'of' " and
"'last' space dayname space 'of' " does something special.
1. It sets the day-of-month to 1.
2. "ordinal dayname 'of' " does not advance to another day. (Example:
"first tuesday of july 2008" means "2008-07-01").
3. "ordinal dayname " does advance to another day. (Example: "first
tuesday july 2008" means "2008-07-08", see also point 4 in the list
above).
4. "'last' dayname 'of' " takes the last dayname of the current month.
(Example: "last wed of july 2008" means "2008-07-30")
5. "'last' dayname" takes the last dayname from the current day.
(Example: "last wed july 2008" means "2008-06-25"; "july 2008" first
sets the current date to "2008-07-01" and then "last wed" moves to
the previous Wednesday which is "2008-06-25").
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
List of Supported Timezones
Table of Contents
* Africa
* America
* Antarctica
* Arctic
* Asia
* Atlantic
* Australia
* Europe
* Indian
* Pacific
* Others
Here you'll find the complete list of timezones supported by PHP, which
are meant to be used with e.g. date_default_timezone_set().
Note: The latest version of the timezone database can be installed via
PECL's >> timezonedb.
Note: This list is based upon the timezone database version 2011.8.
----------------------------------------------------------------------
Africa
Africa
Africa/Abidjan Africa/Accra Africa/Addis_Ababa Africa/Algiers Africa/Asmara
Africa/Asmera Africa/Bamako Africa/Bangui Africa/Banjul Africa/Bissau
Africa/Blantyre Africa/Brazzaville Africa/Bujumbura Africa/Cairo Africa/Casablanca
Africa/Ceuta Africa/Conakry Africa/Dakar Africa/Dar_es_Salaam Africa/Djibouti
Africa/Douala Africa/El_Aaiun Africa/Freetown Africa/Gaborone Africa/Harare
Africa/Johannesburg Africa/Kampala Africa/Khartoum Africa/Kigali Africa/Kinshasa
Africa/Lagos Africa/Libreville Africa/Lome Africa/Luanda Africa/Lubumbashi
Africa/Lusaka Africa/Malabo Africa/Maputo Africa/Maseru Africa/Mbabane
Africa/Mogadishu Africa/Monrovia Africa/Nairobi Africa/Ndjamena Africa/Niamey
Africa/Nouakchott Africa/Ouagadougou Africa/Porto-Novo Africa/Sao_Tome Africa/Timbuktu
Africa/Tripoli Africa/Tunis Africa/Windhoek
----------------------------------------------------------------------
----------------------------------------------------------------------
America
America
America/Adak America/Anchorage America/Anguilla America/Antigua America/Araguaina
America/Argentina/Buenos_Aires America/Argentina/Catamarca America/Argentina/ComodRivadavia America/Argentina/Cordoba America/Argentina/Jujuy
America/Argentina/La_Rioja America/Argentina/Mendoza America/Argentina/Rio_Gallegos America/Argentina/Salta America/Argentina/San_Juan
America/Argentina/San_Luis America/Argentina/Tucuman America/Argentina/Ushuaia America/Aruba America/Asuncion
America/Atikokan America/Atka America/Bahia America/Bahia_Banderas America/Barbados
America/Belem America/Belize America/Blanc-Sablon America/Boa_Vista America/Bogota
America/Boise America/Buenos_Aires America/Cambridge_Bay America/Campo_Grande America/Cancun
America/Caracas America/Catamarca America/Cayenne America/Cayman America/Chicago
America/Chihuahua America/Coral_Harbour America/Cordoba America/Costa_Rica America/Cuiaba
America/Curacao America/Danmarkshavn America/Dawson America/Dawson_Creek America/Denver
America/Detroit America/Dominica America/Edmonton America/Eirunepe America/El_Salvador
America/Ensenada America/Fort_Wayne America/Fortaleza America/Glace_Bay America/Godthab
America/Goose_Bay America/Grand_Turk America/Grenada America/Guadeloupe America/Guatemala
America/Guayaquil America/Guyana America/Halifax America/Havana America/Hermosillo
America/Indiana/Indianapolis America/Indiana/Knox America/Indiana/Marengo America/Indiana/Petersburg America/Indiana/Tell_City
America/Indiana/Vevay America/Indiana/Vincennes America/Indiana/Winamac America/Indianapolis America/Inuvik
America/Iqaluit America/Jamaica America/Jujuy America/Juneau America/Kentucky/Louisville
America/Kentucky/Monticello America/Knox_IN America/Kralendijk America/La_Paz America/Lima
America/Los_Angeles America/Louisville America/Lower_Princes America/Maceio America/Managua
America/Manaus America/Marigot America/Martinique America/Matamoros America/Mazatlan
America/Mendoza America/Menominee America/Merida America/Metlakatla America/Mexico_City
America/Miquelon America/Moncton America/Monterrey America/Montevideo America/Montreal
America/Montserrat America/Nassau America/New_York America/Nipigon America/Nome
America/Noronha America/North_Dakota/Beulah America/North_Dakota/Center America/North_Dakota/New_Salem America/Ojinaga
America/Panama America/Pangnirtung America/Paramaribo America/Phoenix America/Port-au-Prince
America/Port_of_Spain America/Porto_Acre America/Porto_Velho America/Puerto_Rico America/Rainy_River
America/Rankin_Inlet America/Recife America/Regina America/Resolute America/Rio_Branco
America/Rosario America/Santa_Isabel America/Santarem America/Santiago America/Santo_Domingo
America/Sao_Paulo America/Scoresbysund America/Shiprock America/Sitka America/St_Barthelemy
America/St_Johns America/St_Kitts America/St_Lucia America/St_Thomas America/St_Vincent
America/Swift_Current America/Tegucigalpa America/Thule America/Thunder_Bay America/Tijuana
America/Toronto America/Tortola America/Vancouver America/Virgin America/Whitehorse
America/Winnipeg America/Yakutat America/Yellowknife
----------------------------------------------------------------------
----------------------------------------------------------------------
Antarctica
Antarctica
Antarctica/Casey Antarctica/Davis Antarctica/DumontDUrville Antarctica/Macquarie Antarctica/Mawson
Antarctica/McMurdo Antarctica/Palmer Antarctica/Rothera Antarctica/South_Pole Antarctica/Syowa
Antarctica/Vostok
----------------------------------------------------------------------
----------------------------------------------------------------------
Arctic
Arctic
Arctic/Longyearbyen
----------------------------------------------------------------------
----------------------------------------------------------------------
Asia
Asia
Asia/Aden Asia/Almaty Asia/Amman Asia/Anadyr Asia/Aqtau
Asia/Aqtobe Asia/Ashgabat Asia/Ashkhabad Asia/Baghdad Asia/Bahrain
Asia/Baku Asia/Bangkok Asia/Beirut Asia/Bishkek Asia/Brunei
Asia/Calcutta Asia/Choibalsan Asia/Chongqing Asia/Chungking Asia/Colombo
Asia/Dacca Asia/Damascus Asia/Dhaka Asia/Dili Asia/Dubai
Asia/Dushanbe Asia/Gaza Asia/Harbin Asia/Ho_Chi_Minh Asia/Hong_Kong
Asia/Hovd Asia/Irkutsk Asia/Istanbul Asia/Jakarta Asia/Jayapura
Asia/Jerusalem Asia/Kabul Asia/Kamchatka Asia/Karachi Asia/Kashgar
Asia/Kathmandu Asia/Katmandu Asia/Kolkata Asia/Krasnoyarsk Asia/Kuala_Lumpur
Asia/Kuching Asia/Kuwait Asia/Macao Asia/Macau Asia/Magadan
Asia/Makassar Asia/Manila Asia/Muscat Asia/Nicosia Asia/Novokuznetsk
Asia/Novosibirsk Asia/Omsk Asia/Oral Asia/Phnom_Penh Asia/Pontianak
Asia/Pyongyang Asia/Qatar Asia/Qyzylorda Asia/Rangoon Asia/Riyadh
Asia/Saigon Asia/Sakhalin Asia/Samarkand Asia/Seoul Asia/Shanghai
Asia/Singapore Asia/Taipei Asia/Tashkent Asia/Tbilisi Asia/Tehran
Asia/Tel_Aviv Asia/Thimbu Asia/Thimphu Asia/Tokyo Asia/Ujung_Pandang
Asia/Ulaanbaatar Asia/Ulan_Bator Asia/Urumqi Asia/Vientiane Asia/Vladivostok
Asia/Yakutsk Asia/Yekaterinburg Asia/Yerevan
----------------------------------------------------------------------
----------------------------------------------------------------------
Atlantic
Atlantic
Atlantic/Azores Atlantic/Bermuda Atlantic/Canary Atlantic/Cape_Verde Atlantic/Faeroe
Atlantic/Faroe Atlantic/Jan_Mayen Atlantic/Madeira Atlantic/Reykjavik Atlantic/South_Georgia
Atlantic/St_Helena Atlantic/Stanley
----------------------------------------------------------------------
----------------------------------------------------------------------
Australia
Australia
Australia/ACT Australia/Adelaide Australia/Brisbane Australia/Broken_Hill Australia/Canberra
Australia/Currie Australia/Darwin Australia/Eucla Australia/Hobart Australia/LHI
Australia/Lindeman Australia/Lord_Howe Australia/Melbourne Australia/North Australia/NSW
Australia/Perth Australia/Queensland Australia/South Australia/Sydney Australia/Tasmania
Australia/Victoria Australia/West Australia/Yancowinna
----------------------------------------------------------------------
----------------------------------------------------------------------
Europe
Europe
Europe/Amsterdam Europe/Andorra Europe/Athens Europe/Belfast Europe/Belgrade
Europe/Berlin Europe/Bratislava Europe/Brussels Europe/Bucharest Europe/Budapest
Europe/Chisinau Europe/Copenhagen Europe/Dublin Europe/Gibraltar Europe/Guernsey
Europe/Helsinki Europe/Isle_of_Man Europe/Istanbul Europe/Jersey Europe/Kaliningrad
Europe/Kiev Europe/Lisbon Europe/Ljubljana Europe/London Europe/Luxembourg
Europe/Madrid Europe/Malta Europe/Mariehamn Europe/Minsk Europe/Monaco
Europe/Moscow Europe/Nicosia Europe/Oslo Europe/Paris Europe/Podgorica
Europe/Prague Europe/Riga Europe/Rome Europe/Samara Europe/San_Marino
Europe/Sarajevo Europe/Simferopol Europe/Skopje Europe/Sofia Europe/Stockholm
Europe/Tallinn Europe/Tirane Europe/Tiraspol Europe/Uzhgorod Europe/Vaduz
Europe/Vatican Europe/Vienna Europe/Vilnius Europe/Volgograd Europe/Warsaw
Europe/Zagreb Europe/Zaporozhye Europe/Zurich
----------------------------------------------------------------------
----------------------------------------------------------------------
Indian
Indian
Indian/Antananarivo Indian/Chagos Indian/Christmas Indian/Cocos Indian/Comoro
Indian/Kerguelen Indian/Mahe Indian/Maldives Indian/Mauritius Indian/Mayotte
Indian/Reunion
----------------------------------------------------------------------
----------------------------------------------------------------------
Pacific
Pacific
Pacific/Apia Pacific/Auckland Pacific/Chatham Pacific/Chuuk Pacific/Easter
Pacific/Efate Pacific/Enderbury Pacific/Fakaofo Pacific/Fiji Pacific/Funafuti
Pacific/Galapagos Pacific/Gambier Pacific/Guadalcanal Pacific/Guam Pacific/Honolulu
Pacific/Johnston Pacific/Kiritimati Pacific/Kosrae Pacific/Kwajalein Pacific/Majuro
Pacific/Marquesas Pacific/Midway Pacific/Nauru Pacific/Niue Pacific/Norfolk
Pacific/Noumea Pacific/Pago_Pago Pacific/Palau Pacific/Pitcairn Pacific/Pohnpei
Pacific/Ponape Pacific/Port_Moresby Pacific/Rarotonga Pacific/Saipan Pacific/Samoa
Pacific/Tahiti Pacific/Tarawa Pacific/Tongatapu Pacific/Truk Pacific/Wake
Pacific/Wallis Pacific/Yap
----------------------------------------------------------------------
----------------------------------------------------------------------
Others
Others
Brazil/Acre Brazil/DeNoronha Brazil/East Brazil/West Canada/Atlantic
Canada/Central Canada/East-Saskatchewan Canada/Eastern Canada/Mountain Canada/Newfoundland
Canada/Pacific Canada/Saskatchewan Canada/Yukon CET Chile/Continental
Chile/EasterIsland CST6CDT Cuba EET Egypt
Eire EST EST5EDT Etc/GMT Etc/GMT+0
Etc/GMT+1 Etc/GMT+10 Etc/GMT+11 Etc/GMT+12 Etc/GMT+2
Etc/GMT+3 Etc/GMT+4 Etc/GMT+5 Etc/GMT+6 Etc/GMT+7
Etc/GMT+8 Etc/GMT+9 Etc/GMT-0 Etc/GMT-1 Etc/GMT-10
Etc/GMT-11 Etc/GMT-12 Etc/GMT-13 Etc/GMT-14 Etc/GMT-2
Etc/GMT-3 Etc/GMT-4 Etc/GMT-5 Etc/GMT-6 Etc/GMT-7
Etc/GMT-8 Etc/GMT-9 Etc/GMT0 Etc/Greenwich Etc/UCT
Etc/Universal Etc/UTC Etc/Zulu Factory GB
GB-Eire GMT GMT+0 GMT-0 GMT0
Greenwich Hongkong HST Iceland Iran
Israel Jamaica Japan Kwajalein Libya
MET Mexico/BajaNorte Mexico/BajaSur Mexico/General MST
MST7MDT Navajo NZ NZ-CHAT Poland
Portugal PRC PST8PDT ROC ROK
Singapore Turkey UCT Universal US/Alaska
US/Aleutian US/Arizona US/Central US/East-Indiana US/Eastern
US/Hawaii US/Indiana-Starke US/Michigan US/Mountain US/Pacific
US/Pacific-New US/Samoa UTC W-SU WET
Zulu
Warning
Please do not use any of the timezones listed here (besides UTC), they
only exist for backward compatible reasons.
----------------------------------------------------------------------
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* DateTime - The DateTime class
* DateTime::add - Adds an amount of days, months, years, hours,
minutes and seconds to a DateTime object
* DateTime::__construct - Returns new DateTime object
* DateTime::createFromFormat - Returns new DateTime object
formatted according to the specified format
* DateTime::diff - Returns the difference between two DateTime
objects
* DateTime::format - Returns date formatted according to given
format
* DateTime::getLastErrors - Returns the warnings and errors
* DateTime::getOffset - Returns the timezone offset
* DateTime::getTimestamp - Gets the Unix timestamp
* DateTime::getTimezone - Return time zone relative to given
DateTime
* DateTime::modify - Alters the timestamp
* DateTime::__set_state - The __set_state handler
* DateTime::setDate - Sets the date
* DateTime::setISODate - Sets the ISO date
* DateTime::setTime - Sets the time
* DateTime::setTimestamp - Sets the date and time based on an Unix
timestamp
* DateTime::setTimezone - Sets the time zone for the DateTime
object
* DateTime::sub - Subtracts an amount of days, months, years,
hours, minutes and seconds from a DateTime object
* DateTime::__wakeup - The __wakeup handler
* DateTimeZone - The DateTimeZone class
* DateTimeZone::__construct - Creates new DateTimeZone object
* DateTimeZone::getLocation - Returns location information for a
timezone
* DateTimeZone::getName - Returns the name of the timezone
* DateTimeZone::getOffset - Returns the timezone offset from GMT
* DateTimeZone::getTransitions - Returns all transitions for the
timezone
* DateTimeZone::listAbbreviations - Returns associative array
containing dst, offset and the timezone name
* DateTimeZone::listIdentifiers - Returns numerically index array
with all timezone identifiers
* DateInterval - The DateInterval class
* DateInterval::__construct - Creates new DateInterval object
* DateInterval::createFromDateString - Sets up a DateInterval from
the relative parts of the string
* DateInterval::format - Formats the interval
* DatePeriod - The DatePeriod class
* DatePeriod::__construct - Creates new DatePeriod object
* Date/Time Functions
* checkdate - Validate a Gregorian date
* date_add - Alias of DateTime::add
* date_create_from_format - Alias of DateTime::createFromFormat
* date_create - Alias of DateTime::__construct
* date_date_set - Alias of DateTime::setDate
* date_default_timezone_get - Gets the default timezone used by all
date/time functions in a script
* date_default_timezone_set - Sets the default timezone used by all
date/time functions in a script
* date_diff - Alias of DateTime::diff
* date_format - Alias of DateTime::format
* date_get_last_errors - Alias of DateTime::getLastErrors
* date_interval_create_from_date_string - Alias of
DateInterval::createFromDateString
* date_interval_format - Alias of DateInterval::format
* date_isodate_set - Alias of DateTime::setISODate
* date_modify - Alias of DateTime::modify
* date_offset_get - Alias of DateTime::getOffset
* date_parse_from_format - Get info about given date formatted
according to the specified format
* date_parse - Returns associative array with detailed info about
given date
* date_sub - Alias of DateTime::sub
* date_sun_info - Returns an array with information about
sunset/sunrise and twilight begin/end
* date_sunrise - Returns time of sunrise for a given day and
location
* date_sunset - Returns time of sunset for a given day and location
* date_time_set - Alias of DateTime::setTime
* date_timestamp_get - Alias of DateTime::getTimestamp
* date_timestamp_set - Alias of DateTime::setTimestamp
* date_timezone_get - Alias of DateTime::getTimezone
* date_timezone_set - Alias of DateTime::setTimezone
* date - Format a local time/date
* getdate - Get date/time information
* gettimeofday - Get current time
* gmdate - Format a GMT/UTC date/time
* gmmktime - Get Unix timestamp for a GMT date
* gmstrftime - Format a GMT/UTC time/date according to locale
settings
* idate - Format a local time/date as integer
* localtime - Get the local time
* microtime - Return current Unix timestamp with microseconds
* mktime - Get Unix timestamp for a date
* strftime - Format a local time/date according to locale settings
* strptime - Parse a time/date generated with strftime
* strtotime - Parse about any English textual datetime description
into a Unix timestamp
* time - Return current Unix timestamp
* timezone_abbreviations_list - Alias of
DateTimeZone::listAbbreviations
* timezone_identifiers_list - Alias of
DateTimeZone::listIdentifiers
* timezone_location_get - Alias of DateTimeZone::getLocation
* timezone_name_from_abbr - Returns the timezone name from
abbreviation
* timezone_name_get - Alias of DateTimeZone::getName
* timezone_offset_get - Alias of DateTimeZone::getOffset
* timezone_open - Alias of DateTimeZone::__construct
* timezone_transitions_get - Alias of DateTimeZone::getTransitions
* timezone_version_get - Gets the version of the timezonedb
* Supported Date and Time Formats
* Time Formats
* Date Formats
* Compound Formats
* Relative Formats
* List of Supported Timezones
* Africa
* America
* Antarctica
* Arctic
* Asia
* Atlantic
* Australia
* Europe
* Indian
* Pacific
* Others
----------------------------------------------------------------------
* Calendar
* Introduction
* Installing/Configuring
* Predefined Constants
* Calendar Functions
* Date/Time - Date and Time
* Introduction
* Installing/Configuring
* Predefined Constants
* DateTime - The DateTime class
* DateTimeZone - The DateTimeZone class
* DateInterval - The DateInterval class
* DatePeriod - The DatePeriod class
* Date/Time Functions
* Supported Date and Time Formats
* List of Supported Timezones
----------------------------------------------------------------------
----------------------------------------------------------------------
Command Line Specific Extensions
----------------------------------------------------------------------
Newt
----------------------------------------------------------------------
Introduction
This is a PHP language extension for RedHat Newt library, a terminal-based
window and widget library for writing applications with user friendly
interface. Once this extension is enabled in PHP it will provide the use
of Newt widgets, such as windows, buttons, checkboxes, radiobuttons,
labels, editboxes, scrolls, textareas, scales, etc. Use of this extension
if very similar to the original Newt API of C programming language.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
This module uses the functions of the RedHat Newt library. You need
libnewt version >= 0.51.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
This >> PECL extension is not bundled with PHP. Information for installing
this PECL extension may be found in the manual chapter titled Installation
of PECL extensions. Additional information such as new releases,
downloads, source files, maintainer information, and a CHANGELOG, can be
located here: >> http://pecl.php.net/package/newt.
In PHP 4 this PECL extensions source can be found in the ext/ directory
within the PHP source or at the PECL link above. In order to use these
functions you must compile CGI or CLI PHP with newt support by using the
--with-newt[=DIR] configure option.
Note:
This extension is not available for Windows platform.
You may need also curses and slang libraries, in order to compile this
extension. To specify locations of these libraries, use the following
configuration options: --with-curses-dir=/path/to/libcurses
--with-slang-dir=/path/to/libslang
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension uses two resource types: "newt component" and "newt grid".
Resource type "newt component" is returned by functions, which create
common newt widgets (for example: newt_button())
Resource type "newt grid" is a special link identifier for components,
returned by newt grid factory functions (for example: newt_create_grid())
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
Table of Contents
* Newt form exit reasons
* Newt colorsets
* Newt argument flags
* Newt Flags Sense
* Newt Components Flags
* File Descriptor Flags
* Checkbox Tree Flags
* Entry Flags
* Listbox Flags
* Textbox Flags
* Form Flags
* Newt Keys
* Newt Anchors
* Grid Flags
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
----------------------------------------------------------------------
Newt form exit reasons
Newt form exit reasons
constant meaning
NEWT_EXIT_HOTKEY hotkey defined by newt_form_add_hot_key() was pressed
NEWT_EXIT_COMPONENT some component has caused form to exit
NEWT_EXIT_FDREADY file descriptor specified in newt_form_watch_fd() is
ready to be read or written to
NEWT_EXIT_TIMER time specified in newt_form_set_timer() has elapsed
----------------------------------------------------------------------
----------------------------------------------------------------------
Newt colorsets
Newt colorsets
constant meaning
NEWT_COLORSET_ROOT
NEWT_COLORSET_BORDER
NEWT_COLORSET_WINDOW
NEWT_COLORSET_SHADOW
NEWT_COLORSET_TITLE
NEWT_COLORSET_BUTTON
NEWT_COLORSET_ACTBUTTON
NEWT_COLORSET_CHECKBOX
NEWT_COLORSET_ACTCHECKBOX
NEWT_COLORSET_ENTRY
NEWT_COLORSET_LABEL
NEWT_COLORSET_LISTBOX
NEWT_COLORSET_ACTLISTBOX
NEWT_COLORSET_TEXTBOX
NEWT_COLORSET_ACTTEXTBOX
NEWT_COLORSET_HELPLINE
NEWT_COLORSET_ROOTTEXT
NEWT_COLORSET_ROOTTEXT
NEWT_COLORSET_EMPTYSCALE
NEWT_COLORSET_FULLSCALE
NEWT_COLORSET_DISENTRY
NEWT_COLORSET_COMPACTBUTTON
NEWT_COLORSET_ACTSELLISTBOX
NEWT_COLORSET_SELLISTBOX
----------------------------------------------------------------------
----------------------------------------------------------------------
Newt argument flags
Newt argument flags
constant meaning
NEWT_ARG_LAST
NEWT_ARG_APPEND
----------------------------------------------------------------------
----------------------------------------------------------------------
Newt Flags Sense
Newt Flags Sense
constant meaning
NEWT_FLAGS_SET
NEWT_FLAGS_RESET
NEWT_FLAGS_TOGGLE
----------------------------------------------------------------------
----------------------------------------------------------------------
Newt Components Flags
Newt Components Flags
constant meaning
NEWT_FLAG_RETURNEXIT Exit form, when component is activated
NEWT_FLAG_HIDDEN Component is hidden
NEWT_FLAG_SCROLL Component is scrollable
NEWT_FLAG_DISABLED Component is disabled
NEWT_FLAG_BORDER
NEWT_FLAG_WRAP Wrap text
NEWT_FLAG_NOF12 Don't exit form on pressing F12
NEWT_FLAG_MULTIPLE
NEWT_FLAG_SELECTED Component is selected
NEWT_FLAG_CHECKBOX Component is checkbox
NEWT_FLAG_PASSWORD Entry component is password entry
NEWT_FLAG_SHOWCURSOR Show cursor
----------------------------------------------------------------------
----------------------------------------------------------------------
File Descriptor Flags
File Descriptor Flags
constant meaning
NEWT_FD_READ
NEWT_FD_WRITE
NEWT_FD_EXCEPT
----------------------------------------------------------------------
----------------------------------------------------------------------
Checkbox Tree Flags
Checkbox Tree Flags
constant meaning
NEWT_CHECKBOXTREE_UNSELECTABLE
NEWT_CHECKBOXTREE_HIDE_BOX
NEWT_CHECKBOXTREE_COLLAPSED
NEWT_CHECKBOXTREE_EXPANDED
NEWT_CHECKBOXTREE_UNSELECTED
NEWT_CHECKBOXTREE_SELECTED
----------------------------------------------------------------------
----------------------------------------------------------------------
Entry Flags
Entry Flags
constant meaning
NEWT_ENTRY_SCROLL
NEWT_ENTRY_HIDDEN
NEWT_ENTRY_RETURNEXIT
NEWT_ENTRY_DISABLED
----------------------------------------------------------------------
----------------------------------------------------------------------
Listbox Flags
Listbox Flags
constant meaning
NEWT_LISTBOX_RETURNEXIT
----------------------------------------------------------------------
----------------------------------------------------------------------
Textbox Flags
Textbox Flags
constant meaning
NEWT_TEXTBOX_WRAP Wrap text in the textbox
NEWT_TEXTBOX_SCROLL Scroll text in the textbox
----------------------------------------------------------------------
----------------------------------------------------------------------
Form Flags
Form Flags
constant meaning
NEWT_FORM_NOF12 Don't exit form on F12 press
----------------------------------------------------------------------
----------------------------------------------------------------------
Newt Keys
Newt Keys
constant meaning
NEWT_KEY_TAB
NEWT_KEY_ENTER
NEWT_KEY_SUSPEND
NEWT_KEY_ESCAPE
NEWT_KEY_RETURN
NEWT_KEY_EXTRA_BASE
NEWT_KEY_UP
NEWT_KEY_DOWN
NEWT_KEY_LEFT
NEWT_KEY_RIGHT
NEWT_KEY_BKSPC
NEWT_KEY_DELETE
NEWT_KEY_HOME
NEWT_KEY_END
NEWT_KEY_UNTAB
NEWT_KEY_PGUP
NEWT_KEY_PGDN
NEWT_KEY_INSERT
NEWT_KEY_F1
NEWT_KEY_F2
NEWT_KEY_F3
NEWT_KEY_F4
NEWT_KEY_F5
NEWT_KEY_F6
NEWT_KEY_F7
NEWT_KEY_F8
NEWT_KEY_F9
NEWT_KEY_F10
NEWT_KEY_F11
NEWT_KEY_F12
NEWT_KEY_RESIZE
----------------------------------------------------------------------
----------------------------------------------------------------------
Newt Anchors
Newt Anchors
constant meaning
NEWT_ANCHOR_LEFT
NEWT_ANCHOR_RIGHT
NEWT_ANCHOR_TOP
NEWT_ANCHOR_BOTTOM
----------------------------------------------------------------------
----------------------------------------------------------------------
Grid Flags
Grid Flags
constant meaning
NEWT_GRID_FLAG_GROWX
NEWT_GRID_FLAG_GROWY
NEWT_GRID_EMPTY
NEWT_GRID_COMPONENT
NEWT_GRID_SUBGRID
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Table of Contents
* Basic usage
----------------------------------------------------------------------
Basic usage
This example is a PHP port of RedHat 'setup' utility dialog, executed in
text mode.
Example #1 Newt Usage Example
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Newt Functions
----------------------------------------------------------------------
newt_bell
(PECL newt >= 0.1)
newt_bell - Send a beep to the terminal
Description
void newt_bell ( void )
This function sends a beep to the terminal.
Note:
Depending on the terminal's settings, this beep may or may not be
audible.
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_button_bar
(PECL newt >= 0.1)
newt_button_bar - This function returns a grid containing the buttons
created.
Description
resource newt_button_bar ( array &$buttons )
This function returns a grid containing the buttons created.
Parameters
buttons
Return Values
Returns grid containing the buttons created.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_button
(PECL newt >= 0.1)
newt_button - Create a new button
Description
resource newt_button ( int $left , int $top , string $text )
Creates a new button.
Parameters
left
X-coordinate of the button.
top
Y-coordinate of the button.
text
The text which should be displayed in the button.
Return Values
Returns a resource link to the created button component, or FALSE on
error.
Examples
Example #1 A newt_button() example
See Also
* newt_button_bar() - This function returns a grid containing the
buttons created.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_centered_window
(PECL newt >= 0.1)
newt_centered_window - Open a centered window of the specified size
Description
int newt_centered_window ( int $width , int $height [, string $title ] )
Open a centered window of the specified size.
Parameters
width
Window width
height
Window height
title
Window title
Return Values
Undefined value.
See Also
* newt_pop_window() - Removes the top window from the display
* newt_open_window() - Open a window of the specified size and position
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_checkbox_get_value
(PECL newt >= 0.1)
newt_checkbox_get_value - Retreives value of checkox resource
Description
string newt_checkbox_get_value ( resource $checkbox )
This function returns the character in the sequence which indicates the
current value of the checkbox.
Parameters
checkbox
Return Values
Returns character indicating the value of the checkbox.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_checkbox_set_flags
(PECL newt >= 0.1)
newt_checkbox_set_flags - Configures checkbox resource
Description
void newt_checkbox_set_flags ( resource $checkbox , int $flags , int
$sense )
This function allows to set various flags on checkbox resource.
Parameters
checkbox
flags
sense
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_checkbox_set_value
(PECL newt >= 0.1)
newt_checkbox_set_value - Sets the value of the checkbox
Description
void newt_checkbox_set_value ( resource $checkbox , string $value )
This function allows to set the current value of the checkbox resource.
Parameters
checkbox
value
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_checkbox_tree_add_item
(PECL newt >= 0.1)
newt_checkbox_tree_add_item - Adds new item to the checkbox tree
Description
void newt_checkbox_tree_add_item ( resource $checkboxtree , string $text ,
mixed $data , int $flags , int $index [, int $... ] )
This function allows to add new item to the checkbox tree.
Parameters
checkboxtree
text
data
flags
index
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_checkbox_tree_find_item
(PECL newt >= 0.1)
newt_checkbox_tree_find_item - Finds an item in the checkbox tree
Description
array newt_checkbox_tree_find_item ( resource $checkboxtree , mixed $data
)
Finds an item in the checkbox tree by item's data.
Parameters
checkboxtree
data
Return Values
Returns checkbox tree item resource, or NULL if it wasn't found.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_checkbox_tree_get_current
(PECL newt >= 0.1)
newt_checkbox_tree_get_current - Returns checkbox tree selected item
Description
mixed newt_checkbox_tree_get_current ( resource $checkboxtree )
This method returns checkbox tree selected tem.
Parameters
checkboxtree
Return Values
Returns current (selected) checkbox tree item.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_checkbox_tree_get_entry_value
(PECL newt >= 0.1)
newt_checkbox_tree_get_entry_value -
Description
string newt_checkbox_tree_get_entry_value ( resource $checkboxtree , mixed
$data )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
checkboxtree
data
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_checkbox_tree_get_multi_selection
(PECL newt >= 0.1)
newt_checkbox_tree_get_multi_selection -
Description
array newt_checkbox_tree_get_multi_selection ( resource $checkboxtree ,
string $seqnum )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
checkboxtree
seqnum
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_checkbox_tree_get_selection
(PECL newt >= 0.1)
newt_checkbox_tree_get_selection -
Description
array newt_checkbox_tree_get_selection ( resource $checkboxtree )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
checkboxtree
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_checkbox_tree_multi
(PECL newt >= 0.1)
newt_checkbox_tree_multi -
Description
resource newt_checkbox_tree_multi ( int $left , int $top , int $height ,
string $seq [, int $flags ] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
left
top
height
seq
flags
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_checkbox_tree_set_current
(PECL newt >= 0.1)
newt_checkbox_tree_set_current -
Description
void newt_checkbox_tree_set_current ( resource $checkboxtree , mixed $data
)
Warning
This function is currently not documented; only its argument list is
available.
Parameters
checkboxtree
data
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_checkbox_tree_set_entry_value
(PECL newt >= 0.1)
newt_checkbox_tree_set_entry_value -
Description
void newt_checkbox_tree_set_entry_value ( resource $checkboxtree , mixed
$data , string $value )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
checkboxtree
data
value
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_checkbox_tree_set_entry
(PECL newt >= 0.1)
newt_checkbox_tree_set_entry -
Description
void newt_checkbox_tree_set_entry ( resource $checkboxtree , mixed $data ,
string $text )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
checkboxtree
data
text
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_checkbox_tree_set_width
(PECL newt >= 0.1)
newt_checkbox_tree_set_width -
Description
void newt_checkbox_tree_set_width ( resource $checkbox_tree , int $width )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
checkbox_tree
width
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_checkbox_tree
(PECL newt >= 0.1)
newt_checkbox_tree -
Description
resource newt_checkbox_tree ( int $left , int $top , int $height [, int
$flags ] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
left
top
height
flags
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_checkbox
(PECL newt >= 0.1)
newt_checkbox -
Description
resource newt_checkbox ( int $left , int $top , string $text , string
$def_value [, string $seq ] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
left
top
text
def_value
seq
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_clear_key_buffer
(PECL newt >= 0.1)
newt_clear_key_buffer - Discards the contents of the terminal's input
buffer without waiting for additional input
Description
void newt_clear_key_buffer ( void )
Discards the contents of the terminal's input buffer without waiting for
additional input.
Return Values
No value is returned.
See Also
* newt_wait_for_key() - Doesn't return until a key has been pressed
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_cls
(PECL newt >= 0.1)
newt_cls -
Description
void newt_cls ( void )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_compact_button
(PECL newt >= 0.1)
newt_compact_button -
Description
resource newt_compact_button ( int $left , int $top , string $text )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
left
top
text
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_component_add_callback
(PECL newt >= 0.1)
newt_component_add_callback -
Description
void newt_component_add_callback ( resource $component , mixed $func_name
, mixed $data )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
component
func_name
data
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_component_takes_focus
(PECL newt >= 0.1)
newt_component_takes_focus -
Description
void newt_component_takes_focus ( resource $component , bool $takes_focus
)
Warning
This function is currently not documented; only its argument list is
available.
Parameters
component
takes_focus
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_create_grid
(PECL newt >= 0.1)
newt_create_grid -
Description
resource newt_create_grid ( int $cols , int $rows )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
cols
rows
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_cursor_off
(PECL newt >= 0.1)
newt_cursor_off -
Description
void newt_cursor_off ( void )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_cursor_on
(PECL newt >= 0.1)
newt_cursor_on -
Description
void newt_cursor_on ( void )
Warning
This function is currently not documented; only its argument list is
available.
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_delay
(PECL newt >= 0.1)
newt_delay -
Description
void newt_delay ( int $microseconds )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
microseconds
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_draw_form
(PECL newt >= 0.1)
newt_draw_form -
Description
void newt_draw_form ( resource $form )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
form
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_draw_root_text
(PECL newt >= 0.1)
newt_draw_root_text - Displays the string text at the position indicated
Description
void newt_draw_root_text ( int $left , int $top , string $text )
Displays the string text at the position indicated.
Parameters
left
Column number
Note:
If left is negative, the position is measured from the opposite
side of the screen.
top
Line number
Note:
If top is negative, the position is measured from the opposite
side of the screen.
text
Text to display.
Return Values
No value is returned.
Examples
Example #1 A newt_draw_root_text() example
This code demonstrates drawing of titles in the both corners of the
screen.
See Also
* newt_push_help_line() - Saves the current help line on a stack, and
displays the new line
* newt_pop_help_line() - Replaces the current help line with the one
from the stack
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_entry_get_value
(PECL newt >= 0.1)
newt_entry_get_value -
Description
string newt_entry_get_value ( resource $entry )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
entry
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_entry_set_filter
(PECL newt >= 0.1)
newt_entry_set_filter -
Description
void newt_entry_set_filter ( resource $entry , callback $filter , mixed
$data )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
entry
filter
data
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_entry_set_flags
(PECL newt >= 0.1)
newt_entry_set_flags -
Description
void newt_entry_set_flags ( resource $entry , int $flags , int $sense )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
entry
flags
sense
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_entry_set
(PECL newt >= 0.1)
newt_entry_set -
Description
void newt_entry_set ( resource $entry , string $value [, bool
$cursor_at_end ] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
entry
value
cursor_at_end
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_entry
(PECL newt >= 0.1)
newt_entry -
Description
resource newt_entry ( int $left , int $top , int $width [, string
$init_value [, int $flags ]] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
left
top
width
init_value
flags
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_finished
(PECL newt >= 0.1)
newt_finished - Uninitializes newt interface
Description
int newt_finished ( void )
Uninitializes newt interface. This function be called, when program is
ready to exit.
Return Values
Returns 1 on success, 0 on failure.
See Also
* newt_init() - Initialize newt
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_form_add_component
(PECL newt >= 0.1)
newt_form_add_component - Adds a single component to the form
Description
void newt_form_add_component ( resource $form , resource $component )
Adds a single component to the form.
Parameters
form
Form to which component will be added
component
Component to add to the form
Return Values
No value is returned.
Examples
Example #1 A newt_form_add_component() example
See Also
* newt_form_add_components() - Add several components to the form
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_form_add_components
(PECL newt >= 0.1)
newt_form_add_components - Add several components to the form
Description
void newt_form_add_components ( resource $form , array $components )
Adds several components to the form.
Parameters
form
Form to which components will be added
components
Array of components to add to the form
Return Values
No value is returned.
Examples
Example #1 A newt_form_add_components() example
See Also
* newt_form_add_component() - Adds a single component to the form
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_form_add_hot_key
(PECL newt >= 0.1)
newt_form_add_hot_key -
Description
void newt_form_add_hot_key ( resource $form , int $key )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
form
key
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_form_destroy
(PECL newt >= 0.1)
newt_form_destroy - Destroys a form
Description
void newt_form_destroy ( resource $form )
This function frees the memory resources used by the form and all of the
components which have been added to the form (including those components
which are on subforms). Once a form has been destroyed, none of the form's
components can be used.
Parameters
form
Form component, which is going to be destroyed
Return Values
No value is returned.
See Also
* newt_form_run() - Runs a form
* newt_run_form() - Runs a form
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_form_get_current
(PECL newt >= 0.1)
newt_form_get_current -
Description
resource newt_form_get_current ( resource $form )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
form
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_form_run
(PECL newt >= 0.1)
newt_form_run - Runs a form
Description
void newt_form_run ( resource $form , array &$exit_struct )
This function runs the form passed to it.
Parameters
form
Form component
exit_struct
Array, used for returning information after running the form
component. Keys and values are described in the following table:
Form Exit Structure
Index Key Value Type Description
reason integer The reason, why the form has been exited.
Possible values are defined here.
watch resource Resource link, specified in
newt_form_watch_fd()
key integer Hotkey
component resource Component, which caused the form to exit
Return Values
No value is returned.
See Also
* newt_run_form() - Runs a form
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_form_set_background
(PECL newt >= 0.1)
newt_form_set_background -
Description
void newt_form_set_background ( resource $from , int $background )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
from
background
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_form_set_height
(PECL newt >= 0.1)
newt_form_set_height -
Description
void newt_form_set_height ( resource $form , int $height )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
form
height
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_form_set_size
(PECL newt >= 0.1)
newt_form_set_size -
Description
void newt_form_set_size ( resource $form )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
form
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_form_set_timer
(PECL newt >= 0.1)
newt_form_set_timer -
Description
void newt_form_set_timer ( resource $form , int $milliseconds )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
form
milliseconds
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_form_set_width
(PECL newt >= 0.1)
newt_form_set_width -
Description
void newt_form_set_width ( resource $form , int $width )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
form
width
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_form_watch_fd
(PECL newt >= 0.1)
newt_form_watch_fd -
Description
void newt_form_watch_fd ( resource $form , resource $stream [, int $flags
] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
form
stream
flags
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_form
(PECL newt >= 0.1)
newt_form - Create a form
Description
resource newt_form ([ resource $vert_bar [, string $help [, int $flags ]]]
)
Create a new form.
Parameters
vert_bar
Vertical scrollbar which should be associated with the form
help
Help text string
flags
Various flags
Return Values
Returns a resource link to the created form component, or FALSE on error.
Examples
Example #1 A newt_form() example
Displays a single button "Quit", which closes the application once it's
pressed.
See Also
* newt_form_run() - Runs a form
* newt_run_form() - Runs a form
* newt_form_add_component() - Adds a single component to the form
* newt_form_add_components() - Add several components to the form
* newt_form_destroy() - Destroys a form
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_get_screen_size
(PECL newt >= 0.1)
newt_get_screen_size - Fills in the passed references with the current
size of the terminal
Description
void newt_get_screen_size ( int &$cols , int &$rows )
Fills in the passed references with the current size of the terminal.
Parameters
cols
Number of columns in the terminal
rows
Number of rows in the terminal
Return Values
No value is returned.
Examples
Example #1 A newt_get_screen_size() example
This code prints out the screen size of your terminal.
The above example will output:
Your terminal size is: 138x47
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_grid_add_components_to_form
(PECL newt >= 0.1)
newt_grid_add_components_to_form -
Description
void newt_grid_add_components_to_form ( resource $grid , resource $form ,
bool $recurse )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
grid
form
recurse
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_grid_basic_window
(PECL newt >= 0.1)
newt_grid_basic_window -
Description
resource newt_grid_basic_window ( resource $text , resource $middle ,
resource $buttons )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
text
middle
buttons
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_grid_free
(PECL newt >= 0.1)
newt_grid_free -
Description
void newt_grid_free ( resource $grid , bool $recurse )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
grid
recurse
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_grid_get_size
(PECL newt >= 0.1)
newt_grid_get_size -
Description
void newt_grid_get_size ( resouce $grid , int &$width , int &$height )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
grid
width
height
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_grid_h_close_stacked
(PECL newt >= 0.1)
newt_grid_h_close_stacked -
Description
resource newt_grid_h_close_stacked ( int $element1_type , resource
$element1 [, int $... [, resource $... ]] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
element1_type
element1
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_grid_h_stacked
(PECL newt >= 0.1)
newt_grid_h_stacked -
Description
resource newt_grid_h_stacked ( int $element1_type , resource $element1 [,
int $... [, resource $... ]] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
element1_type
element1
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_grid_place
(PECL newt >= 0.1)
newt_grid_place -
Description
void newt_grid_place ( resource $grid , int $left , int $top )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
grid
left
top
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_grid_set_field
(PECL newt >= 0.1)
newt_grid_set_field -
Description
void newt_grid_set_field ( resource $grid , int $col , int $row , int
$type , resource $val , int $pad_left , int $pad_top , int $pad_right ,
int $pad_bottom , int $anchor [, int $flags ] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
grid
col
row
type
val
pad_left
pad_top
pad_right
pad_bottom
anchor
flags
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_grid_simple_window
(PECL newt >= 0.1)
newt_grid_simple_window -
Description
resource newt_grid_simple_window ( resource $text , resource $middle ,
resource $buttons )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
text
middle
buttons
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_grid_v_close_stacked
(PECL newt >= 0.1)
newt_grid_v_close_stacked -
Description
resource newt_grid_v_close_stacked ( int $element1_type , resource
$element1 [, int $... [, resource $... ]] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
element1_type
element1
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_grid_v_stacked
(PECL newt >= 0.1)
newt_grid_v_stacked -
Description
resource newt_grid_v_stacked ( int $element1_type , resource $element1 [,
int $... [, resource $... ]] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
element1_type
element1
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_grid_wrapped_window_at
(PECL newt >= 0.1)
newt_grid_wrapped_window_at -
Description
void newt_grid_wrapped_window_at ( resource $grid , string $title , int
$left , int $top )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
grid
title
left
top
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_grid_wrapped_window
(PECL newt >= 0.1)
newt_grid_wrapped_window -
Description
void newt_grid_wrapped_window ( resource $grid , string $title )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
grid
title
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_init
(PECL newt >= 0.1)
newt_init - Initialize newt
Description
int newt_init ( void )
Initializes the newt interface. This function must be called before any
other newt function.
Return Values
Returns 1 on success, 0 on failure.
See Also
* newt_finished() - Uninitializes newt interface
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_label_set_text
(PECL newt >= 0.1)
newt_label_set_text -
Description
void newt_label_set_text ( resource $label , string $text )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
label
text
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_label
(PECL newt >= 0.1)
newt_label -
Description
resource newt_label ( int $left , int $top , string $text )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
left
top
text
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_listbox_append_entry
(PECL newt >= 0.1)
newt_listbox_append_entry -
Description
void newt_listbox_append_entry ( resource $listbox , string $text , mixed
$data )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
listbox
text
data
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_listbox_clear_selection
(PECL newt >= 0.1)
newt_listbox_clear_selection -
Description
void newt_listbox_clear_selection ( resource $listbox )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
listbox
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_listbox_clear
(PECL newt >= 0.1)
newt_listbox_clear -
Description
void newt_listbox_clear ( resource $listobx )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
listobx
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_listbox_delete_entry
(PECL newt >= 0.1)
newt_listbox_delete_entry -
Description
void newt_listbox_delete_entry ( resource $listbox , mixed $key )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
listbox
key
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_listbox_get_current
(PECL newt >= 0.1)
newt_listbox_get_current -
Description
string newt_listbox_get_current ( resource $listbox )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
listbox
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_listbox_get_selection
(PECL newt >= 0.1)
newt_listbox_get_selection -
Description
array newt_listbox_get_selection ( resource $listbox )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
listbox
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_listbox_insert_entry
(PECL newt >= 0.1)
newt_listbox_insert_entry -
Description
void newt_listbox_insert_entry ( resource $listbox , string $text , mixed
$data , mixed $key )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
listbox
text
data
key
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_listbox_item_count
(PECL newt >= 0.1)
newt_listbox_item_count -
Description
int newt_listbox_item_count ( resource $listbox )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
listbox
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_listbox_select_item
(PECL newt >= 0.1)
newt_listbox_select_item -
Description
void newt_listbox_select_item ( resource $listbox , mixed $key , int
$sense )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
listbox
key
sense
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_listbox_set_current_by_key
(PECL newt >= 0.1)
newt_listbox_set_current_by_key -
Description
void newt_listbox_set_current_by_key ( resource $listbox , mixed $key )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
listbox
key
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_listbox_set_current
(PECL newt >= 0.1)
newt_listbox_set_current -
Description
void newt_listbox_set_current ( resource $listbox , int $num )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
listbox
num
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_listbox_set_data
(PECL newt >= 0.1)
newt_listbox_set_data -
Description
void newt_listbox_set_data ( resource $listbox , int $num , mixed $data )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
listbox
num
data
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_listbox_set_entry
(PECL newt >= 0.1)
newt_listbox_set_entry -
Description
void newt_listbox_set_entry ( resource $listbox , int $num , string $text
)
Warning
This function is currently not documented; only its argument list is
available.
Parameters
listbox
num
text
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_listbox_set_width
(PECL newt >= 0.1)
newt_listbox_set_width -
Description
void newt_listbox_set_width ( resource $listbox , int $width )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
listbox
width
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_listbox
(PECL newt >= 0.1)
newt_listbox -
Description
resource newt_listbox ( int $left , int $top , int $height [, int $flags ]
)
Warning
This function is currently not documented; only its argument list is
available.
Parameters
left
top
height
flags
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_listitem_get_data
(PECL newt >= 0.1)
newt_listitem_get_data -
Description
mixed newt_listitem_get_data ( resource $item )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
item
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_listitem_set
(PECL newt >= 0.1)
newt_listitem_set -
Description
void newt_listitem_set ( resource $item , string $text )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
item
text
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_listitem
(PECL newt >= 0.1)
newt_listitem -
Description
resource newt_listitem ( int $left , int $top , string $text , bool
$is_default , resouce $prev_item , mixed $data [, int $flags ] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
left
top
text
is_default
prev_item
data
flags
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_open_window
(PECL newt >= 0.1)
newt_open_window - Open a window of the specified size and position
Description
int newt_open_window ( int $left , int $top , int $width , int $height [,
string $title ] )
Open a window of the specified size and position.
Parameters
left
Location of the upper left-hand corner of the window (column
number)
top
Location of the upper left-hand corner of the window (row number)
width
Window width
height
Window height
title
Window title
Return Values
Returns 1 on success, 0 on failure.
See Also
* newt_pop_window() - Removes the top window from the display
* newt_centered_window() - Open a centered window of the specified size
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_pop_help_line
(PECL newt >= 0.1)
newt_pop_help_line - Replaces the current help line with the one from the
stack
Description
void newt_pop_help_line ( void )
Replaces the current help line with the one from the stack.
Note:
It's important not to call to newt_pop_help_line() more than
newt_push_help_line().
Return Values
No value is returned.
See Also
* newt_push_help_line() - Saves the current help line on a stack, and
displays the new line
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_pop_window
(PECL newt >= 0.1)
newt_pop_window - Removes the top window from the display
Description
void newt_pop_window ( void )
Removes the top window from the display, and redraws the display areas
which the window overwrote.
Return Values
No value is returned.
See Also
* newt_open_window() - Open a window of the specified size and position
* newt_centered_window() - Open a centered window of the specified size
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_push_help_line
(PECL newt >= 0.1)
newt_push_help_line - Saves the current help line on a stack, and displays
the new line
Description
void newt_push_help_line ([ string $text ] )
Saves the current help line on a stack, and displays the new line.
Parameters
text
New help text message
Note:
If not specified, the help line is cleared.
Return Values
No value is returned.
See Also
* newt_pop_help_line() - Replaces the current help line with the one
from the stack
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_radio_get_current
(PECL newt >= 0.1)
newt_radio_get_current -
Description
resource newt_radio_get_current ( resource $set_member )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
set_member
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_radiobutton
(PECL newt >= 0.1)
newt_radiobutton -
Description
resource newt_radiobutton ( int $left , int $top , string $text , bool
$is_default [, resource $prev_button ] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
left
top
text
is_default
prev_button
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_redraw_help_line
(PECL newt >= 0.1)
newt_redraw_help_line -
Description
void newt_redraw_help_line ( void )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_reflow_text
(PECL newt >= 0.1)
newt_reflow_text -
Description
string newt_reflow_text ( string $text , int $width , int $flex_down , int
$flex_up , int &$actual_width , int &$actual_height )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
text
width
flex_down
flex_up
actual_width
actual_height
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_refresh
(PECL newt >= 0.1)
newt_refresh - Updates modified portions of the screen
Description
void newt_refresh ( void )
To increase performance, newt only updates the display when it needs to,
not when the program tells it to write to the terminal. Applications can
force newt to immediately update modified portions of the screen by
calling this function.
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_resize_screen
(PECL newt >= 0.1)
newt_resize_screen -
Description
void newt_resize_screen ([ bool $redraw ] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
redraw
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_resume
(PECL newt >= 0.1)
newt_resume - Resume using the newt interface after calling newt_suspend()
Description
void newt_resume ( void )
Resume using the newt interface after calling newt_suspend().
Return Values
No value is returned.
See Also
* newt_suspend() - Tells newt to return the terminal to its initial
state
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_run_form
(PECL newt >= 0.1)
newt_run_form - Runs a form
Description
resource newt_run_form ( resource $form )
This function runs the form passed to it.
Parameters
form
Form component
Return Values
The component which caused the form to stop running.
Note:
Notice that this function doesn't fit in with newt's normal naming
convention. It is an older interface which will not work for all forms.
It was left in newt only for legacy applications. It is a simpler
interface than the new newt_form_run() though, and is still used quite
often as a result. When an application is done with a form, it destroys
the form and all of the components the form contains.
See Also
* newt_form_run() - Runs a form
* newt_form_destroy() - Destroys a form
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_scale_set
(PECL newt >= 0.1)
newt_scale_set -
Description
void newt_scale_set ( resource $scale , int $amount )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
scale
amount
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_scale
(PECL newt >= 0.1)
newt_scale -
Description
resource newt_scale ( int $left , int $top , int $width , int $full_value
)
Warning
This function is currently not documented; only its argument list is
available.
Parameters
left
top
width
full_value
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_scrollbar_set
(PECL newt >= 0.1)
newt_scrollbar_set -
Description
void newt_scrollbar_set ( resource $scrollbar , int $where , int $total )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
scrollbar
where
total
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_set_help_callback
(PECL newt >= 0.1)
newt_set_help_callback -
Description
void newt_set_help_callback ( mixed $function )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
function
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_set_suspend_callback
(PECL newt >= 0.1)
newt_set_suspend_callback - Set a callback function which gets invoked
when user presses the suspend key
Description
void newt_set_suspend_callback ( callback $function , mixed $data )
Set a callback function which gets invoked when user presses the suspend
key (normally ^Z). If no suspend callback is registered, the suspend
keystroke is ignored.
Parameters
function
A callback function, which accepts one argument: data
data
This data is been passed to the callback function
Return Values
No value is returned.
See Also
* newt_suspend() - Tells newt to return the terminal to its initial
state
* newt_resume() - Resume using the newt interface after calling
newt_suspend
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_suspend
(PECL newt >= 0.1)
newt_suspend - Tells newt to return the terminal to its initial state
Description
void newt_suspend ( void )
Tells newt to return the terminal to its initial state. Once this is done,
the application can suspend itself (by sending itself a SIGTSTP, fork a
child program, or do whatever else it likes).
Return Values
No value is returned.
See Also
* newt_resume() - Resume using the newt interface after calling
newt_suspend
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_textbox_get_num_lines
(PECL newt >= 0.1)
newt_textbox_get_num_lines -
Description
int newt_textbox_get_num_lines ( resource $textbox )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
textbox
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_textbox_reflowed
(PECL newt >= 0.1)
newt_textbox_reflowed -
Description
resource newt_textbox_reflowed ( int $left , int $top , char $*text , int
$width , int $flex_down , int $flex_up [, int $flags ] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
left
top
*text
width
flex_down
flex_up
flags
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_textbox_set_height
(PECL newt >= 0.1)
newt_textbox_set_height -
Description
void newt_textbox_set_height ( resource $textbox , int $height )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
textbox
height
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_textbox_set_text
(PECL newt >= 0.1)
newt_textbox_set_text -
Description
void newt_textbox_set_text ( resource $textbox , string $text )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
textbox
text
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_textbox
(PECL newt >= 0.1)
newt_textbox -
Description
resource newt_textbox ( int $left , int $top , int $width , int $height [,
int $flags ] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
left
top
width
height
flags
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_vertical_scrollbar
(PECL newt >= 0.1)
newt_vertical_scrollbar -
Description
resource newt_vertical_scrollbar ( int $left , int $top , int $height [,
int $normal_colorset [, int $thumb_colorset ]] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
left
top
height
normal_colorset
thumb_colorset
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_wait_for_key
(PECL newt >= 0.1)
newt_wait_for_key - Doesn't return until a key has been pressed
Description
void newt_wait_for_key ( void )
This function doesn't return until a key has been pressed. The keystroke
is then ignored. If a key is already in the terminal's buffer, this
function discards a keystroke and returns immediately.
Return Values
No value is returned.
See Also
* newt_clear_key_buffer() - Discards the contents of the terminal's
input buffer without waiting for additional input
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_win_choice
(PECL newt >= 0.1)
newt_win_choice -
Description
int newt_win_choice ( string $title , string $button1_text , string
$button2_text , string $format [, mixed $args [, mixed $... ]] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
title
button1_text
button2_text
format
args
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_win_entries
(PECL newt >= 0.1)
newt_win_entries -
Description
int newt_win_entries ( string $title , string $text , int $suggested_width
, int $flex_down , int $flex_up , int $data_width , array &$items , string
$button1 [, string $... ] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
title
text
suggested_width
flex_down
flex_up
data_width
items
button1
button2
Return Values
Examples
Example #1 A newt_win_entries() example
'First name:', 'value' => &$f_name);
$entries[] = array('text' => 'Last name:', 'value' => &$l_name);
$rc = newt_win_entries("User information", "Please enter your credentials:", 50, 7, 7, 30, $entries, "Ok", "Back");
newt_finished ();
if ($rc != 2) {
echo "Your name is: $f_name $l_name\n";
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_win_menu
(PECL newt >= 0.1)
newt_win_menu -
Description
int newt_win_menu ( string $title , string $text , int $suggestedWidth ,
int $flexDown , int $flexUp , int $maxListHeight , array $items , int
&$listItem [, string $button1 [, string $... ]] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
title
text
suggestedWidth
flexDown
flexUp
maxListHeight
items
listItem
button1
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_win_message
(PECL newt >= 0.1)
newt_win_message -
Description
void newt_win_message ( string $title , string $button_text , string
$format [, mixed $args [, mixed $... ]] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
title
button_text
format
args
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_win_messagev
(PECL newt >= 0.1)
newt_win_messagev -
Description
void newt_win_messagev ( string $title , string $button_text , string
$format , array $args )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
title
button_text
format
args
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
newt_win_ternary
(PECL newt >= 0.1)
newt_win_ternary -
Description
int newt_win_ternary ( string $title , string $button1_text , string
$button2_text , string $button3_text , string $format [, mixed $args [,
mixed $... ]] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
title
Its description
button1_text
Its description
button2_text
Its description
button3_text
Its description
format
Its description
args
Its description
Return Values
What the function returns, first on success, then on failure. See also the
&return.success; entity
----------------------------------------------------------------------
Table of Contents
* newt_bell - Send a beep to the terminal
* newt_button_bar - This function returns a grid containing the buttons
created.
* newt_button - Create a new button
* newt_centered_window - Open a centered window of the specified size
* newt_checkbox_get_value - Retreives value of checkox resource
* newt_checkbox_set_flags - Configures checkbox resource
* newt_checkbox_set_value - Sets the value of the checkbox
* newt_checkbox_tree_add_item - Adds new item to the checkbox tree
* newt_checkbox_tree_find_item - Finds an item in the checkbox tree
* newt_checkbox_tree_get_current - Returns checkbox tree selected item
* newt_checkbox_tree_get_entry_value - Description
* newt_checkbox_tree_get_multi_selection - Description
* newt_checkbox_tree_get_selection - Description
* newt_checkbox_tree_multi - Description
* newt_checkbox_tree_set_current - Description
* newt_checkbox_tree_set_entry_value - Description
* newt_checkbox_tree_set_entry - Description
* newt_checkbox_tree_set_width - Description
* newt_checkbox_tree - Description
* newt_checkbox - Description
* newt_clear_key_buffer - Discards the contents of the terminal's input
buffer without waiting for additional input
* newt_cls - Description
* newt_compact_button - Description
* newt_component_add_callback - Description
* newt_component_takes_focus - Description
* newt_create_grid - Description
* newt_cursor_off - Description
* newt_cursor_on - Description
* newt_delay - Description
* newt_draw_form - Description
* newt_draw_root_text - Displays the string text at the position
indicated
* newt_entry_get_value - Description
* newt_entry_set_filter - Description
* newt_entry_set_flags - Description
* newt_entry_set - Description
* newt_entry - Description
* newt_finished - Uninitializes newt interface
* newt_form_add_component - Adds a single component to the form
* newt_form_add_components - Add several components to the form
* newt_form_add_hot_key - Description
* newt_form_destroy - Destroys a form
* newt_form_get_current - Description
* newt_form_run - Runs a form
* newt_form_set_background - Description
* newt_form_set_height - Description
* newt_form_set_size - Description
* newt_form_set_timer - Description
* newt_form_set_width - Description
* newt_form_watch_fd - Description
* newt_form - Create a form
* newt_get_screen_size - Fills in the passed references with the current
size of the terminal
* newt_grid_add_components_to_form - Description
* newt_grid_basic_window - Description
* newt_grid_free - Description
* newt_grid_get_size - Description
* newt_grid_h_close_stacked - Description
* newt_grid_h_stacked - Description
* newt_grid_place - Description
* newt_grid_set_field - Description
* newt_grid_simple_window - Description
* newt_grid_v_close_stacked - Description
* newt_grid_v_stacked - Description
* newt_grid_wrapped_window_at - Description
* newt_grid_wrapped_window - Description
* newt_init - Initialize newt
* newt_label_set_text - Description
* newt_label - Description
* newt_listbox_append_entry - Description
* newt_listbox_clear_selection - Description
* newt_listbox_clear - Description
* newt_listbox_delete_entry - Description
* newt_listbox_get_current - Description
* newt_listbox_get_selection - Description
* newt_listbox_insert_entry - Description
* newt_listbox_item_count - Description
* newt_listbox_select_item - Description
* newt_listbox_set_current_by_key - Description
* newt_listbox_set_current - Description
* newt_listbox_set_data - Description
* newt_listbox_set_entry - Description
* newt_listbox_set_width - Description
* newt_listbox - Description
* newt_listitem_get_data - Description
* newt_listitem_set - Description
* newt_listitem - Description
* newt_open_window - Open a window of the specified size and position
* newt_pop_help_line - Replaces the current help line with the one from
the stack
* newt_pop_window - Removes the top window from the display
* newt_push_help_line - Saves the current help line on a stack, and
displays the new line
* newt_radio_get_current - Description
* newt_radiobutton - Description
* newt_redraw_help_line - Description
* newt_reflow_text - Description
* newt_refresh - Updates modified portions of the screen
* newt_resize_screen - Description
* newt_resume - Resume using the newt interface after calling
newt_suspend
* newt_run_form - Runs a form
* newt_scale_set - Description
* newt_scale - Description
* newt_scrollbar_set - Description
* newt_set_help_callback - Description
* newt_set_suspend_callback - Set a callback function which gets invoked
when user presses the suspend key
* newt_suspend - Tells newt to return the terminal to its initial state
* newt_textbox_get_num_lines - Description
* newt_textbox_reflowed - Description
* newt_textbox_set_height - Description
* newt_textbox_set_text - Description
* newt_textbox - Description
* newt_vertical_scrollbar - Description
* newt_wait_for_key - Doesn't return until a key has been pressed
* newt_win_choice - Description
* newt_win_entries - Description
* newt_win_menu - Description
* newt_win_message - Description
* newt_win_messagev - Description
* newt_win_ternary - Description
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Newt form exit reasons
* Newt colorsets
* Newt argument flags
* Newt Flags Sense
* Newt Components Flags
* File Descriptor Flags
* Checkbox Tree Flags
* Entry Flags
* Listbox Flags
* Textbox Flags
* Form Flags
* Newt Keys
* Newt Anchors
* Grid Flags
* Examples
* Basic usage
* Newt Functions
* newt_bell - Send a beep to the terminal
* newt_button_bar - This function returns a grid containing the
buttons created.
* newt_button - Create a new button
* newt_centered_window - Open a centered window of the specified
size
* newt_checkbox_get_value - Retreives value of checkox resource
* newt_checkbox_set_flags - Configures checkbox resource
* newt_checkbox_set_value - Sets the value of the checkbox
* newt_checkbox_tree_add_item - Adds new item to the checkbox tree
* newt_checkbox_tree_find_item - Finds an item in the checkbox tree
* newt_checkbox_tree_get_current - Returns checkbox tree selected
item
* newt_checkbox_tree_get_entry_value - Description
* newt_checkbox_tree_get_multi_selection - Description
* newt_checkbox_tree_get_selection - Description
* newt_checkbox_tree_multi - Description
* newt_checkbox_tree_set_current - Description
* newt_checkbox_tree_set_entry_value - Description
* newt_checkbox_tree_set_entry - Description
* newt_checkbox_tree_set_width - Description
* newt_checkbox_tree - Description
* newt_checkbox - Description
* newt_clear_key_buffer - Discards the contents of the terminal's
input buffer without waiting for additional input
* newt_cls - Description
* newt_compact_button - Description
* newt_component_add_callback - Description
* newt_component_takes_focus - Description
* newt_create_grid - Description
* newt_cursor_off - Description
* newt_cursor_on - Description
* newt_delay - Description
* newt_draw_form - Description
* newt_draw_root_text - Displays the string text at the position
indicated
* newt_entry_get_value - Description
* newt_entry_set_filter - Description
* newt_entry_set_flags - Description
* newt_entry_set - Description
* newt_entry - Description
* newt_finished - Uninitializes newt interface
* newt_form_add_component - Adds a single component to the form
* newt_form_add_components - Add several components to the form
* newt_form_add_hot_key - Description
* newt_form_destroy - Destroys a form
* newt_form_get_current - Description
* newt_form_run - Runs a form
* newt_form_set_background - Description
* newt_form_set_height - Description
* newt_form_set_size - Description
* newt_form_set_timer - Description
* newt_form_set_width - Description
* newt_form_watch_fd - Description
* newt_form - Create a form
* newt_get_screen_size - Fills in the passed references with the
current size of the terminal
* newt_grid_add_components_to_form - Description
* newt_grid_basic_window - Description
* newt_grid_free - Description
* newt_grid_get_size - Description
* newt_grid_h_close_stacked - Description
* newt_grid_h_stacked - Description
* newt_grid_place - Description
* newt_grid_set_field - Description
* newt_grid_simple_window - Description
* newt_grid_v_close_stacked - Description
* newt_grid_v_stacked - Description
* newt_grid_wrapped_window_at - Description
* newt_grid_wrapped_window - Description
* newt_init - Initialize newt
* newt_label_set_text - Description
* newt_label - Description
* newt_listbox_append_entry - Description
* newt_listbox_clear_selection - Description
* newt_listbox_clear - Description
* newt_listbox_delete_entry - Description
* newt_listbox_get_current - Description
* newt_listbox_get_selection - Description
* newt_listbox_insert_entry - Description
* newt_listbox_item_count - Description
* newt_listbox_select_item - Description
* newt_listbox_set_current_by_key - Description
* newt_listbox_set_current - Description
* newt_listbox_set_data - Description
* newt_listbox_set_entry - Description
* newt_listbox_set_width - Description
* newt_listbox - Description
* newt_listitem_get_data - Description
* newt_listitem_set - Description
* newt_listitem - Description
* newt_open_window - Open a window of the specified size and
position
* newt_pop_help_line - Replaces the current help line with the one
from the stack
* newt_pop_window - Removes the top window from the display
* newt_push_help_line - Saves the current help line on a stack, and
displays the new line
* newt_radio_get_current - Description
* newt_radiobutton - Description
* newt_redraw_help_line - Description
* newt_reflow_text - Description
* newt_refresh - Updates modified portions of the screen
* newt_resize_screen - Description
* newt_resume - Resume using the newt interface after calling
newt_suspend
* newt_run_form - Runs a form
* newt_scale_set - Description
* newt_scale - Description
* newt_scrollbar_set - Description
* newt_set_help_callback - Description
* newt_set_suspend_callback - Set a callback function which gets
invoked when user presses the suspend key
* newt_suspend - Tells newt to return the terminal to its initial
state
* newt_textbox_get_num_lines - Description
* newt_textbox_reflowed - Description
* newt_textbox_set_height - Description
* newt_textbox_set_text - Description
* newt_textbox - Description
* newt_vertical_scrollbar - Description
* newt_wait_for_key - Doesn't return until a key has been pressed
* newt_win_choice - Description
* newt_win_entries - Description
* newt_win_menu - Description
* newt_win_message - Description
* newt_win_messagev - Description
* newt_win_ternary - Description
----------------------------------------------------------------------
----------------------------------------------------------------------
Ncurses Terminal Screen Control
----------------------------------------------------------------------
Introduction
ncurses (new curses) is a free software emulation of curses in System V
Rel 4.0 (and above). It uses terminfo format, supports pads, colors,
multiple highlights, form characters and function key mapping. Because of
the interactive nature of this library, it will be of little use for
writing Web applications, but may be useful when writing scripts meant
using PHP from the command line.
The features available, such as colors, depend on the terminal that you
are using. Use functions such as ncurses_has_colors(),
ncurses_can_change_color(), and ncurses_has_ic() to check for individual
capabilities.
Note:
This extension has been moved to the >> PECL repository and is no longer
bundled with PHP as of PHP 5.3.0.
ncurses is available for the following platforms:
* AIX
* BeOS
* BSD variants (FreeBSD, NetBSD, OpenBSD)
* Cygwin
* Digital Unix (aka OSF1)
* GNU/Linux
* HPUX
* IRIX64
* Mac OS X
* OS/2
* QNX
* SCO OpenServer
* Solaris
* Tru64
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
You need the ncurses libraries and headerfiles. Download the latest
version from the >> ftp://ftp.gnu.org/pub/gnu/ncurses/ or from an other
GNU-Mirror.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here: >> http://pecl.php.net/package/ncurses.
Wide character CRT screen handling (ncursesw) support was added in version
1.0.1 of this PECL extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension defines window, panel and pad resources.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
Table of Contents
* Error codes
* Colors
* Keys
* Mouse
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
----------------------------------------------------------------------
Error codes
On error ncurses functions return -1. Some functions return 0 on success.
See the relevant pages in the documentation for actual return values.
----------------------------------------------------------------------
----------------------------------------------------------------------
Colors
ncurses color constants
constant meaning
NCURSES_COLOR_BLACK no color (black)
NCURSES_COLOR_WHITE white
NCURSES_COLOR_RED red - supported when terminal is in color mode
NCURSES_COLOR_GREEN green - supported when terminal is in color mode
NCURSES_COLOR_YELLOW yellow - supported when terminal is in color mode
NCURSES_COLOR_BLUE blue - supported when terminal is in color mode
NCURSES_COLOR_CYAN cyan - supported when terminal is in color mode
NCURSES_COLOR_MAGENTA magenta - supported when terminal is in color mode
----------------------------------------------------------------------
----------------------------------------------------------------------
Keys
ncurses key constants
constant meaning
NCURSES_KEY_F0 - NCURSES_KEY_F64 function keys F1 - F64
NCURSES_KEY_DOWN down arrow
NCURSES_KEY_UP up arrow
NCURSES_KEY_LEFT left arrow
NCURSES_KEY_RIGHT right arrow
NCURSES_KEY_HOME home key (upward+left arrow)
NCURSES_KEY_BACKSPACE backspace
NCURSES_KEY_DL delete line
NCURSES_KEY_IL insert line
NCURSES_KEY_DC delete character
NCURSES_KEY_IC insert char or enter insert mode
NCURSES_KEY_EIC exit insert char mode
NCURSES_KEY_CLEAR clear screen
NCURSES_KEY_EOS clear to end of screen
NCURSES_KEY_EOL clear to end of line
NCURSES_KEY_SF scroll one line forward
NCURSES_KEY_SR scroll one line backward
NCURSES_KEY_NPAGE next page
NCURSES_KEY_PPAGE previous page
NCURSES_KEY_STAB set tab
NCURSES_KEY_CTAB clear tab
NCURSES_KEY_CATAB clear all tabs
NCURSES_KEY_SRESET soft (partial) reset
NCURSES_KEY_RESET reset or hard reset
NCURSES_KEY_PRINT print
NCURSES_KEY_LL lower left
NCURSES_KEY_A1 upper left of keypad
NCURSES_KEY_A3 upper right of keypad
NCURSES_KEY_B2 center of keypad
NCURSES_KEY_C1 lower left of keypad
NCURSES_KEY_C3 lower right of keypad
NCURSES_KEY_BTAB back tab
NCURSES_KEY_BEG beginning
NCURSES_KEY_CANCEL cancel
NCURSES_KEY_CLOSE close
NCURSES_KEY_COMMAND cmd (command)
NCURSES_KEY_COPY copy
NCURSES_KEY_CREATE create
NCURSES_KEY_END end
NCURSES_KEY_EXIT exit
NCURSES_KEY_FIND find
NCURSES_KEY_HELP help
NCURSES_KEY_MARK mark
NCURSES_KEY_MESSAGE message
NCURSES_KEY_MOVE move
NCURSES_KEY_NEXT next
NCURSES_KEY_OPEN open
NCURSES_KEY_OPTIONS options
NCURSES_KEY_PREVIOUS previous
NCURSES_KEY_REDO redo
NCURSES_KEY_REFERENCE ref (reference)
NCURSES_KEY_REFRESH refresh
NCURSES_KEY_REPLACE replace
NCURSES_KEY_RESTART restart
NCURSES_KEY_RESUME resume
NCURSES_KEY_SAVE save
NCURSES_KEY_SBEG shiftet beg (beginning)
NCURSES_KEY_SCANCEL shifted cancel
NCURSES_KEY_SCOMMAND shifted command
NCURSES_KEY_SCOPY shifted copy
NCURSES_KEY_SCREATE shifted create
NCURSES_KEY_SDC shifted delete char
NCURSES_KEY_SDL shifted delete line
NCURSES_KEY_SELECT select
NCURSES_KEY_SEND shifted end
NCURSES_KEY_SEOL shifted end of line
NCURSES_KEY_SEXIT shifted exit
NCURSES_KEY_SFIND shifted find
NCURSES_KEY_SHELP shifted help
NCURSES_KEY_SHOME shifted home
NCURSES_KEY_SIC shifted input
NCURSES_KEY_SLEFT shifted left arrow
NCURSES_KEY_SMESSAGE shifted message
NCURSES_KEY_SMOVE shifted move
NCURSES_KEY_SNEXT shifted next
NCURSES_KEY_SOPTIONS shifted options
NCURSES_KEY_SPREVIOUS shifted previous
NCURSES_KEY_SPRINT shifted print
NCURSES_KEY_SREDO shifted redo
NCURSES_KEY_SREPLACE shifted replace
NCURSES_KEY_SRIGHT shifted right arrow
NCURSES_KEY_SRSUME shifted resume
NCURSES_KEY_SSAVE shifted save
NCURSES_KEY_SSUSPEND shifted suspend
NCURSES_KEY_UNDO undo
NCURSES_KEY_MOUSE mouse event has occurred
NCURSES_KEY_MAX maximum key value
----------------------------------------------------------------------
----------------------------------------------------------------------
Mouse
mouse constants
Constant meaning
NCURSES_BUTTON1_RELEASED - NCURSES_BUTTON4_RELEASED button (1-4) released
NCURSES_BUTTON1_PRESSED - NCURSES_BUTTON4_PRESSED button (1-4) pressed
NCURSES_BUTTON1_CLICKED - NCURSES_BUTTON4_CLICKED button (1-4) clicked
NCURSES_BUTTON1_DOUBLE_CLICKED - button (1-4) double
NCURSES_BUTTON4_DOUBLE_CLICKED clicked
NCURSES_BUTTON1_TRIPLE_CLICKED - button (1-4) triple
NCURSES_BUTTON4_TRIPLE_CLICKED clicked
NCURSES_BUTTON_CTRL ctrl pressed during
click
NCURSES_BUTTON_SHIFT shift pressed during
click
NCURSES_BUTTON_ALT alt pressed during
click
NCURSES_ALL_MOUSE_EVENTS report all mouse
events
NCURSES_REPORT_MOUSE_POSITION report mouse position
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Ncurses Functions
----------------------------------------------------------------------
ncurses_addch
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_addch - Add character at current position and advance cursor
Description
int ncurses_addch ( int $ch )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
ch
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_addchnstr
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_addchnstr - Add attributed string with specified length at current
position
Description
int ncurses_addchnstr ( string $s , int $n )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
s
n
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_addchstr
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_addchstr - Add attributed string at current position
Description
int ncurses_addchstr ( string $s )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
s
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_addnstr
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_addnstr - Add string with specified length at current position
Description
int ncurses_addnstr ( string $s , int $n )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
s
n
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_addstr
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_addstr - Output text at current position
Description
int ncurses_addstr ( string $text )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
text
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_assume_default_colors
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_assume_default_colors - Define default colors for color 0
Description
int ncurses_assume_default_colors ( int $fg , int $bg )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
fg
bg
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_attroff
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_attroff - Turn off the given attributes
Description
int ncurses_attroff ( int $attributes )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
attributes
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_attron
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_attron - Turn on the given attributes
Description
int ncurses_attron ( int $attributes )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
attributes
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_attrset
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_attrset - Set given attributes
Description
int ncurses_attrset ( int $attributes )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
attributes
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_baudrate
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_baudrate - Returns baudrate of terminal
Description
int ncurses_baudrate ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_beep
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_beep - Let the terminal beep
Description
int ncurses_beep ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
ncurses_beep() sends an audible alert (bell) and if its not possible
flashes the screen.
See Also
* ncurses_flash() - Flash terminal screen (visual bell)
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_bkgd
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_bkgd - Set background property for terminal screen
Description
int ncurses_bkgd ( int $attrchar )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
attrchar
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_bkgdset
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_bkgdset - Control screen background
Description
void ncurses_bkgdset ( int $attrchar )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
attrchar
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_border
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_border - Draw a border around the screen using attributed
characters
Description
int ncurses_border ( int $left , int $right , int $top , int $bottom , int
$tl_corner , int $tr_corner , int $bl_corner , int $br_corner )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Draws the specified lines and corners around the main window.
Use ncurses_wborder() for borders around subwindows!
Parameters
Every parameter expects 0 to draw a line or 1 to skip it.
left
right
top
bottom
tl_corner
Top left corner
tr_corner
Top right corner
bl_corner
Bottom left corner
br_corner
Bottom right corner
See Also
* ncurses_wborder() - Draws a border around the window using attributed
characters
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_bottom_panel
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_bottom_panel - Moves a visible panel to the bottom of the stack
Description
int ncurses_bottom_panel ( resource $panel )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
panel
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_can_change_color
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_can_change_color - Checks if terminal color definitions can be
changed
Description
bool ncurses_can_change_color ( void )
Checks whether the terminal has color capabilities and whether the
programmer can change color definitions using ncurses_init_color().
ncurses must be initialized using ncurses_init() before calling this
function.
Parameters
This function has no parameters.
Return Values
Return TRUE if the programmer can change color definitions, FALSE
otherwise.
See Also
* ncurses_has_colors() - Checks if terminal has color capabilities
* ncurses_init_color() - Define a terminal color
* ncurses_start_color() - Initializes color functionality
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_cbreak
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_cbreak - Switch of input buffering
Description
bool ncurses_cbreak ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Disables line buffering and character processing (interrupt and flow
control characters are unaffected), making characters typed by the user
immediately available to the program.
Return Values
Returns TRUE or NCURSES_ERR if any error occurred.
See Also
* ncurses_nocbreak() - Switch terminal to cooked mode
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_clear
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_clear - Clear screen
Description
bool ncurses_clear ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Clears the screen completely without setting blanks.
Note: ncurses_clear() clears the screen without setting blanks, which have
the current background rendition. To clear screen with blanks, use
ncurses_erase().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ncurses_erase() - Erase terminal screen
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_clrtobot
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_clrtobot - Clear screen from current position to bottom
Description
bool ncurses_clrtobot ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Erases all lines from cursor to end of screen and creates blanks. Blanks
created by ncurses_clrtobot() have the current background rendition.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ncurses_clear() - Clear screen
* ncurses_clrtoeol() - Clear screen from current position to end of line
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_clrtoeol
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_clrtoeol - Clear screen from current position to end of line
Description
bool ncurses_clrtoeol ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Erases the current line from cursor position to the end. Blanks created by
ncurses_clrtoeol() have the current background rendition.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ncurses_clear() - Clear screen
* ncurses_clrtobot() - Clear screen from current position to bottom
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_color_content
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_color_content - Retrieves RGB components of a color
Description
int ncurses_color_content ( int $color , int &$r , int &$g , int &$b )
Retrieves the red, green, and blue components for the given color
definition. Terminal color capabilities must be initialized with
ncurses_start_color() prior to calling this function.
Parameters
color
The number of the color to retrieve information for. May be one of
the pre-defined color constants.
r
A reference to which to return the red component of the color. The
value returned to the reference will be between 0 and 1000.
g
A reference to which to return the green component of the color.
The value returned to the reference will be between 0 and 1000.
b
A reference to which to return the blue component of the color.
The value returned to the reference will be between 0 and 1000.
Return Values
Returns -1 if the function was successful, and 0 if ncurses or terminal
color capabilities have not been initialized.
See Also
* ncurses_init_color() - Define a terminal color
* ncurses_start_color() - Initializes color functionality
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_color_set
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_color_set - Set active foreground and background colors
Description
int ncurses_color_set ( int $pair )
Sets the active foreground and background colors. Any characters written
after this function is invoked will have these colors. This function
requires terminal colors to be supported and initialized using
ncurses_start_color() beforehand.
ncurses uses color pairs to specify both foreground and background colors.
Use ncurses_init_pair() to define a color pair.
Parameters
pair
The color pair from which to get the foreground and background
colors to set as the active colors.
Return Values
Returns -1 on success, and 0 on failure.
Examples
Example #1 Writing a string with a specified color to the screen
See Also
* ncurses_init_pair() - Define a color pair
* ncurses_start_color() - Initializes color functionality
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_curs_set
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_curs_set - Set cursor state
Description
int ncurses_curs_set ( int $visibility )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
visibility
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_def_prog_mode
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_def_prog_mode - Saves terminals (program) mode
Description
bool ncurses_def_prog_mode ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Saves the current terminal modes for program (in curses) for use by
ncurses_reset_prog_mode().
Return Values
Returns FALSE on success, otherwise TRUE.
See Also
* ncurses_reset_prog_mode() - Resets the prog mode saved by
def_prog_mode
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_def_shell_mode
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_def_shell_mode - Saves terminals (shell) mode
Description
bool ncurses_def_shell_mode ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Saves the current terminal modes for shell (not in curses) for use by
ncurses_reset_shell_mode().
Return Values
Returns FALSE on success, TRUE otherwise.
See Also
* ncurses_reset_shell_mode() - Resets the shell mode saved by
def_shell_mode
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_define_key
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_define_key - Define a keycode
Description
int ncurses_define_key ( string $definition , int $keycode )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
definition
keycode
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_del_panel
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_del_panel - Remove panel from the stack and delete it (but not the
associated window)
Description
bool ncurses_del_panel ( resource $panel )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
panel
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_delay_output
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_delay_output - Delay output on terminal using padding characters
Description
int ncurses_delay_output ( int $milliseconds )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
milliseconds
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_delch
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_delch - Delete character at current position, move rest of line
left
Description
bool ncurses_delch ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Deletes the character under the cursor. All characters to the right of the
cursor on the same line are moved to the left one position and the last
character on the line is filled with a blank. The cursor position does not
change.
Return Values
Returns FALSE on success, TRUE otherwise.
See Also
* ncurses_deleteln() - Delete line at current position, move rest of
screen up
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_deleteln
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_deleteln - Delete line at current position, move rest of screen up
Description
bool ncurses_deleteln ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Deletes the current line under cursorposition. All lines below the current
line are moved up one line. The bottom line of window is cleared. Cursor
position does not change.
Return Values
Returns FALSE on success, otherwise TRUE.
See Also
* ncurses_delch() - Delete character at current position, move rest of
line left
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_delwin
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_delwin - Delete a ncurses window
Description
bool ncurses_delwin ( resource $window )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_doupdate
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_doupdate - Write all prepared refreshes to terminal
Description
bool ncurses_doupdate ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Compares the virtual screen to the physical screen and updates the
physical screen. This way is more effective than using multiple refresh
calls.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_echo
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_echo - Activate keyboard input echo
Description
bool ncurses_echo ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Enables echo mode. All characters typed by user are echoed by
ncurses_getch().
Return Values
Returns FALSE on success, TRUE if any error occurred.
See Also
* ncurses_noecho() - Switch off keyboard input echo to disable echo mode
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_echochar
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_echochar - Single character output including refresh
Description
int ncurses_echochar ( int $character )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
character
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_end
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_end - Stop using ncurses, clean up the screen
Description
int ncurses_end ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_erase
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_erase - Erase terminal screen
Description
bool ncurses_erase ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Fills the terminal screen with blanks.
Created blanks have the current background rendition, set by
ncurses_bkgd().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ncurses_bkgd() - Set background property for terminal screen
* ncurses_clear() - Clear screen
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_erasechar
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_erasechar - Returns current erase character
Description
string ncurses_erasechar ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Returns the current erase character.
Return Values
The current erase char, as a string.
See Also
* ncurses_killchar() - Returns current line kill character
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_filter
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_filter - Set LINES for iniscr() and newterm() to 1
Description
void ncurses_filter ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_flash
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_flash - Flash terminal screen (visual bell)
Description
bool ncurses_flash ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Flashes the screen, and if its not possible, sends an audible alert
(bell).
Return Values
Returns FALSE on success, otherwise TRUE.
See Also
* ncurses_beep() - Let the terminal beep
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_flushinp
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_flushinp - Flush keyboard input buffer
Description
bool ncurses_flushinp ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Throws away any typeahead that has been typed and has not yet been read by
your program.
Return Values
Returns FALSE on success, otherwise TRUE.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_getch
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_getch - Read a character from keyboard
Description
int ncurses_getch ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_getmaxyx
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_getmaxyx - Returns the size of a window
Description
void ncurses_getmaxyx ( resource $window , int &$y , int &$x )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Gets the horizontal and vertical size of the given window into the given
variables.
Variables must be passed as reference, so they are updated when the user
changes the terminal size.
Parameters
window
The measured window
y
This will be set to the window height
x
This will be set to the window width
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_getmouse
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_getmouse - Reads mouse event
Description
bool ncurses_getmouse ( array &$mevent )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
ncurses_getmouse() reads mouse event out of queue.
Parameters
mevent
Event options will be delivered in this parameter which has to be
an array, passed by reference (see example below).
On success an associative array with following keys will be
delivered:
* "id" : Id to distinguish multiple devices
* "x" : screen relative x-position in character cells
* "y" : screen relative y-position in character cells
* "z" : currently not supported
* "mmask" : Mouse action
Return Values
Returns FALSE if a mouse event is actually visible in the given window,
otherwise returns TRUE.
Examples
Example #1 ncurses_getmouse() example
See Also
* ncurses_ungetmouse() - Pushes mouse event to queue
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_getyx
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_getyx - Returns the current cursor position for a window
Description
void ncurses_getyx ( resource $window , int &$y , int &$x )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
y
x
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_halfdelay
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_halfdelay - Put terminal into halfdelay mode
Description
int ncurses_halfdelay ( int $tenth )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
tenth
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_has_colors
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_has_colors - Checks if terminal has color capabilities
Description
bool ncurses_has_colors ( void )
Checks whether the terminal has color capabilities. This function can be
used to write terminal-independent programs. ncurses must be initialized
using ncurses_init() before calling this function.
Parameters
This function has no parameters.
Return Values
Return TRUE if the terminal has color capabilities, FALSE otherwise.
Examples
Example #1 Writing a string with a specified color to the screen
See Also
* ncurses_can_change_color() - Checks if terminal color definitions can
be changed
* ncurses_start_color() - Initializes color functionality
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_has_ic
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_has_ic - Check for insert- and delete-capabilities
Description
bool ncurses_has_ic ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Checks whether the terminal has insert and delete capabilities.
Return Values
Returns TRUE if the terminal has insert/delete-capabilities, FALSE
otherwise.
See Also
* ncurses_has_il() - Check for line insert- and delete-capabilities
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_has_il
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_has_il - Check for line insert- and delete-capabilities
Description
bool ncurses_has_il ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Checks whether the terminal has insert- and delete-line-capabilities.
Return Values
Returns TRUE if the terminal has insert/delete-line capabilities, FALSE
otherwise.
See Also
* ncurses_has_ic() - Check for insert- and delete-capabilities
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_has_key
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_has_key - Check for presence of a function key on terminal
keyboard
Description
int ncurses_has_key ( int $keycode )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
keycode
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_hide_panel
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_hide_panel - Remove panel from the stack, making it invisible
Description
int ncurses_hide_panel ( resource $panel )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
panel
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_hline
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_hline - Draw a horizontal line at current position using an
attributed character and max. n characters long
Description
int ncurses_hline ( int $charattr , int $n )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
charattr
n
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_inch
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_inch - Get character and attribute at current position
Description
string ncurses_inch ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Returns the character from the current position.
Return Values
Returns the character, as a string.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_init_color
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_init_color - Define a terminal color
Description
int ncurses_init_color ( int $color , int $r , int $g , int $b )
Defines or redefines the given color. When this function is called, all
occurrences of the given color on the screen, if any, immediately change
to the new definition.
Color capabilities must be supported by the terminal and initialized using
ncurses_start_color() prior to calling this function. In addition, the
terminal must have color changing capabilities; use
ncurses_can_change_color() to check for this.
Parameters
color
The identification number of the color to redefine. It may be one
of the default color constants.
r
A color value, between 0 and 1000, for the red component.
g
A color value, between 0 and 1000, for the green component.
b
A color value, between 0 and 1000, for the blue component.
Return Values
Returns -1 if the function was successful, and 0 if ncurses or terminal
color capabilities have not been initialized or the terminal does not have
color changing capabilities.
See Also
* ncurses_color_content() - Retrieves RGB components of a color
* ncurses_start_color() - Initializes color functionality
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_init_pair
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_init_pair - Define a color pair
Description
int ncurses_init_pair ( int $pair , int $fg , int $bg )
Defines or redefines the given color pair to have the given foreground and
background colors. If the color pair was previously initialized, the
screen is refreshed and all occurrences of it are changed to reflect the
new definition.
Color capabilities must be initialized using ncurses_start_color() before
calling this function. The first color pair (color pair 0) is assumed to
be white on black by default, but can be changed using
ncurses_assume_default_colors().
Parameters
pair
The number of the color pair to define.
fg
The foreground color for the color pair. May be one of the
pre-defined colors or one defined by ncurses_init_color() if the
terminal has color changing capabilities.
bg
The background color for the color pair. May be one of the
pre-defined colors or one defined by ncurses_init_color() if the
terminal has color changing capabilities.
Return Values
Returns -1 if the function was successful, and 0 if ncurses or color
support were not initialized.
Notes
Note that color changing capabilities are not required for defining color
pairs of pre-existing colors, but only for changing definitions (red,
green, and blue components) of colors themselves per ncurses_init_color().
Examples
Example #1 Writing a string with a specified color to the screen
See Also
* ncurses_pair_content() - Retrieves foreground and background colors of
a color pair
* ncurses_start_color() - Initializes color functionality
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_init
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_init - Initialize ncurses
Description
void ncurses_init ( void )
Initializes the ncurses interface. This function must be used before any
other ncurses function call.
Note that ncurses_end() must be called before exiting from the program, or
the terminal will not be restored to its proper non-visual mode.
Parameters
This function has no parameters.
Return Values
No value is returned.
See Also
* ncurses_end() - Stop using ncurses, clean up the screen
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_insch
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_insch - Insert character moving rest of line including character
at current position
Description
int ncurses_insch ( int $character )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
character
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_insdelln
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_insdelln - Insert lines before current line scrolling down
(negative numbers delete and scroll up)
Description
int ncurses_insdelln ( int $count )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
count
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_insertln
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_insertln - Insert a line, move rest of screen down
Description
int ncurses_insertln ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Inserts a new line above the current line. The bottom line will be lost.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_insstr
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_insstr - Insert string at current position, moving rest of line
right
Description
int ncurses_insstr ( string $text )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
text
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_instr
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_instr - Reads string from terminal screen
Description
int ncurses_instr ( string &$buffer )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Reads a string from the terminal screen and returns the number of
characters read from the current character position until end of line.
Parameters
buffer
The characters. Attributes will be stripped.
Return Values
Returns the number of characters.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_isendwin
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_isendwin - Ncurses is in endwin mode, normal screen output may be
performed
Description
bool ncurses_isendwin ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Checks if ncurses is in endwin mode.
Return Values
Returns TRUE, if ncurses_end() has been called without any subsequent
calls to ncurses_wrefresh(), FALSE otherwise.
See Also
* ncurses_end() - Stop using ncurses, clean up the screen
* ncurses_wrefresh() - Refresh window on terminal screen
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_keyok
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_keyok - Enable or disable a keycode
Description
int ncurses_keyok ( int $keycode , bool $enable )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
keycode
enable
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_keypad
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_keypad - Turns keypad on or off
Description
int ncurses_keypad ( resource $window , bool $bf )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
bf
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_killchar
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_killchar - Returns current line kill character
Description
string ncurses_killchar ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Returns the current line kill character.
Return Values
Returns the kill character, as a string.
See Also
* ncurses_erasechar() - Returns current erase character
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_longname
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_longname - Returns terminals description
Description
string ncurses_longname ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Returns a verbose description of the terminal.
Return Values
Returns the description, as a string truncated to 128 characters. On
errors, returns NULL.
See Also
* ncurses_termname() - Returns terminals (short)-name
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_meta
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_meta - Enables/Disable 8-bit meta key information
Description
int ncurses_meta ( resource $window , bool $8bit )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
8bit
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_mouse_trafo
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mouse_trafo - Transforms coordinates
Description
bool ncurses_mouse_trafo ( int &$y , int &$x , bool $toscreen )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
y
x
toscreen
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_mouseinterval
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mouseinterval - Set timeout for mouse button clicks
Description
int ncurses_mouseinterval ( int $milliseconds )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
milliseconds
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_mousemask
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mousemask - Sets mouse options
Description
int ncurses_mousemask ( int $newmask , int &$oldmask )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Sets mouse events to be reported. By default no mouse events will be
reported.
Mouse events are represented by NCURSES_KEY_MOUSE in the ncurses_wgetch()
input stream. To read the event data and pop the event of queue, call
ncurses_getmouse().
Parameters
newmask
Mouse mask options can be set with the following predefined
constants:
* NCURSES_BUTTON1_PRESSED
* NCURSES_BUTTON1_RELEASED
* NCURSES_BUTTON1_CLICKED
* NCURSES_BUTTON1_DOUBLE_CLICKED
* NCURSES_BUTTON1_TRIPLE_CLICKED
* NCURSES_BUTTON2_PRESSED
* NCURSES_BUTTON2_RELEASED
* NCURSES_BUTTON2_CLICKED
* NCURSES_BUTTON2_DOUBLE_CLICKED
* NCURSES_BUTTON2_TRIPLE_CLICKED
* NCURSES_BUTTON3_PRESSED
* NCURSES_BUTTON3_RELEASED
* NCURSES_BUTTON3_CLICKED
* NCURSES_BUTTON3_DOUBLE_CLICKED
* NCURSES_BUTTON3_TRIPLE_CLICKED
* NCURSES_BUTTON4_PRESSED
* NCURSES_BUTTON4_RELEASED
* NCURSES_BUTTON4_CLICKED
* NCURSES_BUTTON4_DOUBLE_CLICKED
* NCURSES_BUTTON4_TRIPLE_CLICKED
* NCURSES_BUTTON_SHIFT>
* NCURSES_BUTTON_CTRL
* NCURSES_BUTTON_ALT
* NCURSES_ALL_MOUSE_EVENTS
* NCURSES_REPORT_MOUSE_POSITION
As a side effect, setting a zero mousemask in newmask turns off
the mouse pointer. Setting a non zero value turns mouse pointer
on.
oldmask
This will be set to the previous value of the mouse event mask.
Return Values
Returns a mask to indicated which of the in parameter newmask specified
mouse events can be reported. On complete failure, it returns 0.
Examples
Example #1 ncurses_mousemask() example
See Also
* ncurses_getch() - Read a character from keyboard
* ncurses_getmouse() - Reads mouse event
* ncurses_ungetmouse() - Pushes mouse event to queue
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_move_panel
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_move_panel - Moves a panel so that its upper-left corner is at
[startx, starty]
Description
int ncurses_move_panel ( resource $panel , int $startx , int $starty )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
panel
startx
starty
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_move
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_move - Move output position
Description
int ncurses_move ( int $y , int $x )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
y
x
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_mvaddch
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvaddch - Move current position and add character
Description
int ncurses_mvaddch ( int $y , int $x , int $c )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
y
x
c
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_mvaddchnstr
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvaddchnstr - Move position and add attributed string with
specified length
Description
int ncurses_mvaddchnstr ( int $y , int $x , string $s , int $n )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
y
x
s
n
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_mvaddchstr
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvaddchstr - Move position and add attributed string
Description
int ncurses_mvaddchstr ( int $y , int $x , string $s )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
y
x
s
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_mvaddnstr
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvaddnstr - Move position and add string with specified length
Description
int ncurses_mvaddnstr ( int $y , int $x , string $s , int $n )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
y
x
s
n
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_mvaddstr
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvaddstr - Move position and add string
Description
int ncurses_mvaddstr ( int $y , int $x , string $s )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
y
x
s
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_mvcur
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvcur - Move cursor immediately
Description
int ncurses_mvcur ( int $old_y , int $old_x , int $new_y , int $new_x )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
old_y
old_x
new_y
new_x
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_mvdelch
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvdelch - Move position and delete character, shift rest of line
left
Description
int ncurses_mvdelch ( int $y , int $x )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
y
x
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_mvgetch
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvgetch - Move position and get character at new position
Description
int ncurses_mvgetch ( int $y , int $x )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
y
x
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_mvhline
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvhline - Set new position and draw a horizontal line using an
attributed character and max. n characters long
Description
int ncurses_mvhline ( int $y , int $x , int $attrchar , int $n )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
y
x
attrchar
n
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_mvinch
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvinch - Move position and get attributed character at new
position
Description
int ncurses_mvinch ( int $y , int $x )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
y
x
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_mvvline
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvvline - Set new position and draw a vertical line using an
attributed character and max. n characters long
Description
int ncurses_mvvline ( int $y , int $x , int $attrchar , int $n )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
y
x
attrchar
n
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_mvwaddstr
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvwaddstr - Add string at new position in window
Description
int ncurses_mvwaddstr ( resource $window , int $y , int $x , string $text
)
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
y
x
text
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_napms
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_napms - Sleep
Description
int ncurses_napms ( int $milliseconds )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
milliseconds
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_new_panel
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_new_panel - Create a new panel and associate it with window
Description
resource ncurses_new_panel ( resource $window )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_newpad
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_newpad - Creates a new pad (window)
Description
resource ncurses_newpad ( int $rows , int $cols )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
rows
cols
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_newwin
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_newwin - Create a new window
Description
resource ncurses_newwin ( int $rows , int $cols , int $y , int $x )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Creates a new window to draw elements in.
When creating additional windows, remember to use ncurses_getmaxyx() to
check for available space, as terminal size is individual and may vary.
Parameters
rows
Number of rows
cols
Number of columns
y
y-coordinate of the origin
x
x-coordinate of the origin
Return Values
Returns a resource ID for the new window.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_nl
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_nl - Translate newline and carriage return / line feed
Description
bool ncurses_nl ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_nocbreak
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_nocbreak - Switch terminal to cooked mode
Description
bool ncurses_nocbreak ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Returns terminal to normal (cooked) mode. Initially the terminal may or
may not in cbreak mode as the mode is inherited. Therefore a program
should call ncurses_cbreak() and ncurses_nocbreak() explicitly.
Return Values
Returns TRUE if any error occurred, otherwise FALSE.
See Also
* ncurses_cbreak() - Switch of input buffering
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_noecho
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_noecho - Switch off keyboard input echo
Description
bool ncurses_noecho ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Prevents echoing of user typed characters.
Return Values
Returns TRUE if any error occurred, FALSE otherwise.
See Also
* ncurses_echo() - Activate keyboard input echo
* ncurses_getch() - Read a character from keyboard
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_nonl
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_nonl - Do not translate newline and carriage return / line feed
Description
bool ncurses_nonl ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_noqiflush
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_noqiflush - Do not flush on signal characters
Description
void ncurses_noqiflush ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_noraw
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_noraw - Switch terminal out of raw mode
Description
bool ncurses_noraw ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Switches the terminal out of raw mode. Raw mode is similar to cbreak mode,
in that characters typed are immediately passed through to the user
program. The differences that are that in raw mode, the interrupt, quit,
suspend and flow control characters are all passed through uninterpreted,
instead of generating a signal.
Return Values
Returns TRUE if any error occurred, otherwise FALSE.
See Also
* ncurses_raw() - Switch terminal into raw mode
* ncurses_cbreak() - Switch of input buffering
* ncurses_nocbreak() - Switch terminal to cooked mode
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_pair_content
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_pair_content - Retrieves foreground and background colors of a
color pair
Description
int ncurses_pair_content ( int $pair , int &$f , int &$b )
Retrieves the foreground and background colors that constitute the given
color pair. Terminal color capabilities must be initialized with
ncurses_start_color() prior to calling this function.
Parameters
pair
The number of the color pair to retrieve information for.
f
A reference to which to return the foreground color of the color
pair. The information returned will be a color number referring to
one of the pre-defined colors or a color defined previously by
ncurses_init_color() if the terminal supports color changing.
b
A reference to which to return the background color of the color
pair. The information returned will be a color number referring to
one of the pre-defined colors or a color defined previously by
ncurses_init_color() if the terminal supports color changing.
Return Values
Returns -1 if the function was successful, and 0 if ncurses or terminal
color capabilities have not been initialized.
See Also
* ncurses_init_pair() - Define a color pair
* ncurses_start_color() - Initializes color functionality
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_panel_above
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_panel_above - Returns the panel above panel
Description
resource ncurses_panel_above ( resource $panel )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
panel
Return Values
If panel is null, returns the bottom panel in the stack.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_panel_below
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_panel_below - Returns the panel below panel
Description
resource ncurses_panel_below ( resource $panel )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
panel
Parameters
If panel is null, returns the top panel in the stack.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_panel_window
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_panel_window - Returns the window associated with panel
Description
resource ncurses_panel_window ( resource $panel )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
panel
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_pnoutrefresh
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_pnoutrefresh - Copies a region from a pad into the virtual screen
Description
int ncurses_pnoutrefresh ( resource $pad , int $pminrow , int $pmincol ,
int $sminrow , int $smincol , int $smaxrow , int $smaxcol )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
pad
pminrow
pmincol
sminrow
smincol
smaxrow
smaxcol
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_prefresh
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_prefresh - Copies a region from a pad into the virtual screen
Description
int ncurses_prefresh ( resource $pad , int $pminrow , int $pmincol , int
$sminrow , int $smincol , int $smaxrow , int $smaxcol )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
pad
pminrow
pmincol
sminrow
smincol
smaxrow
smaxcol
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_putp
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_putp - Apply padding information to the string and output it
Description
int ncurses_putp ( string $text )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
text
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_qiflush
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_qiflush - Flush on signal characters
Description
void ncurses_qiflush ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_raw
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_raw - Switch terminal into raw mode
Description
bool ncurses_raw ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Places the terminal in raw mode. Raw mode is similar to cbreak mode, in
that characters typed are immediately passed through to the user program.
The differences that are that in raw mode, the interrupt, quit, suspend
and flow control characters are all passed through uninterpreted, instead
of generating a signal.
Return Values
Returns TRUE if any error occurred, otherwise FALSE.
See Also
* ncurses_noraw() - Switch terminal out of raw mode
* ncurses_cbreak() - Switch of input buffering
* ncurses_nocbreak() - Switch terminal to cooked mode
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_refresh
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_refresh - Refresh screen
Description
int ncurses_refresh ( int $ch )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
ch
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_replace_panel
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_replace_panel - Replaces the window associated with panel
Description
int ncurses_replace_panel ( resource $panel , resource $window )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
panel
window
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_reset_prog_mode
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_reset_prog_mode - Resets the prog mode saved by def_prog_mode
Description
int ncurses_reset_prog_mode ( void )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_reset_shell_mode
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_reset_shell_mode - Resets the shell mode saved by def_shell_mode
Description
int ncurses_reset_shell_mode ( void )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_resetty
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_resetty - Restores saved terminal state
Description
bool ncurses_resetty ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Restores the terminal state, which was previously saved by calling
ncurses_savetty().
Return Values
Always returns FALSE.
See Also
* ncurses_savetty() - Saves terminal state
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_savetty
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_savetty - Saves terminal state
Description
bool ncurses_savetty ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Saves the current terminal state. The saved terminal state can be restored
with ncurses_resetty().
Return Values
Always returns FALSE.
See Also
* ncurses_resetty() - Restores saved terminal state
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_scr_dump
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_scr_dump - Dump screen content to file
Description
int ncurses_scr_dump ( string $filename )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
filename
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_scr_init
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_scr_init - Initialize screen from file dump
Description
int ncurses_scr_init ( string $filename )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
filename
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_scr_restore
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_scr_restore - Restore screen from file dump
Description
int ncurses_scr_restore ( string $filename )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
filename
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_scr_set
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_scr_set - Inherit screen from file dump
Description
int ncurses_scr_set ( string $filename )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
filename
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_scrl
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_scrl - Scroll window content up or down without changing current
position
Description
int ncurses_scrl ( int $count )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
count
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_show_panel
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_show_panel - Places an invisible panel on top of the stack, making
it visible
Description
int ncurses_show_panel ( resource $panel )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
panel
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_slk_attr
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_attr - Returns current soft label key attribute
Description
int ncurses_slk_attr ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Returns the current soft label key attribute.
Return Values
The attribute, as an integer.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_slk_attroff
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_attroff - Turn off the given attributes for soft function-key
labels
Description
int ncurses_slk_attroff ( int $intarg )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
intarg
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_slk_attron
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_attron - Turn on the given attributes for soft function-key
labels
Description
int ncurses_slk_attron ( int $intarg )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
intarg
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_slk_attrset
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_attrset - Set given attributes for soft function-key labels
Description
int ncurses_slk_attrset ( int $intarg )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
intarg
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_slk_clear
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_clear - Clears soft labels from screen
Description
bool ncurses_slk_clear ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
The function ncurses_slk_clear() clears soft label keys from screen.
Return Values
Returns TRUE on errors, FALSE otherwise.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_slk_color
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_color - Sets color for soft label keys
Description
int ncurses_slk_color ( int $intarg )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
intarg
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_slk_init
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_init - Initializes soft label key functions
Description
bool ncurses_slk_init ( int $format )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Initializes soft label key functions
This function must be called before ncurses_init() or ncurses_newwin() is
called.
Parameters
format
If ncurses_init() eventually uses a line from stdscr to emulate
the soft labels, then this parameter determines how the labels are
arranged of the screen.
0 indicates a 3-2-3 arrangement of the labels, 1 indicates a 4-4
arrangement and 2 indicates the PC like 4-4-4 mode, but in
addition an index line will be created.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_slk_noutrefresh
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_noutrefresh - Copies soft label keys to virtual screen
Description
bool ncurses_slk_noutrefresh ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_slk_refresh
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_refresh - Copies soft label keys to screen
Description
int ncurses_slk_refresh ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Copies soft label keys from virtual screen to physical screen.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_slk_restore
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_restore - Restores soft label keys
Description
int ncurses_slk_restore ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Restores the soft label keys after ncurses_slk_clear() has been performed.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_slk_set
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_set - Sets function key labels
Description
bool ncurses_slk_set ( int $labelnr , string $label , int $format )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
labelnr
label
format
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_slk_touch
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_touch - Forces output when ncurses_slk_noutrefresh is
performed
Description
int ncurses_slk_touch ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Forces all the soft labels to be output the next time a
ncurses_slk_noutrefresh() is performed.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_standend
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_standend - Stop using 'standout' attribute
Description
int ncurses_standend ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_standout
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_standout - Start using 'standout' attribute
Description
int ncurses_standout ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_start_color
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_start_color - Initializes color functionality
Description
int ncurses_start_color ( void )
Initializes color functionality in ncurses. This function must be called
before any color manipulation functions are called and after
ncurses_init() is called. It is good practice to call this function right
after ncurses_init().
Parameters
This function has no parameters.
Return Values
Returns 0 on success, or -1 if the color table could not be allocated or
ncurses was not initialized.
Examples
Example #1 Writing a string with a specified color to the screen
See Also
* ncurses_can_change_color() - Checks if terminal color definitions can
be changed
* ncurses_has_colors() - Checks if terminal has color capabilities
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_termattrs
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_termattrs - Returns a logical OR of all attribute flags supported
by terminal
Description
bool ncurses_termattrs ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_termname
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_termname - Returns terminals (short)-name
Description
string ncurses_termname ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Returns terminals shortname.
Return Values
Returns the shortname of the terminal, truncated to 14 characters. On
errors, returns NULL.
See Also
* ncurses_longname() - Returns terminals description
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_timeout
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_timeout - Set timeout for special key sequences
Description
void ncurses_timeout ( int $millisec )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
millisec
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_top_panel
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_top_panel - Moves a visible panel to the top of the stack
Description
int ncurses_top_panel ( resource $panel )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
panel
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_typeahead
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_typeahead - Specify different filedescriptor for typeahead
checking
Description
int ncurses_typeahead ( int $fd )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
fd
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_ungetch
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_ungetch - Put a character back into the input stream
Description
int ncurses_ungetch ( int $keycode )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
keycode
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_ungetmouse
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_ungetmouse - Pushes mouse event to queue
Description
bool ncurses_ungetmouse ( array $mevent )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Pushes a KEY_MOUSE event onto the unput queue and associates with this
event the given state sata and screen-relative character cell coordinates,
specified in mevent.
Parameters
mevent
An associative array specifying the event options:
* "id" : Id to distinguish multiple devices
* "x" : screen relative x-position in character cells
* "y" : screen relative y-position in character cells
* "z" : currently not supported
* "mmask" : Mouse action
Return Values
Returns FALSE on success, TRUE otherwise.
See Also
* ncurses_getmouse() - Reads mouse event
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_update_panels
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_update_panels - Refreshes the virtual screen to reflect the
relations between panels in the stack
Description
void ncurses_update_panels ( void )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_use_default_colors
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_use_default_colors - Assign terminal default colors to color id -1
Description
bool ncurses_use_default_colors ( void )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_use_env
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_use_env - Control use of environment information about terminal
size
Description
void ncurses_use_env ( bool $flag )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
flag
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_use_extended_names
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_use_extended_names - Control use of extended names in terminfo
descriptions
Description
int ncurses_use_extended_names ( bool $flag )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
flag
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_vidattr
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_vidattr - Display the string on the terminal in the video
attribute mode
Description
int ncurses_vidattr ( int $intarg )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
intarg
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_vline
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_vline - Draw a vertical line at current position using an
attributed character and max. n characters long
Description
int ncurses_vline ( int $charattr , int $n )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
charattr
n
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_waddch
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_waddch - Adds character at current position in a window and
advance cursor
Description
int ncurses_waddch ( resource $window , int $ch )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
ch
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_waddstr
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_waddstr - Outputs text at current postion in window
Description
int ncurses_waddstr ( resource $window , string $str [, int $n ] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
str
n
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_wattroff
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wattroff - Turns off attributes for a window
Description
int ncurses_wattroff ( resource $window , int $attrs )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
attrs
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_wattron
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wattron - Turns on attributes for a window
Description
int ncurses_wattron ( resource $window , int $attrs )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
attrs
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_wattrset
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wattrset - Set the attributes for a window
Description
int ncurses_wattrset ( resource $window , int $attrs )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
attrs
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_wborder
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wborder - Draws a border around the window using attributed
characters
Description
int ncurses_wborder ( resource $window , int $left , int $right , int $top
, int $bottom , int $tl_corner , int $tr_corner , int $bl_corner , int
$br_corner )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Draws the specified lines and corners around the passed window.
Use ncurses_border() for borders around the main window.
Parameters
Each parameter expects 0 to draw a line and 1 to skip it.
window
The window on which we operate
left
right
top
bottom
tl_corner
Top left corner
tr_corner
Top right corner
bl_corner
Bottom left corner
br_corner
Bottom right corner
See Also
* ncurses_border() - Draw a border around the screen using attributed
characters
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_wclear
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wclear - Clears window
Description
int ncurses_wclear ( resource $window )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_wcolor_set
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wcolor_set - Sets windows color pairings
Description
int ncurses_wcolor_set ( resource $window , int $color_pair )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
color_pair
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_werase
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_werase - Erase window contents
Description
int ncurses_werase ( resource $window )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_wgetch
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wgetch - Reads a character from keyboard (window)
Description
int ncurses_wgetch ( resource $window )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_whline
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_whline - Draws a horizontal line in a window at current position
using an attributed character and max. n characters long
Description
int ncurses_whline ( resource $window , int $charattr , int $n )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
charattr
n
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_wmouse_trafo
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wmouse_trafo - Transforms window/stdscr coordinates
Description
bool ncurses_wmouse_trafo ( resource $window , int &$y , int &$x , bool
$toscreen )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
x
y
toscreen
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_wmove
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wmove - Moves windows output position
Description
int ncurses_wmove ( resource $window , int $y , int $x )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
y
x
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_wnoutrefresh
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wnoutrefresh - Copies window to virtual screen
Description
int ncurses_wnoutrefresh ( resource $window )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_wrefresh
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wrefresh - Refresh window on terminal screen
Description
int ncurses_wrefresh ( resource $window )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_wstandend
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wstandend - End standout mode for a window
Description
int ncurses_wstandend ( resource $window )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_wstandout
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wstandout - Enter standout mode for a window
Description
int ncurses_wstandout ( resource $window )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
----------------------------------------------------------------------
----------------------------------------------------------------------
ncurses_wvline
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wvline - Draws a vertical line in a window at current position
using an attributed character and max. n characters long
Description
int ncurses_wvline ( resource $window , int $charattr , int $n )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
window
charattr
n
----------------------------------------------------------------------
Table of Contents
* ncurses_addch - Add character at current position and advance cursor
* ncurses_addchnstr - Add attributed string with specified length at
current position
* ncurses_addchstr - Add attributed string at current position
* ncurses_addnstr - Add string with specified length at current position
* ncurses_addstr - Output text at current position
* ncurses_assume_default_colors - Define default colors for color 0
* ncurses_attroff - Turn off the given attributes
* ncurses_attron - Turn on the given attributes
* ncurses_attrset - Set given attributes
* ncurses_baudrate - Returns baudrate of terminal
* ncurses_beep - Let the terminal beep
* ncurses_bkgd - Set background property for terminal screen
* ncurses_bkgdset - Control screen background
* ncurses_border - Draw a border around the screen using attributed
characters
* ncurses_bottom_panel - Moves a visible panel to the bottom of the
stack
* ncurses_can_change_color - Checks if terminal color definitions can be
changed
* ncurses_cbreak - Switch of input buffering
* ncurses_clear - Clear screen
* ncurses_clrtobot - Clear screen from current position to bottom
* ncurses_clrtoeol - Clear screen from current position to end of line
* ncurses_color_content - Retrieves RGB components of a color
* ncurses_color_set - Set active foreground and background colors
* ncurses_curs_set - Set cursor state
* ncurses_def_prog_mode - Saves terminals (program) mode
* ncurses_def_shell_mode - Saves terminals (shell) mode
* ncurses_define_key - Define a keycode
* ncurses_del_panel - Remove panel from the stack and delete it (but not
the associated window)
* ncurses_delay_output - Delay output on terminal using padding
characters
* ncurses_delch - Delete character at current position, move rest of
line left
* ncurses_deleteln - Delete line at current position, move rest of
screen up
* ncurses_delwin - Delete a ncurses window
* ncurses_doupdate - Write all prepared refreshes to terminal
* ncurses_echo - Activate keyboard input echo
* ncurses_echochar - Single character output including refresh
* ncurses_end - Stop using ncurses, clean up the screen
* ncurses_erase - Erase terminal screen
* ncurses_erasechar - Returns current erase character
* ncurses_filter - Set LINES for iniscr() and newterm() to 1
* ncurses_flash - Flash terminal screen (visual bell)
* ncurses_flushinp - Flush keyboard input buffer
* ncurses_getch - Read a character from keyboard
* ncurses_getmaxyx - Returns the size of a window
* ncurses_getmouse - Reads mouse event
* ncurses_getyx - Returns the current cursor position for a window
* ncurses_halfdelay - Put terminal into halfdelay mode
* ncurses_has_colors - Checks if terminal has color capabilities
* ncurses_has_ic - Check for insert- and delete-capabilities
* ncurses_has_il - Check for line insert- and delete-capabilities
* ncurses_has_key - Check for presence of a function key on terminal
keyboard
* ncurses_hide_panel - Remove panel from the stack, making it invisible
* ncurses_hline - Draw a horizontal line at current position using an
attributed character and max. n characters long
* ncurses_inch - Get character and attribute at current position
* ncurses_init_color - Define a terminal color
* ncurses_init_pair - Define a color pair
* ncurses_init - Initialize ncurses
* ncurses_insch - Insert character moving rest of line including
character at current position
* ncurses_insdelln - Insert lines before current line scrolling down
(negative numbers delete and scroll up)
* ncurses_insertln - Insert a line, move rest of screen down
* ncurses_insstr - Insert string at current position, moving rest of
line right
* ncurses_instr - Reads string from terminal screen
* ncurses_isendwin - Ncurses is in endwin mode, normal screen output may
be performed
* ncurses_keyok - Enable or disable a keycode
* ncurses_keypad - Turns keypad on or off
* ncurses_killchar - Returns current line kill character
* ncurses_longname - Returns terminals description
* ncurses_meta - Enables/Disable 8-bit meta key information
* ncurses_mouse_trafo - Transforms coordinates
* ncurses_mouseinterval - Set timeout for mouse button clicks
* ncurses_mousemask - Sets mouse options
* ncurses_move_panel - Moves a panel so that its upper-left corner is at
[startx, starty]
* ncurses_move - Move output position
* ncurses_mvaddch - Move current position and add character
* ncurses_mvaddchnstr - Move position and add attributed string with
specified length
* ncurses_mvaddchstr - Move position and add attributed string
* ncurses_mvaddnstr - Move position and add string with specified length
* ncurses_mvaddstr - Move position and add string
* ncurses_mvcur - Move cursor immediately
* ncurses_mvdelch - Move position and delete character, shift rest of
line left
* ncurses_mvgetch - Move position and get character at new position
* ncurses_mvhline - Set new position and draw a horizontal line using an
attributed character and max. n characters long
* ncurses_mvinch - Move position and get attributed character at new
position
* ncurses_mvvline - Set new position and draw a vertical line using an
attributed character and max. n characters long
* ncurses_mvwaddstr - Add string at new position in window
* ncurses_napms - Sleep
* ncurses_new_panel - Create a new panel and associate it with window
* ncurses_newpad - Creates a new pad (window)
* ncurses_newwin - Create a new window
* ncurses_nl - Translate newline and carriage return / line feed
* ncurses_nocbreak - Switch terminal to cooked mode
* ncurses_noecho - Switch off keyboard input echo
* ncurses_nonl - Do not translate newline and carriage return / line
feed
* ncurses_noqiflush - Do not flush on signal characters
* ncurses_noraw - Switch terminal out of raw mode
* ncurses_pair_content - Retrieves foreground and background colors of a
color pair
* ncurses_panel_above - Returns the panel above panel
* ncurses_panel_below - Returns the panel below panel
* ncurses_panel_window - Returns the window associated with panel
* ncurses_pnoutrefresh - Copies a region from a pad into the virtual
screen
* ncurses_prefresh - Copies a region from a pad into the virtual screen
* ncurses_putp - Apply padding information to the string and output it
* ncurses_qiflush - Flush on signal characters
* ncurses_raw - Switch terminal into raw mode
* ncurses_refresh - Refresh screen
* ncurses_replace_panel - Replaces the window associated with panel
* ncurses_reset_prog_mode - Resets the prog mode saved by def_prog_mode
* ncurses_reset_shell_mode - Resets the shell mode saved by
def_shell_mode
* ncurses_resetty - Restores saved terminal state
* ncurses_savetty - Saves terminal state
* ncurses_scr_dump - Dump screen content to file
* ncurses_scr_init - Initialize screen from file dump
* ncurses_scr_restore - Restore screen from file dump
* ncurses_scr_set - Inherit screen from file dump
* ncurses_scrl - Scroll window content up or down without changing
current position
* ncurses_show_panel - Places an invisible panel on top of the stack,
making it visible
* ncurses_slk_attr - Returns current soft label key attribute
* ncurses_slk_attroff - Turn off the given attributes for soft
function-key labels
* ncurses_slk_attron - Turn on the given attributes for soft
function-key labels
* ncurses_slk_attrset - Set given attributes for soft function-key
labels
* ncurses_slk_clear - Clears soft labels from screen
* ncurses_slk_color - Sets color for soft label keys
* ncurses_slk_init - Initializes soft label key functions
* ncurses_slk_noutrefresh - Copies soft label keys to virtual screen
* ncurses_slk_refresh - Copies soft label keys to screen
* ncurses_slk_restore - Restores soft label keys
* ncurses_slk_set - Sets function key labels
* ncurses_slk_touch - Forces output when ncurses_slk_noutrefresh is
performed
* ncurses_standend - Stop using 'standout' attribute
* ncurses_standout - Start using 'standout' attribute
* ncurses_start_color - Initializes color functionality
* ncurses_termattrs - Returns a logical OR of all attribute flags
supported by terminal
* ncurses_termname - Returns terminals (short)-name
* ncurses_timeout - Set timeout for special key sequences
* ncurses_top_panel - Moves a visible panel to the top of the stack
* ncurses_typeahead - Specify different filedescriptor for typeahead
checking
* ncurses_ungetch - Put a character back into the input stream
* ncurses_ungetmouse - Pushes mouse event to queue
* ncurses_update_panels - Refreshes the virtual screen to reflect the
relations between panels in the stack
* ncurses_use_default_colors - Assign terminal default colors to color
id -1
* ncurses_use_env - Control use of environment information about
terminal size
* ncurses_use_extended_names - Control use of extended names in terminfo
descriptions
* ncurses_vidattr - Display the string on the terminal in the video
attribute mode
* ncurses_vline - Draw a vertical line at current position using an
attributed character and max. n characters long
* ncurses_waddch - Adds character at current position in a window and
advance cursor
* ncurses_waddstr - Outputs text at current postion in window
* ncurses_wattroff - Turns off attributes for a window
* ncurses_wattron - Turns on attributes for a window
* ncurses_wattrset - Set the attributes for a window
* ncurses_wborder - Draws a border around the window using attributed
characters
* ncurses_wclear - Clears window
* ncurses_wcolor_set - Sets windows color pairings
* ncurses_werase - Erase window contents
* ncurses_wgetch - Reads a character from keyboard (window)
* ncurses_whline - Draws a horizontal line in a window at current
position using an attributed character and max. n characters long
* ncurses_wmouse_trafo - Transforms window/stdscr coordinates
* ncurses_wmove - Moves windows output position
* ncurses_wnoutrefresh - Copies window to virtual screen
* ncurses_wrefresh - Refresh window on terminal screen
* ncurses_wstandend - End standout mode for a window
* ncurses_wstandout - Enter standout mode for a window
* ncurses_wvline - Draws a vertical line in a window at current position
using an attributed character and max. n characters long
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Error codes
* Colors
* Keys
* Mouse
* Ncurses Functions
* ncurses_addch - Add character at current position and advance
cursor
* ncurses_addchnstr - Add attributed string with specified length
at current position
* ncurses_addchstr - Add attributed string at current position
* ncurses_addnstr - Add string with specified length at current
position
* ncurses_addstr - Output text at current position
* ncurses_assume_default_colors - Define default colors for color 0
* ncurses_attroff - Turn off the given attributes
* ncurses_attron - Turn on the given attributes
* ncurses_attrset - Set given attributes
* ncurses_baudrate - Returns baudrate of terminal
* ncurses_beep - Let the terminal beep
* ncurses_bkgd - Set background property for terminal screen
* ncurses_bkgdset - Control screen background
* ncurses_border - Draw a border around the screen using attributed
characters
* ncurses_bottom_panel - Moves a visible panel to the bottom of the
stack
* ncurses_can_change_color - Checks if terminal color definitions
can be changed
* ncurses_cbreak - Switch of input buffering
* ncurses_clear - Clear screen
* ncurses_clrtobot - Clear screen from current position to bottom
* ncurses_clrtoeol - Clear screen from current position to end of
line
* ncurses_color_content - Retrieves RGB components of a color
* ncurses_color_set - Set active foreground and background colors
* ncurses_curs_set - Set cursor state
* ncurses_def_prog_mode - Saves terminals (program) mode
* ncurses_def_shell_mode - Saves terminals (shell) mode
* ncurses_define_key - Define a keycode
* ncurses_del_panel - Remove panel from the stack and delete it
(but not the associated window)
* ncurses_delay_output - Delay output on terminal using padding
characters
* ncurses_delch - Delete character at current position, move rest
of line left
* ncurses_deleteln - Delete line at current position, move rest of
screen up
* ncurses_delwin - Delete a ncurses window
* ncurses_doupdate - Write all prepared refreshes to terminal
* ncurses_echo - Activate keyboard input echo
* ncurses_echochar - Single character output including refresh
* ncurses_end - Stop using ncurses, clean up the screen
* ncurses_erase - Erase terminal screen
* ncurses_erasechar - Returns current erase character
* ncurses_filter - Set LINES for iniscr() and newterm() to 1
* ncurses_flash - Flash terminal screen (visual bell)
* ncurses_flushinp - Flush keyboard input buffer
* ncurses_getch - Read a character from keyboard
* ncurses_getmaxyx - Returns the size of a window
* ncurses_getmouse - Reads mouse event
* ncurses_getyx - Returns the current cursor position for a window
* ncurses_halfdelay - Put terminal into halfdelay mode
* ncurses_has_colors - Checks if terminal has color capabilities
* ncurses_has_ic - Check for insert- and delete-capabilities
* ncurses_has_il - Check for line insert- and delete-capabilities
* ncurses_has_key - Check for presence of a function key on
terminal keyboard
* ncurses_hide_panel - Remove panel from the stack, making it
invisible
* ncurses_hline - Draw a horizontal line at current position using
an attributed character and max. n characters long
* ncurses_inch - Get character and attribute at current position
* ncurses_init_color - Define a terminal color
* ncurses_init_pair - Define a color pair
* ncurses_init - Initialize ncurses
* ncurses_insch - Insert character moving rest of line including
character at current position
* ncurses_insdelln - Insert lines before current line scrolling
down (negative numbers delete and scroll up)
* ncurses_insertln - Insert a line, move rest of screen down
* ncurses_insstr - Insert string at current position, moving rest
of line right
* ncurses_instr - Reads string from terminal screen
* ncurses_isendwin - Ncurses is in endwin mode, normal screen
output may be performed
* ncurses_keyok - Enable or disable a keycode
* ncurses_keypad - Turns keypad on or off
* ncurses_killchar - Returns current line kill character
* ncurses_longname - Returns terminals description
* ncurses_meta - Enables/Disable 8-bit meta key information
* ncurses_mouse_trafo - Transforms coordinates
* ncurses_mouseinterval - Set timeout for mouse button clicks
* ncurses_mousemask - Sets mouse options
* ncurses_move_panel - Moves a panel so that its upper-left corner
is at [startx, starty]
* ncurses_move - Move output position
* ncurses_mvaddch - Move current position and add character
* ncurses_mvaddchnstr - Move position and add attributed string
with specified length
* ncurses_mvaddchstr - Move position and add attributed string
* ncurses_mvaddnstr - Move position and add string with specified
length
* ncurses_mvaddstr - Move position and add string
* ncurses_mvcur - Move cursor immediately
* ncurses_mvdelch - Move position and delete character, shift rest
of line left
* ncurses_mvgetch - Move position and get character at new position
* ncurses_mvhline - Set new position and draw a horizontal line
using an attributed character and max. n characters long
* ncurses_mvinch - Move position and get attributed character at
new position
* ncurses_mvvline - Set new position and draw a vertical line using
an attributed character and max. n characters long
* ncurses_mvwaddstr - Add string at new position in window
* ncurses_napms - Sleep
* ncurses_new_panel - Create a new panel and associate it with
window
* ncurses_newpad - Creates a new pad (window)
* ncurses_newwin - Create a new window
* ncurses_nl - Translate newline and carriage return / line feed
* ncurses_nocbreak - Switch terminal to cooked mode
* ncurses_noecho - Switch off keyboard input echo
* ncurses_nonl - Do not translate newline and carriage return /
line feed
* ncurses_noqiflush - Do not flush on signal characters
* ncurses_noraw - Switch terminal out of raw mode
* ncurses_pair_content - Retrieves foreground and background colors
of a color pair
* ncurses_panel_above - Returns the panel above panel
* ncurses_panel_below - Returns the panel below panel
* ncurses_panel_window - Returns the window associated with panel
* ncurses_pnoutrefresh - Copies a region from a pad into the
virtual screen
* ncurses_prefresh - Copies a region from a pad into the virtual
screen
* ncurses_putp - Apply padding information to the string and output
it
* ncurses_qiflush - Flush on signal characters
* ncurses_raw - Switch terminal into raw mode
* ncurses_refresh - Refresh screen
* ncurses_replace_panel - Replaces the window associated with panel
* ncurses_reset_prog_mode - Resets the prog mode saved by
def_prog_mode
* ncurses_reset_shell_mode - Resets the shell mode saved by
def_shell_mode
* ncurses_resetty - Restores saved terminal state
* ncurses_savetty - Saves terminal state
* ncurses_scr_dump - Dump screen content to file
* ncurses_scr_init - Initialize screen from file dump
* ncurses_scr_restore - Restore screen from file dump
* ncurses_scr_set - Inherit screen from file dump
* ncurses_scrl - Scroll window content up or down without changing
current position
* ncurses_show_panel - Places an invisible panel on top of the
stack, making it visible
* ncurses_slk_attr - Returns current soft label key attribute
* ncurses_slk_attroff - Turn off the given attributes for soft
function-key labels
* ncurses_slk_attron - Turn on the given attributes for soft
function-key labels
* ncurses_slk_attrset - Set given attributes for soft function-key
labels
* ncurses_slk_clear - Clears soft labels from screen
* ncurses_slk_color - Sets color for soft label keys
* ncurses_slk_init - Initializes soft label key functions
* ncurses_slk_noutrefresh - Copies soft label keys to virtual
screen
* ncurses_slk_refresh - Copies soft label keys to screen
* ncurses_slk_restore - Restores soft label keys
* ncurses_slk_set - Sets function key labels
* ncurses_slk_touch - Forces output when ncurses_slk_noutrefresh is
performed
* ncurses_standend - Stop using 'standout' attribute
* ncurses_standout - Start using 'standout' attribute
* ncurses_start_color - Initializes color functionality
* ncurses_termattrs - Returns a logical OR of all attribute flags
supported by terminal
* ncurses_termname - Returns terminals (short)-name
* ncurses_timeout - Set timeout for special key sequences
* ncurses_top_panel - Moves a visible panel to the top of the stack
* ncurses_typeahead - Specify different filedescriptor for
typeahead checking
* ncurses_ungetch - Put a character back into the input stream
* ncurses_ungetmouse - Pushes mouse event to queue
* ncurses_update_panels - Refreshes the virtual screen to reflect
the relations between panels in the stack
* ncurses_use_default_colors - Assign terminal default colors to
color id -1
* ncurses_use_env - Control use of environment information about
terminal size
* ncurses_use_extended_names - Control use of extended names in
terminfo descriptions
* ncurses_vidattr - Display the string on the terminal in the video
attribute mode
* ncurses_vline - Draw a vertical line at current position using an
attributed character and max. n characters long
* ncurses_waddch - Adds character at current position in a window
and advance cursor
* ncurses_waddstr - Outputs text at current postion in window
* ncurses_wattroff - Turns off attributes for a window
* ncurses_wattron - Turns on attributes for a window
* ncurses_wattrset - Set the attributes for a window
* ncurses_wborder - Draws a border around the window using
attributed characters
* ncurses_wclear - Clears window
* ncurses_wcolor_set - Sets windows color pairings
* ncurses_werase - Erase window contents
* ncurses_wgetch - Reads a character from keyboard (window)
* ncurses_whline - Draws a horizontal line in a window at current
position using an attributed character and max. n characters long
* ncurses_wmouse_trafo - Transforms window/stdscr coordinates
* ncurses_wmove - Moves windows output position
* ncurses_wnoutrefresh - Copies window to virtual screen
* ncurses_wrefresh - Refresh window on terminal screen
* ncurses_wstandend - End standout mode for a window
* ncurses_wstandout - Enter standout mode for a window
* ncurses_wvline - Draws a vertical line in a window at current
position using an attributed character and max. n characters long
----------------------------------------------------------------------
----------------------------------------------------------------------
GNU Readline
----------------------------------------------------------------------
Introduction
The readline functions implement an interface to the GNU Readline library.
These are functions that provide editable command lines. An example being
the way Bash allows you to use the arrow keys to insert characters or
scroll through command history. Because of the interactive nature of this
library, it will be of little use for writing Web applications, but may be
useful when writing scripts used from a command line.
Note: This extension is not available on Windows platforms.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
To use the readline functions, you need to install libreadline. You can
find libreadline on the home page of the GNU Readline project, at
>> http://cnswww.cns.cwru.edu/~chet/readline/rltop.html. It's maintained
by Chet Ramey, who's also the author of Bash.
You can also use these functions with the libedit library, a non-GPL
replacement for the readline library. The libedit library is BSD licensed
and available for download from >> http://www.thrysoee.dk/editline/.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
To use these functions you must compile the CGI or CLI version of PHP with
readline support. You need to configure PHP --with-readline[=DIR] . If you
want to use the libedit readline replacement, configure PHP
--with-libedit[=DIR] .
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Readline Configure Options
Name Default Changeable Changelog
cli.pager "" PHP_INI_ALL Available since PHP 5.4.0.
cli.prompt "\\b \\> " PHP_INI_ALL Available since PHP 5.4.0.
Here's a short explanation of the configuration directives.
cli.pager string
External tool to display output from command line.
cli.prompt string
Command line prompt.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
This extension has no constants defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
Readline Functions
----------------------------------------------------------------------
readline_add_history
(PHP 4, PHP 5)
readline_add_history - Adds a line to the history
Description
bool readline_add_history ( string $line )
This function adds a line to the command line history.
Parameters
line
The line to be added in the history.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
readline_callback_handler_install
(PHP 5 >= 5.1.0)
readline_callback_handler_install - Initializes the readline callback
interface and terminal, prints the prompt and returns immediately
Description
bool readline_callback_handler_install ( string $prompt , callback
$callback )
Sets up a readline callback interface then prints prompt and immediately
returns. Calling this function twice without removing the previous
callback interface will automatically and conveniently overwrite the old
interface.
The callback feature is useful when combined with stream_select() as it
allows interleaving of IO and user input, unlike readline().
Parameters
prompt
The prompt message.
callback
The callback function takes one parameter; the user input
returned.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Readline Callback Interface Example
10) {
$prompting = false;
readline_callback_handler_remove();
} else {
readline_callback_handler_install("[$c] Enter something: ", 'rl_callback');
}
}
$c = 1;
$prompting = true;
readline_callback_handler_install("[$c] Enter something: ", 'rl_callback');
while ($prompting) {
$w = NULL;
$e = NULL;
$n = stream_select($r = array(STDIN), $w, $e, null);
if ($n && in_array(STDIN, $r)) {
// read a character, will call the callback when a newline is entered
readline_callback_read_char();
}
}
echo "Prompting disabled. All done.\n";
?>
See Also
* readline_callback_handler_remove() - Removes a previously installed
callback handler and restores terminal settings
* readline_callback_read_char() - Reads a character and informs the
readline callback interface when a line is received
* stream_select() - Runs the equivalent of the select() system call on
the given arrays of streams with a timeout specified by tv_sec and
tv_usec
----------------------------------------------------------------------
----------------------------------------------------------------------
readline_callback_handler_remove
(PHP 5 >= 5.1.0)
readline_callback_handler_remove - Removes a previously installed callback
handler and restores terminal settings
Description
bool readline_callback_handler_remove ( void )
Removes a previously installed callback handler and restores terminal
settings.
Return Values
Returns TRUE if a previously installed callback handler was removed, or
FALSE if one could not be found.
Examples
See readline_callback_handler_install() for an example of how to use the
readline callback interface.
See Also
* readline_callback_handler_install() - Initializes the readline
callback interface and terminal, prints the prompt and returns
immediately
* readline_callback_read_char() - Reads a character and informs the
readline callback interface when a line is received
----------------------------------------------------------------------
----------------------------------------------------------------------
readline_callback_read_char
(PHP 5 >= 5.1.0)
readline_callback_read_char - Reads a character and informs the readline
callback interface when a line is received
Description
void readline_callback_read_char ( void )
Reads a character of user input. When a line is received, this function
informs the readline callback interface installed using
readline_callback_handler_install() that a line is ready for input.
Return Values
No value is returned.
Examples
See readline_callback_handler_install() for an example of how to use the
readline callback interface.
See Also
* readline_callback_handler_install() - Initializes the readline
callback interface and terminal, prints the prompt and returns
immediately
* readline_callback_handler_remove() - Removes a previously installed
callback handler and restores terminal settings
----------------------------------------------------------------------
----------------------------------------------------------------------
readline_clear_history
(PHP 4, PHP 5)
readline_clear_history - Clears the history
Description
bool readline_clear_history ( void )
This function clears the entire command line history.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
readline_completion_function
(PHP 4, PHP 5)
readline_completion_function - Registers a completion function
Description
bool readline_completion_function ( callback $function )
This function registers a completion function. This is the same kind of
functionality you'd get if you hit your tab key while using Bash.
Parameters
function
You must supply the name of an existing function which accepts a
partial command line and returns an array of possible matches.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
readline_info
(PHP 4, PHP 5)
readline_info - Gets/sets various internal readline variables
Description
mixed readline_info ([ string $varname [, string $newvalue ]] )
Gets or sets various internal readline variables.
Parameters
varname
A variable name.
newvalue
If provided, this will be the new value of the setting.
Return Values
If called with no parameters, this function returns an array of values for
all the setting readline uses. The elements will be indexed by the
following values: done, end, erase_empty_line, library_version,
line_buffer, mark, pending_input, point, prompt, readline_name, and
terminal_name.
If called with one or two parameters, the old value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
readline_list_history
(PHP 4, PHP 5)
readline_list_history - Lists the history
Description
array readline_list_history ( void )
Gets the entire command line history.
Return Values
Returns an array of the entire command line history. The elements are
indexed by integers starting at zero.
----------------------------------------------------------------------
----------------------------------------------------------------------
readline_on_new_line
(PHP 5 >= 5.1.0)
readline_on_new_line - Inform readline that the cursor has moved to a new
line
Description
void readline_on_new_line ( void )
Tells readline that the cursor has moved to a new line.
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
readline_read_history
(PHP 4, PHP 5)
readline_read_history - Reads the history
Description
bool readline_read_history ([ string $filename ] )
This function reads a command history from a file.
Parameters
filename
Path to the filename containing the command history.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
readline_redisplay
(PHP 5 >= 5.1.0)
readline_redisplay - Redraws the display
Description
void readline_redisplay ( void )
Redraws readline to redraw the display.
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
readline_write_history
(PHP 4, PHP 5)
readline_write_history - Writes the history
Description
bool readline_write_history ([ string $filename ] )
This function writes the command history to a file.
Parameters
filename
Path to the saved file.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
readline
(PHP 4, PHP 5)
readline - Reads a line
Description
string readline ([ string $prompt ] )
Reads a single line from the user. You must add this line to the history
yourself using readline_add_history().
Parameters
prompt
You may specify a string with which to prompt the user.
Return Values
Returns a single string from the user. The line returned has the ending
newline removed.
Examples
Example #1 readline() Example
----------------------------------------------------------------------
Table of Contents
* readline_add_history - Adds a line to the history
* readline_callback_handler_install - Initializes the readline callback
interface and terminal, prints the prompt and returns immediately
* readline_callback_handler_remove - Removes a previously installed
callback handler and restores terminal settings
* readline_callback_read_char - Reads a character and informs the
readline callback interface when a line is received
* readline_clear_history - Clears the history
* readline_completion_function - Registers a completion function
* readline_info - Gets/sets various internal readline variables
* readline_list_history - Lists the history
* readline_on_new_line - Inform readline that the cursor has moved to a
new line
* readline_read_history - Reads the history
* readline_redisplay - Redraws the display
* readline_write_history - Writes the history
* readline - Reads a line
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Readline Functions
* readline_add_history - Adds a line to the history
* readline_callback_handler_install - Initializes the readline
callback interface and terminal, prints the prompt and returns
immediately
* readline_callback_handler_remove - Removes a previously installed
callback handler and restores terminal settings
* readline_callback_read_char - Reads a character and informs the
readline callback interface when a line is received
* readline_clear_history - Clears the history
* readline_completion_function - Registers a completion function
* readline_info - Gets/sets various internal readline variables
* readline_list_history - Lists the history
* readline_on_new_line - Inform readline that the cursor has moved
to a new line
* readline_read_history - Reads the history
* readline_redisplay - Redraws the display
* readline_write_history - Writes the history
* readline - Reads a line
----------------------------------------------------------------------
* Newt
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* Newt Functions
* Ncurses - Ncurses Terminal Screen Control
* Introduction
* Installing/Configuring
* Predefined Constants
* Ncurses Functions
* Readline - GNU Readline
* Introduction
* Installing/Configuring
* Predefined Constants
* Readline Functions
----------------------------------------------------------------------
----------------------------------------------------------------------
Compression and Archive Extensions
----------------------------------------------------------------------
Bzip2
----------------------------------------------------------------------
Introduction
The bzip2 functions are used to transparently read and write bzip2 (.bz2)
compressed files.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
This module uses the functions of the >> bzip2 library by Julian Seward.
This module requires bzip2/libbzip2 version >= 1.0.x.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
Bzip2 support in PHP is not enabled by default. You will need to use the
--with-bz2[=DIR] configuration option when compiling PHP to enable bzip2
support.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension defines one resource type: a file pointer identifying the
bz2-file to work on.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
This extension has no constants defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
This example opens a temporary file and writes a test string to it, then
prints out the contents of the file.
Example #1 Small bzip2 Example
----------------------------------------------------------------------
----------------------------------------------------------------------
Bzip2 Functions
----------------------------------------------------------------------
bzclose
(PHP 4 >= 4.0.4, PHP 5)
bzclose - Close a bzip2 file
Description
int bzclose ( resource $bz )
Closes the given bzip2 file pointer.
Parameters
bz
The file pointer. It must be valid and must point to a file
successfully opened by bzopen().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* bzopen() - Opens a bzip2 compressed file
----------------------------------------------------------------------
----------------------------------------------------------------------
bzcompress
(PHP 4 >= 4.0.4, PHP 5)
bzcompress - Compress a string into bzip2 encoded data
Description
mixed bzcompress ( string $source [, int $blocksize = 4 [, int $workfactor
= 0 ]] )
bzcompress() compresses the given string and returns it as bzip2 encoded
data.
Parameters
source
The string to compress.
blocksize
Specifies the blocksize used during compression and should be a
number from 1 to 9 with 9 giving the best compression, but using
more resources to do so.
workfactor
Controls how the compression phase behaves when presented with
worst case, highly repetitive, input data. The value can be
between 0 and 250 with 0 being a special case.
Regardless of the workfactor, the generated output is the same.
Return Values
The compressed string or number of error in case of error.
Examples
Example #1 Compressing data
See Also
* bzdecompress() - Decompresses bzip2 encoded data
----------------------------------------------------------------------
----------------------------------------------------------------------
bzdecompress
(PHP 4 >= 4.0.4, PHP 5)
bzdecompress - Decompresses bzip2 encoded data
Description
mixed bzdecompress ( string $source [, int $small = 0 ] )
bzdecompress() decompresses the given string containing bzip2 encoded
data.
Parameters
source
The string to decompress.
small
If TRUE, an alternative decompression algorithm will be used which
uses less memory (the maximum memory requirement drops to around
2300K) but works at roughly half the speed.
See the >> bzip2 documentation for more information about this
feature.
Return Values
The decompressed string or number of error in case of error.
Examples
Example #1 Decompressing a String
\n";
$str = bzdecompress($bzstr);
echo "Decompressed String: ";
echo $str;
echo "\n \n";
?>
See Also
* bzcompress() - Compress a string into bzip2 encoded data
----------------------------------------------------------------------
----------------------------------------------------------------------
bzerrno
(PHP 4 >= 4.0.4, PHP 5)
bzerrno - Returns a bzip2 error number
Description
int bzerrno ( resource $bz )
Returns the error number of any bzip2 error returned by the given file
pointer.
Parameters
bz
The file pointer. It must be valid and must point to a file
successfully opened by bzopen().
Return Values
Returns the error number as an integer.
See Also
* bzerror() - Returns the bzip2 error number and error string in an
array
* bzerrstr() - Returns a bzip2 error string
----------------------------------------------------------------------
----------------------------------------------------------------------
bzerror
(PHP 4 >= 4.0.4, PHP 5)
bzerror - Returns the bzip2 error number and error string in an array
Description
array bzerror ( resource $bz )
Returns the error number and error string of any bzip2 error returned by
the given file pointer.
Parameters
bz
The file pointer. It must be valid and must point to a file
successfully opened by bzopen().
Return Values
Returns an associative array, with the error code in the errno entry, and
the error message in the errstr entry.
Examples
Example #1 bzerror() example
See Also
* bzerrno() - Returns a bzip2 error number
* bzerrstr() - Returns a bzip2 error string
----------------------------------------------------------------------
----------------------------------------------------------------------
bzerrstr
(PHP 4 >= 4.0.4, PHP 5)
bzerrstr - Returns a bzip2 error string
Description
string bzerrstr ( resource $bz )
Gets the error string of any bzip2 error returned by the given file
pointer.
Parameters
bz
The file pointer. It must be valid and must point to a file
successfully opened by bzopen().
Return Values
Returns a string containing the error message.
See Also
* bzerrno() - Returns a bzip2 error number
* bzerror() - Returns the bzip2 error number and error string in an
array
----------------------------------------------------------------------
----------------------------------------------------------------------
bzflush
(PHP 4 >= 4.0.4, PHP 5)
bzflush - Force a write of all buffered data
Description
int bzflush ( resource $bz )
Forces a write of all buffered bzip2 data for the file pointer bz.
Parameters
bz
The file pointer. It must be valid and must point to a file
successfully opened by bzopen().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* bzread() - Binary safe bzip2 file read
* bzwrite() - Binary safe bzip2 file write
----------------------------------------------------------------------
----------------------------------------------------------------------
bzopen
(PHP 4 >= 4.0.4, PHP 5)
bzopen - Opens a bzip2 compressed file
Description
resource bzopen ( string $filename , string $mode )
bzopen() opens a bzip2 (.bz2) file for reading or writing.
Parameters
filename
The name of the file to open.
mode
Similar to the fopen() function, only 'r' (read) and 'w' (write)
are supported. Everything else will cause bzopen to return FALSE.
Return Values
If the open fails, bzopen() returns FALSE, otherwise it returns a pointer
to the newly opened file.
Examples
Example #1 bzopen() example
See Also
* bzclose() - Close a bzip2 file
----------------------------------------------------------------------
----------------------------------------------------------------------
bzread
(PHP 4 >= 4.0.4, PHP 5)
bzread - Binary safe bzip2 file read
Description
string bzread ( resource $bz [, int $length = 1024 ] )
bzread() reads from the given bzip2 file pointer.
Reading stops when length (uncompressed) bytes have been read or EOF is
reached, whichever comes first.
Parameters
bz
The file pointer. It must be valid and must point to a file
successfully opened by bzopen().
length
If not specified, bzread() will read 1024 (uncompressed) bytes at
a time. A maximum of 8192 uncompressed bytes will be read at a
time.
Return Values
Returns the uncompressed data, or FALSE on error.
Examples
Example #1 bzread() example
\n";
echo $decompressed_file;
?>
See Also
* bzwrite() - Binary safe bzip2 file write
* feof() - Tests for end-of-file on a file pointer
* bzopen() - Opens a bzip2 compressed file
----------------------------------------------------------------------
----------------------------------------------------------------------
bzwrite
(PHP 4 >= 4.0.4, PHP 5)
bzwrite - Binary safe bzip2 file write
Description
int bzwrite ( resource $bz , string $data [, int $length ] )
bzwrite() writes a string into the given bzip2 file stream.
Parameters
bz
The file pointer. It must be valid and must point to a file
successfully opened by bzopen().
data
The written data.
length
If supplied, writing will stop after length (uncompressed) bytes
have been written or the end of data is reached, whichever comes
first.
Return Values
Returns the number of bytes written, or FALSE on error.
Examples
Example #1 bzwrite() example
See Also
* bzread() - Binary safe bzip2 file read
* bzopen() - Opens a bzip2 compressed file
----------------------------------------------------------------------
Table of Contents
* bzclose - Close a bzip2 file
* bzcompress - Compress a string into bzip2 encoded data
* bzdecompress - Decompresses bzip2 encoded data
* bzerrno - Returns a bzip2 error number
* bzerror - Returns the bzip2 error number and error string in an array
* bzerrstr - Returns a bzip2 error string
* bzflush - Force a write of all buffered data
* bzopen - Opens a bzip2 compressed file
* bzread - Binary safe bzip2 file read
* bzwrite - Binary safe bzip2 file write
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* Bzip2 Functions
* bzclose - Close a bzip2 file
* bzcompress - Compress a string into bzip2 encoded data
* bzdecompress - Decompresses bzip2 encoded data
* bzerrno - Returns a bzip2 error number
* bzerror - Returns the bzip2 error number and error string in an
array
* bzerrstr - Returns a bzip2 error string
* bzflush - Force a write of all buffered data
* bzopen - Opens a bzip2 compressed file
* bzread - Binary safe bzip2 file read
* bzwrite - Binary safe bzip2 file write
----------------------------------------------------------------------
----------------------------------------------------------------------
LZF
----------------------------------------------------------------------
Introduction
LZF is a very fast compression algorithm, ideal for saving space with only
slight speed cost. It can be optimized for speed or space at the time of
compilation. This extension is using >> liblzf library by Marc Lehmann for
its operations.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
This >> PECL extension is not bundled with PHP. Information for installing
this PECL extension may be found in the manual chapter titled Installation
of PECL extensions. Additional information such as new releases,
downloads, source files, maintainer information, and a CHANGELOG, can be
located here: >> http://pecl.php.net/package/lzf.
In order to use these functions you must compile PHP with lzf support by
using the --with-lzf[=DIR] configure option. You may also pass
--enable-lzf-better-compression to optimize LZF for space rather than
speed.
Windows users will enable php_lzf.dll inside of php.ini in order to use
these functions. A DLL for this PECL extension is currently unavailable.
See also the building on Windows section.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
This extension has no constants defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
LZF Functions
----------------------------------------------------------------------
lzf_compress
(PECL lzf >= 0.1.0)
lzf_compress - LZF compression
Description
string lzf_compress ( string $data )
lzf_compress() compresses the given data string using LZF encoding.
Parameters
data
The string to compress.
Return Values
Returns the compressed data or FALSE if an error occurred.
See Also
* lzf_decompress() - LZF decompression
----------------------------------------------------------------------
----------------------------------------------------------------------
lzf_decompress
(PECL lzf >= 0.1.0)
lzf_decompress - LZF decompression
Description
string lzf_decompress ( string $data )
lzf_compress() decompresses the given data string containing lzf encoded
data.
Parameters
data
The compressed string.
Return Values
Returns the decompressed data or FALSE if an error occurred.
See Also
* lzf_compress() - LZF compression
----------------------------------------------------------------------
----------------------------------------------------------------------
lzf_optimized_for
(PECL lzf >= 1.0.0)
lzf_optimized_for - Determines what LZF extension was optimized for
Description
int lzf_optimized_for ( void )
Determines what was LZF extension optimized for during compilation.
Return Values
Returns 1 if LZF was optimized for speed, 0 for compression.
----------------------------------------------------------------------
Table of Contents
* lzf_compress - LZF compression
* lzf_decompress - LZF decompression
* lzf_optimized_for - Determines what LZF extension was optimized for
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* LZF Functions
* lzf_compress - LZF compression
* lzf_decompress - LZF decompression
* lzf_optimized_for - Determines what LZF extension was optimized
for
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar
----------------------------------------------------------------------
Introduction
The phar extension provides a way to put entire PHP applications into a
single file called a "phar" (PHP Archive) for easy distribution and
installation. In addition to providing this service, the phar extension
also provides a file-format abstraction method for creating and
manipulating tar and zip files through the PharData class, much as PDO
provides a unified interface for accessing different databases. Unlike
PDO, which cannot convert between different databases, Phar also can
convert between tar, zip and phar file formats with a single line of code.
see Phar::convertToExecutable() for one example.
What is phar? Phar archives are best characterized as a convenient way to
group several files into a single file. As such, a phar archive provides a
way to distribute a complete PHP application in a single file and run it
from that file without the need to extract it to disk. Additionally, phar
archives can be executed by PHP as easily as any other file, both on the
commandline and from a web server. Phar is kind of like a thumb drive for
PHP applications.
Phar implements this functionality through a Stream Wrapper. Normally, to
use an external file within a PHP script, you would use include()
Example #1 Using an external file
PHP can be thought of as actually translating /path/to/external/file.php
into a stream wrapper as file:///path/to/external/file.php, and under the
hood it does in fact use the plain file stream wrapper stream functions to
access all local files.
To use a file named file.php contained with a phar archive
/path/to/myphar.phar, the syntax is very similar to the file:// syntax
above.
Example #2 Using a file within a phar archive
In fact, one can treat a phar archive exactly as if it were an external
disk, using any of fopen()-related functions, opendir() and
mkdir()-related functions to read, change, or create new files and
directories within the phar archive. This allows complete PHP applications
to be distributed in a single file and run directly from that file.
The most common usage for a phar archive is to distribute a complete
application in a single file. For instance, the PEAR Installer that is
bundled with PHP versions is distributed as a phar archive. To use a phar
archive distributed in this way, the archive can be executed on the
command-line or via a web server.
Phar archives can be distributed as tar archives, zip archives, or as the
custom phar file format designed specifically for the phar extension. Each
file format has advantages and disadvantages. The tar and zip file formats
can be read or extracted by any third-party tool that can read the format,
but require the phar extension in order to run with PHP. The phar file
format is customized and unique to the phar extension, and can only be
created by the phar extension or the PEAR package >> PHP_Archive, but has
the advantage that applications created in this format will run even if
the phar extension is not enabled.
In other words, even with the phar extension disabled, one can execute or
include a phar-based archive. Accessing individual files within a phar
archive is only possible with the phar extension unless the phar archive
was created by PHP_Archive.
The phar extension is also capable of converting a phar archive from tar
to zip or to phar file format in a single command:
Example #3 Converting a phar archive from phar to tar file format
convertToExecutable(Phar::TAR, Phar::GZ); // makes myphar.phar.tar.gz
?>
Phar can compress individual files or an entire archive using gzip
compression or bzip2 compression, and can verify archive integrity
automatically through the use of md5(), sha1(), sha256(), or sha512()
signatures.
Lastly, the Phar extension is security-conscious, and disables write
access to executable phar archives by default, and requires system-level
disabling of the phar.readonly php.ini setting in order to create or
modify phar archives. Normal tar and zip archives without an executable
stub can always be created or modified using the PharData class.
If you are creating applications for distribution, you will want to read
How to create Phar Archives. If you want more information on the
differences between the three file formats that phar supports, you should
read Phar, Tar and Zip.
If you are using phar applications, there are helpful tips in How to use
Phar Archives
The word phar is a contraction of PHP and Archive and is based loosely on
the jar (Java Archive) familiar to Java developers.
The implementation for Phar archives is based on the PEAR package
>> PHP_Archive, and the implementation details are similar, although the
Phar extension is much more powerful. In addition, the Phar extension
allows most PHP applications to be run unmodified while PHP_Archive-based
phar archives often require extensive modification in order to work.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
Phar requires PHP 5.2.0 or newer. Additional features require the SPL
extension in order to take advantage of iteration and array access to a
Phar's file contents. The phar stream does not require any additional
extensions to function.
You may optionally wish to enable the zlib and bzip2 extensions to take
advantage of compressed phar support. In addition, to take advantage of
OpenSSL signing, the OpenSSL extension must be enabled.
Note that a bug in the zlib.deflate stream filter fixed in PHP version
5.2.6 and newer may cause truncation of gzip and bzip2-compressed phar
archives.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
The Phar extension is built into PHP as of PHP version 5.3.0. Phar may be
installed via the PECL extension with previous PHP versions, and the
>> Phar PECL page contains further information and history.
Windows users must include the php_phar.dll file within php.ini to use
this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Filesystem and Streams Configuration Options
Name Default Changeable Changelog
phar.readonly "1" PHP_INI_ALL
phar.require_hash "1" PHP_INI_ALL
phar.extract_list "" PHP_INI_ALL Available from phar 1.1.0 to
1.2.3, removed in 2.0.0.
phar.cache_list "" PHP_INI_SYSTEM Available from phar 2.0.0.
Here's a short explanation of the configuration directives.
phar.readonly boolean
This option disables creation or modification of Phar archives
using the phar stream or Phar object's write support. This setting
should always be enabled on production machines, as the phar
extension's convenient write support could allow straightforward
creation of a php-based virus when coupled with other common
security vulnerabilities.
Note:
This setting can only be unset in php.ini due to security
reasons. If phar.readonly is disabled in php.ini, the user may
enable phar.readonly in a script or disable it later. If
phar.readonly is enabled in php.ini, a script may harmlessly
"re-enable" the INI variable, but may not disable it.
phar.require_hash boolean
This option will force all opened Phar archives to contain some
kind of signature (currently MD5, SHA1, SHA256 and SHA512 are
supported), and will refuse to process any Phar archive that does
not contain a signature.
Note:
This setting can only be unset in php.ini due to security
reasons. If phar.require_hash is disabled in php.ini, the user
may enable phar.require_hash in a script or disable it later. If
phar.require_hash is enabled in php.ini, a script may harmlessly
"re-enable" the INI variable, but may not disable it.
This setting does not affect reading plain tar files with the
PharData class.
phar.extract_list string
This INI setting has been removed as of phar 2.0.0
Allows mappings from a full path to a phar archive or its alias to
the location of its extracted files. The format of the parameter
is name=archive,name2=archive2. This allows extraction of phar
files to disk, and allows phar to act as a kind of mapper to
extracted disk files. This is often done for performance reasons,
or to assist with debugging a phar.
Example #1 phar.extract_list usage example
in php.ini:
phar.extract_list = archive=/full/path/to/archive/,arch2=/full/path/to/arch2
phar.cache_list string
This INI setting was added in phar 2.0.0
Allows mapping phar archives to be pre-parsed at web server
startup, providing a performance improvement that brings running
files out of a phar archive very close to the speed of running
those files from a traditional disk-based installation.
Example #2 phar.cache_list usage example
in php.ini (windows):
phar.cache_list =C:\path\to\phar1.phar;C:\path\to\phar2.phar
in php.ini (unix):
phar.cache_list =/path/to/phar1.phar:/path/to/phar2.phar
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
The Phar extension provides the phar stream, which allows accessing files
contained within a phar transparently. See also the description of the
Phar file format.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
Phar compression constants
Constant Value Description
Phar::NONE (integer) 0x00000000 no compression
bitmask that can be used with file
Phar::COMPRESSED (integer) 0x0000F000 flags to determine if any
compression is present
Phar::GZ (integer) 0x00001000 zlib (gzip) compression
Phar::BZ2 (integer) 0x00002000 bzip2 compression
Phar file format constants
Constant Value Description
Phar::SAME (integer) 0 retain the same file format
Phar::PHAR (integer) 1 phar file format
Phar::TAR (integer) 2 tar file format
Phar::ZIP (integer) 3 zip file format
Phar signature constants
Constant Value Description
Phar::MD5 (integer) 0x0001 signature with md5 hash algorithm
Phar::SHA1 (integer) 0x0002 signature with sha1 hash algorithm
Phar::SHA256 (integer) 0x0003 signature with sha256 hash algorithm
(requires hash extension)
Phar::SHA512 (integer) 0x0004 signature with sha512 hash algorithm
(requires hash extension)
signature with OpenSSL public/private key
Phar::OPENSSL (integer) 0x0010 pair. This is a true, asymmetric key
signature.
Phar webPhar mime override constants
Constant Value Description
used to instruct the mimeoverrides parameter of
Phar::PHP (integer) 1 Phar::webPhar() that the extension should be
parsed as a PHP file
used to instruct the mimeoverrides parameter of
Phar::PHPS (integer) 2 Phar::webPhar() that the extension should be
parsed as a PHP source file through
highlight_file()
----------------------------------------------------------------------
----------------------------------------------------------------------
Using Phar Archives
Table of Contents
* Using Phar Archives: Introduction
* Using Phar Archives: the phar stream wrapper
* Using Phar Archives: the Phar and PharData class
----------------------------------------------------------------------
Using Phar Archives: Introduction
Phar archives are similar in concept to Java JAR archives, but are
tailored to the needs and to the flexibility of PHP applications. A Phar
archive is used to distribute a complete PHP application or library in a
single file. Unlike Java's implementation of JAR archives, no external
tool is required to process or run a PHP Phar archive. A Phar archive
application is used exactly like any other PHP application:
php coolapplication.phar
Using a Phar archive library is identical to using any other PHP library:
The phar stream wrapper provides the core of the phar extension, and is
explained in detail here. The phar stream wrapper allows accessing the
files within a phar archive using PHP's standard file functions fopen(),
opendir(), and others that work on regular files. The phar stream wrapper
supports all read/write operations on both files and directories.
The Phar class implements advanced functionality for accessing files and
for creating phar archives. The Phar class is explained in detail here.
getFileName() . "\n";
echo file_get_contents($file->getPathName()) . "\n"; // display contents;
}
if (isset($p['internal/file.php'])) {
var_dump($p['internal/file.php']->getMetaData());
}
// create a new phar - phar.readonly must be 0 in php.ini
// phar.readonly is enabled by default for security reasons.
// On production servers, Phars need never be created,
// only executed.
if (Phar::canWrite()) {
$p = new Phar('newphar.tar.phar', 0, 'newphar.tar.phar');
// make this a tar-based phar archive, compressed with gzip compression (.tar.gz)
$p = $p->convertToExecutable(Phar::TAR, Phar::GZ);
// create transaction - nothing is written to newphar.phar
// until stopBuffering() is called, although temporary storage is needed
$p->startBuffering();
// add all files in /path/to/project, saving in the phar with the prefix "project"
$p->buildFromIterator(new RecursiveIteratorIterator(new DirectoryIterator('/path/to/project')), '/path/to/');
// add a new file via the array access API
$p['file1.txt'] = 'Information';
$fp = fopen('hugefile.dat', 'rb');
// copy all data from the stream
$p['data/hugefile.dat'] = $fp;
if (Phar::canCompress(Phar::GZ)) {
$p['data/hugefile.dat']->compress(Phar::GZ);
}
$p['images/wow.jpg'] = file_get_contents('images/wow.jpg');
// any value can be saved as file-specific meta-data
$p['images/wow.jpg']->setMetaData(array('mime-type' => 'image/jpeg'));
$p['index.php'] = file_get_contents('index.php');
$p->setMetaData(array('bootstrap' => 'index.php'));
// save the phar archive to disk
$p->stopBuffering();
}
} catch (Exception $e) {
echo 'Could not open Phar: ', $e;
}
?>
In addition, verification of phar file contents can be done using any of
the supported symmetric hash algorithms (MD5, SHA1, SHA256 and SHA512 if
ext/hash is enabled) and using asymmetric public/private key signing using
OpenSSL (new in Phar 2.0.0). To take advantage of OpenSSL signing, you
need to generate a public/private key pair, and use the private key to set
the signature using Phar::setSignatureAlgorithm(). In addition, the public
key as extracted using this code:
must be saved adjacent to the phar archive it verifies. If the phar
archive is saved as /path/to/my.phar, the public key must be saved as
/path/to/my.phar.pubkey, or phar will be unable to verify the OpenSSL
signature.
As of version 2.0.0, The Phar class also provides 3 static methods,
Phar::webPhar(), Phar::mungServer() and Phar::interceptFileFuncs() that
are crucial to packaging up PHP applications designed for usage on regular
filesystems and for web-based applications. Phar::webPhar() implements a
front controller that routes HTTP calls to the correct location within the
phar archive. Phar::mungServer() is used to modify the values of the
$_SERVER array to trick applications that process these values.
Phar::interceptFileFuncs() instructs Phar to intercept calls to fopen(),
file_get_contents(), opendir(), and all of the stat-based functions
(file_exists(), is_readable() and so on) and route all relative paths to
locations within the phar archive.
As an example, packaging up a release of the popular phpMyAdmin
application for use as a phar archive requires only this simple script and
then phpMyAdmin.phar.tar.php can be accessed as a regular file from your
web server after modifying the user/password:
startBuffering();
$a["phpMyAdmin-2.11.3-english/config.inc.php"] = 'setStub('stopBuffering();
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
Using Phar Archives: the phar stream wrapper
The Phar stream wrapper fully supports fopen() for read and write (not
append), unlink(), stat(), fstat(), fseek(), rename() and directory stream
operations opendir() and as of version 2.0.0, rmdir() and mkdir().
Individual file compression and per-file metadata can also be manipulated
in a Phar archive using stream contexts:
array('compress' => Phar::GZ)),
array('metadata' => array('user' => 'cellog')));
file_put_contents('phar://my.phar/somefile.php', 0, $context);
?>
The phar stream wrapper does not operate on remote files, and cannot
operate on remote files, and so is allowed even when the allow_url_fopen
and allow_url_include INI options are disabled.
Although it is possible to create phar archives from scratch just using
stream operations, it is best to use the functionality built into the Phar
class. The stream wrapper is best used for read-only operations.
----------------------------------------------------------------------
----------------------------------------------------------------------
Using Phar Archives: the Phar and PharData class
The Phar class supports reading and manipulation of Phar archives, as well
as iteration through inherited functionality of the
RecursiveDirectoryIterator class. With support for the ArrayAccess
interface, files inside a Phar archive can be accessed as if they were
part of an associative array.
The PharData class extends the Phar, and allows creating and modifying
non-executable (data) tar and zip archives even if phar.readonly=1 in
php.ini. As such, PharData::setAlias() and PharData::setStub() are both
disabled as the concept of alias and stub are unique to executable phar
archives.
It is important to note that when creating a Phar archive, the full path
should be passed to the Phar object constructor. Relative paths will fail
to initialize.
Assuming that $p is a Phar object initialized as follows:
An empty Phar archive will be created at /path/to/myphar.phar, or if
/path/to/myphar.phar already exists, it will be opened again. The literal
myphar.phar demonstrates the concept of an alias that can be used to
reference /path/to/myphar.phar in URLs as in:
With the newly created $p Phar object, the following is possible:
* $a = $p['file.php'] creates a PharFileInfo class that refers to the
contents of phar://myphar.phar/file.php
* $p['file.php'] = $v creates a new file (phar://myphar.phar/file.php),
or overwrites an existing file within myphar.phar. $v can be either a
string or an open file pointer, in which case the entire contents of
the file will be used to create the new file. Note that
$p->addFromString('file.php', $v) is functionally equivalent to the
above. Also possible is to add the contents of a file with
$p->addFile('/path/to/file.php', 'file.php'). Lastly, an empty
directory can be created with $p->addEmptyDir('empty').
* isset($p['file.php']) can be used to determine whether
phar://myphar.phar/file.php exists within myphar.phar.
* unset($p['file.php']) erases phar://myphar.phar/file.php from
myphar.phar.
In addition, the Phar object is the only way to access Phar-specific
metadata, through Phar::getMetaData(), and the only way to set or retrieve
a Phar archive's PHP loader stub through Phar::getStub() and
Phar::setStub(). Additionally, compression for the entire Phar archive at
once can only be manipulated using the Phar class.
The full list of Phar object functionality is documented below.
The PharFileInfo class extends the SplFileInfo class, and adds several
methods for manipulating Phar-specific details of a file contained within
a Phar, such as manipulating compression and metadata.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Creating Phar Archives
Table of Contents
* Creating Phar Archives: Introduction
----------------------------------------------------------------------
Creating Phar Archives: Introduction
To be written fully in the near future. Before reading this, be sure to
read How to use Phar Archives.
A great place to start is by reading about Phar::buildFromIterator(), and
the specifics of the file format choices available for archives. A healthy
understanding of what a stub is and does is crucial to phar archive
creation, and so Phar::setStub() and Phar::createDefaultStub() are good
places to start as well. If you are distributing a web-based application,
it is crucial to know about Phar::webPhar() and related method
Phar::mungServer(). Any application that accesses its own files should
also consider using Phar::interceptFileFuncs().
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
What makes a phar a phar and not a tar or a zip?
Table of Contents
* Ingredients of all Phar archives, independent of file format
* Phar file stub
* Head-to-head comparison of Phar, Tar and Zip
* Tar-based phars
* Zip-based phars
* Phar File Format
* Global Phar bitmapped flags
* Phar manifest file entry definition
* Phar Signature format
----------------------------------------------------------------------
Ingredients of all Phar archives, independent of file format
All Phar archives contain three to four sections:
1. a stub
2. a manifest describing the contents
3. the file contents
4. [optional] a signature for verifying Phar integrity (phar file format
only)
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar file stub
A Phar's stub is a simple PHP file. The smallest possible stub follows:
may be included or omitted, but there can be no more than 1 space between
the ; and the close tag
?>
or the phar extension will be unable to process the Phar archive's
manifest.
In a tar or zip-based phar archive, the stub is stored in the
.phar/stub.php file. The default stub for phar-based Phar archives
contains approximately 7k of code to extract the contents of the phar and
execute them. See Phar::createDefaultStub() for more detail.
The phar alias is stored in a tar or zip-based phar archive in the
.phar/alias.txt file as plain text.
----------------------------------------------------------------------
----------------------------------------------------------------------
Head-to-head comparison of Phar, Tar and Zip
What are the good and the bad things about the three supported file
formats in the phar extension? This table attempts to address that
question.
Feature matrix: Phar vs. Tar vs. Zip
Feature Phar Tar Zip
Standard File Format No Yes Yes
Can be executed without the Phar Extension [1] Yes No No
Per-file compression Yes No Yes
Whole-archive compression Yes Yes No
Whole-archive signature validation Yes Yes Yes (PHP 5.3.1+)
Web-specific application support Yes Yes Yes
Per-file Meta-data Yes Yes Yes
Whole-Archive Meta-data Yes Yes Yes
Archive creation/modification [2] Yes Yes Yes
Full support for all stream wrapper functions Yes Yes Yes
Can be created/modified even if phar.readonly=1 No Yes Yes
[3]
Tip
[1] PHP can only directly access the contents of a Phar archive without
the Phar extension if it is using a stub that extracts the contents of the
phar archive. The stub created by Phar::createDefaultStub() extracts the
phar archive and runs its contents from a temporary directory if no phar
extension is found.
Tip
[2] All write access requires phar.readonly to be disabled in php.ini or
on the command-line directly.
Tip
[3] Only tar and zip archives without .phar in their filename and without
an executable stub .phar/stub.php can be created if phar.readonly=1.
----------------------------------------------------------------------
----------------------------------------------------------------------
Tar-based phars
Archives based on the tar file format follow the more modern USTAR file
format. The design of the tar file header makes them more efficient to
access than the zip file format, and almost as efficient as the phar file
format. File names are limited to 255 bytes, including full path within
the phar archive. There is no limit on the number of files within a
tar-based phar archive. These archives can fully compressed in gzip or
bzip2 format and still be executed by the Phar extension.
To compress an entire archive, use Phar::compress(). To decompress an
entire archive, use Phar::decompress().
----------------------------------------------------------------------
----------------------------------------------------------------------
Zip-based phars
Archives based on the zip file format support several features built into
the zip file format. Per-file and whole-archive metadata is stored in the
zip file comment and zip archive comment as a serialized string.
Pre-existing zip comments will be successfully read as a string. Per-file
compression read/write is supported with zlib compression, and read access
is supported with bzip2 compression. There is no limit on the number of
files within a zip-based phar archive. Empty directories are stored in the
zip archive as files with a trailing slash like my/directory/
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar File Format
The phar file format is literally laid out as
stub/manifest/contents/signature, and stores the crucial information of
what is included in the phar archive in its manifest.
The Phar manifest is a highly optimized format that allows per-file
specification of file compression, file permissions, and even user-defined
meta-data such as file user or group. All values greater than 1 byte are
stored in little-endian byte order, with the exception of the API version,
which for historical reasons is stored as 3 nibbles in big-endian order.
All unused flags are reserved for future use, and must not be used to
store custom information. Use the per-file meta-data facility to store
customized information about particular files.
The basic file format of a Phar archive manifest is as follows:
Global Phar manifest format
Size in bytes Description
4 bytes Length of manifest in bytes (1 MB limit)
4 bytes Number of files in the Phar
2 bytes API version of the Phar manifest
(currently 1.0.0)
4 bytes Global Phar bitmapped flags
4 bytes Length of Phar alias
?? Phar alias (length based on previous)
4 bytes Length of Phar metadata (0 for none)
?? Serialized Phar Meta-data, stored in
serialize() format
at least 24 * number of entries entries for each file
bytes
----------------------------------------------------------------------
----------------------------------------------------------------------
Global Phar bitmapped flags
Here are the bitmapped flags currently recognized by the Phar extension
for the global Phar flat bitmap:
Bitmap values recognized
Value Description
0x00010000 If set, this Phar contains a verification signature
0x00001000 If set, this Phar contains at least 1 file that is compressed
with zlib compression
0x00002000 If set, this Phar contains at least 1 file that is compressed
with bzip compression
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar manifest file entry definition
Each file in the manifest contains the following information:
Phar Manifest file entry
Size in bytes Description
4 bytes Filename length in bytes
?? Filename (length specified in previous)
4 bytes Un-compressed file size in bytes
4 bytes Unix timestamp of file
4 bytes Compressed file size in bytes
4 bytes CRC32 checksum of un-compressed file contents
4 bytes Bit-mapped File-specific flags
4 bytes Serialized File Meta-data length (0 for none)
?? Serialized File Meta-data, stored in serialize() format
Note that as of API version 1.1.1, empty directories are stored as
filenames with a trailing slash like my/directory/
The File-specific bitmap values recognized are:
Bitmap values recognized
Value Description
These bits are reserved for defining specific file permissions
0x000001FF of a file. Permissions are used for fstat() and can be used to
recreate desired permissions upon extraction.
0x00001000 If set, this file is compressed with zlib compression
0x00002000 If set, this file is compressed with bzip compression
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar Signature format
Phars containing a signature always have the signature appended to the end
of the Phar archive after the loader, manifest, and file contents. The two
signature formats supported at this time are MD5 and SHA1.
Signature format
Length in bytes Description
The actual signature, 20 bytes for an SHA1 signature, 16
16 or 20 bytes bytes for an MD5 signature, 32 bytes for an SHA256
signature, and 64 bytes for an SHA512 signature.
Signature flags. 0x0001 is used to define an MD5
signature, 0x0002 is used to define an SHA1 signature,
4 bytes 0x0004 is used to define an SHA256 signature, and 0x0008
is used to define an SHA512 signature. The SHA256 and
SHA512 signature support was introduced with API version
1.1.0.
4 bytes Magic GBMB used to define the presence of a signature.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
The Phar class
Introduction
The Phar class provides a high-level interface to accessing and creating
phar archives.
Class synopsis
Phar extends RecursiveDirectoryIterator implements Countable , ArrayAccess
{
/* Properties */
/* Methods */
void addEmptyDir ( string $dirname )
void addFile ( string $file [, string $localname ] )
void addFromString ( string $localname , string $contents )
string apiVersion ( void )
array buildFromDirectory ( string $base_dir [, string $regex ] )
array buildFromIterator ( Iterator $iter [, string $base_directory ] )
bool canCompress ([ int $type = 0 ] )
bool canWrite ( void )
object compress ( int $compression [, string $extension ] )
bool compressAllFilesBZIP2 ( void )
bool compressAllFilesGZ ( void )
void compressFiles ( int $compression )
void __construct ( string $fname [, int $flags [, string $alias ]] )
PharData convertToData ([ int $format = 9021976 [, int $compression =
9021976 [, string $extension ]]] )
Phar convertToExecutable ([ int $format = 9021976 [, int $compression =
9021976 [, string $extension ]]] )
bool copy ( string $oldfile , string $newfile )
int count ( void )
string createDefaultStub ([ string $indexfile [, string $webindexfile ]] )
object decompress ([ string $extension ] )
bool decompressFiles ( void )
bool delMetadata ( void )
bool delete ( string $entry )
bool extractTo ( string $pathto [, string|array $files [, bool $overwrite
= false ]] )
mixed getMetaData ( void )
bool getModified ( void )
array getSignature ( void )
string getStub ( void )
array getSupportedCompression ( void )
array getSupportedSignatures ( void )
string getVersion ( void )
bool hasMetadata ( void )
void interceptFileFuncs ( void )
bool isBuffering ( void )
mixed isCompressed ( void )
bool isFileFormat ( int $format )
bool isValidPharFilename ( string $filename [, bool $executable = true ] )
bool isWritable ( void )
bool loadPhar ( string $filename [, string $alias ] )
bool mapPhar ([ string $alias [, int $dataoffset = 0 ]] )
void mount ( string $pharpath , string $externalpath )
void mungServer ( array $munglist )
bool offsetExists ( string $offset )
int offsetGet ( string $offset )
void offsetSet ( string $offset , string $value )
bool offsetUnset ( string $offset )
string running ([ bool $retphar = true ] )
bool setAlias ( string $alias )
bool setDefaultStub ([ string $index [, string $webindex ]] )
void setMetadata ( mixed $metadata )
void setSignatureAlgorithm ( int $sigtype [, string $privatekey ] )
bool setStub ( string $stub )
void startBuffering ( void )
void stopBuffering ( void )
bool uncompressAllFiles ( void )
bool unlinkArchive ( string $archive )
void webPhar ([ string $alias [, string $index = "index.php" [, string
$f404 [, array $mimetypes [, array $rewrites ]]]]] )
}
----------------------------------------------------------------------
Phar::addEmptyDir
(Unknown)
Phar::addEmptyDir - Add an empty directory to the phar archive
Description
void Phar::addEmptyDir ( string $dirname )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
With this method, an empty directory is created with path dirname. This
method is similar to ZipArchive::addEmptyDir().
Parameters
dirname
The name of the empty directory to create in the phar archive
Return Values
no return value, exception is thrown on failure.
Examples
Example #1 A Phar::addEmptyDir() example
addEmptyDir('/full/path/to/file');
// demonstrates how this file is stored
$b = $a['full/path/to/file']->isDir();
} catch (Exception $e) {
// handle errors here
}
?>
See Also
* PharData::addEmptyDir() - Add an empty directory to the tar/zip
archive
* Phar::addFile() - Add a file from the filesystem to the phar archive
* Phar::addFromString() - Add a file from the filesystem to the phar
archive
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::addFile
(Unknown)
Phar::addFile - Add a file from the filesystem to the phar archive
Description
void Phar::addFile ( string $file [, string $localname ] )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
With this method, any file or URL can be added to the phar archive. If the
optional second parameter localname is specified, the file will be stored
in the archive with that name, otherwise the file parameter is used as the
path to store within the archive. URLs must have a localname or an
exception is thrown. This method is similar to ZipArchive::addFile().
Parameters
file
Full or relative path to a file on disk to be added to the phar
archive.
localname
Path that the file will be stored in the archive.
Return Values
no return value, exception is thrown on failure.
Examples
Example #1 A Phar::addFile() example
addFile('/full/path/to/file');
// demonstrates how this file is stored
$b = $a['full/path/to/file']->getContent();
$a->addFile('/full/path/to/file', 'my/file.txt');
$c = $a['my/file.txt']->getContent();
// demonstrate URL usage
$a->addFile('http://www.example.com', 'example.html');
} catch (Exception $e) {
// handle errors here
}
?>
See Also
* Phar::offsetSet() - set the contents of an internal file to those of
an external file
* PharData::addFile() - Add a file from the filesystem to the tar/zip
archive
* Phar::addFromString() - Add a file from the filesystem to the phar
archive
* Phar::addEmptyDir() - Add an empty directory to the phar archive
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::addFromString
(Unknown)
Phar::addFromString - Add a file from the filesystem to the phar archive
Description
void Phar::addFromString ( string $localname , string $contents )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
With this method, any string can be added to the phar archive. The file
will be stored in the archive with localname as its path. This method is
similar to ZipArchive::addFromString().
Parameters
localname
Path that the file will be stored in the archive.
contents
The file contents to store
Return Values
no return value, exception is thrown on failure.
Examples
Example #1 A Phar::addFromString() example
addFromString('path/to/file.txt', 'my simple file');
$b = $a['path/to/file.txt']->getContent();
// to add contents from a stream handle for large files, use offsetSet()
$c = fopen('/path/to/hugefile.bin');
$a['largefile.bin'] = $c;
fclose($c);
} catch (Exception $e) {
// handle errors here
}
?>
See Also
* Phar::offsetSet() - set the contents of an internal file to those of
an external file
* PharData::addFromString() - Add a file from the filesystem to the
tar/zip archive
* Phar::addFile() - Add a file from the filesystem to the phar archive
* Phar::addEmptyDir() - Add an empty directory to the phar archive
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::apiVersion
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::apiVersion - Returns the api version
Description
string Phar::apiVersion ( void )
Return the API version of the phar file format that will be used when
creating phars. The Phar extension supports reading API version 1.0.0 or
newer. API version 1.1.0 is required for SHA-256 and SHA-512 hash, and API
version 1.1.1 is required to store empty directories.
Parameters
Return Values
The API version string as in "1.0.0".
Examples
Example #1 A Phar::apiVersion() example
The above example will output:
1.1.1
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::buildFromDirectory
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::buildFromDirectory - Construct a phar archive from the files within
a directory.
Description
array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
Populate a phar archive from directory contents. The optional second
parameter is a regular expression (pcre) that is used to exclude files.
Any filename that matches the regular expression will be included, all
others will be excluded. For more fine-grained control, use
Phar::buildFromIterator().
Parameters
base_dir
The full or relative path to the directory that contains all files
to add to the archive.
regex
An optional pcre regular expression that is used to filter the
list of files. Only file paths matching the regular expression
will be included in the archive.
Return Values
Phar::buildFromDirectory() returns an associative array mapping internal
path of file to the full path of the file on the filesystem.
Errors/Exceptions
This method throws BadMethodCallException when unable to instantiate the
internal directory iterators, or a PharException if there were errors
saving the phar archive.
Examples
Example #1 A Phar::buildFromDirectory() example
buildFromDirectory(dirname(__FILE__) . '/project');
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
$phar2 = new Phar('project2.phar', 0, 'project2.phar');
// add all files in the project, only include php files
$phar2->buildFromDirectory(dirname(__FILE__) . '/project', '/\.php$/');
$phar2->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>
See Also
* Phar::buildFromIterator() - Construct a phar archive from an iterator.
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::buildFromIterator
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::buildFromIterator - Construct a phar archive from an iterator.
Description
array Phar::buildFromIterator ( Iterator $iter [, string $base_directory ]
)
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
Populate a phar archive from an iterator. Two styles of iterators are
supported, iterators that map the filename within the phar to the name of
a file on disk, and iterators like DirectoryIterator that return
SplFileInfo objects. For iterators that return SplFileInfo objects, the
second parameter is required.
Parameters
iter
Any iterator that either associatively maps phar file to location
or returns SplFileInfo objects
base_directory
For iterators that return SplFileInfo objects, the portion of each
file's full path to remove when adding to the phar archive
Return Values
Phar::buildFromIterator() returns an associative array mapping internal
path of file to the full path of the file on the filesystem.
Examples
Example #1 A Phar::buildFromIterator() with SplFileInfo
For most phar archives, the archive will reflect an actual directory
layout, and the second style is the most useful. For instance, to create a
phar archive containing the files in this sample directory layout:
/path/to/project/
config/
dist.xml
debug.xml
lib/
file1.php
file2.php
src/
processthing.php
www/
index.php
cli/
index.php
This code could be used to add these files to the "project.phar" phar
archive:
buildFromIterator(
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/path/to/project')),
'/path/to/project');
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>
The file project.phar can then be used immediately.
Phar::buildFromIterator() does not set values such as compression,
metadata, and this can be done after creating the phar archive.
As an interesting note, Phar::buildFromIterator() can also be used to copy
the contents of an existing phar archive, as the Phar object descends from
DirectoryIterator:
buildFromIterator(
new RecursiveIteratorIterator(
new Phar('/path/to/anotherphar.phar')),
'phar:///path/to/anotherphar.phar/path/to/project');
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>
Example #2 A Phar::buildFromIterator() with other iterators
The second form of the iterator can be used with any iterator that returns
a key => value mapping, such as an ArrayIterator:
buildFromIterator(
new ArrayIterator(
array(
'internal/file.php' => dirname(__FILE__) . '/somefile.php',
'another/file.jpg' => fopen('/path/to/bigfile.jpg', 'rb'),
)));
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>
Errors/Exceptions
This method returns UnexpectedValueException when the iterator returns
incorrect values, such as an integer key instead of a string, a
BadMethodCallException when an SplFileInfo-based iterator is passed
without a base_directory parameter, or a PharException if there were
errors saving the phar archive.
See Also
* Phar::buildFromDirectory() - Construct a phar archive from the files
within a directory.
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::canCompress
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::canCompress - Returns whether phar extension supports compression
using either zlib or bzip2
Description
bool Phar::canCompress ([ int $type = 0 ] )
This should be used to test whether compression is possible prior to
loading a phar archive containing compressed files.
Parameters
type
Either Phar::GZ or Phar::BZ2 can be used to test whether
compression is possible with a specific compression algorithm
(zlib or bzip2).
Return Values
TRUE if compression/decompression is available, FALSE if not.
Examples
Example #1 A Phar::canCompress() example
See Also
* PharFileInfo::getCompressedSize() - Returns the actual size of the
file (with compression) inside the Phar archive
* PharFileInfo::isCompressed() - Returns whether the entry is compressed
* PharFileInfo::compress() - Compresses the current Phar entry with
either zlib or bzip2 compression
* PharFileInfo::decompress() - Decompresses the current Phar entry
within the phar
* Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire
phar archive is compressed (.tar.gz/tar.bz and so on)
* Phar::compressFiles() - Compresses all files in the current Phar
archive
* Phar::decompressFiles() - Decompresses all files in the current Phar
archive
* Phar::getSupportedCompression() - Return array of supported
compression algorithms
* Phar::convertToExecutable() - Convert a phar archive to another
executable phar archive file format
* Phar::convertToData() - Convert a phar archive to a non-executable tar
or zip file
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::canWrite
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::canWrite - Returns whether phar extension supports writing and
creating phars
Description
bool Phar::canWrite ( void )
This static method determines whether write access has been disabled in
the system php.ini via the phar.readonly ini variable.
Parameters
Return Values
TRUE if write access is enabled, FALSE if it is disabled.
Examples
Example #1 A Phar::canWrite() example
See Also
* phar.readonly
* Phar::isWritable() - Returns true if the phar archive can be modified
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::compress
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::compress - Compresses the entire Phar archive using Gzip or Bzip2
compression
Description
object Phar::compress ( int $compression [, string $extension ] )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
For tar-based and phar-based phar archives, this method compresses the
entire archive using gzip compression or bzip2 compression. The resulting
file can be processed with the gunzip command/bunzip command, or accessed
directly and transparently with the Phar extension.
For Zip-based phar archives, this method fails with an exception. The zlib
extension must be enabled to compress with gzip compression, the bzip2
extension must be enabled in order to compress with bzip2 compression. As
with all functionality that modifies the contents of a phar, the
phar.readonly INI variable must be off in order to succeed.
In addition, this method automatically renames the archive, appending .gz,
.bz2 or removing the extension if passed Phar::NONE to remove compression.
Alternatively, a file extension may be specified with the second
parameter.
Parameters
compression
Compression must be one of Phar::GZ, Phar::BZ2 to add compression,
or Phar::NONE to remove compression.
extension
By default, the extension is .phar.gz or .phar.bz2 for compressing
phar archives, and .phar.tar.gz or .phar.tar.bz2 for compressing
tar archives. For decompressing, the default file extensions are
.phar and .phar.tar.
Return Values
Returns a Phar object.
Errors/Exceptions
Throws BadMethodCallException if the phar.readonly INI variable is on, the
zlib extension is not available, or the bzip2 extension is not enabled.
Examples
Example #1 A Phar::compress() example
compress(Phar::GZ); // copies to /path/to/my.phar.gz
$p2 = $p->compress(Phar::BZ2); // copies to /path/to/my.phar.bz2
$p3 = $p2->compress(Phar::NONE); // exception: /path/to/my.phar already exists
?>
See Also
* PharFileInfo::getCompressedSize() - Returns the actual size of the
file (with compression) inside the Phar archive
* PharFileInfo::isCompressed() - Returns whether the entry is compressed
* PharFileInfo::compress() - Compresses the current Phar entry with
either zlib or bzip2 compression
* PharFileInfo::decompress() - Decompresses the current Phar entry
within the phar
* PharData::compress() - Compresses the entire tar/zip archive using
Gzip or Bzip2 compression
* Phar::canCompress() - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire
phar archive is compressed (.tar.gz/tar.bz and so on)
* Phar::decompress() - Decompresses the entire Phar archive
* Phar::getSupportedCompression() - Return array of supported
compression algorithms
* Phar::compressFiles() - Compresses all files in the current Phar
archive
* Phar::decompressFiles() - Decompresses all files in the current Phar
archive
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::compressAllFilesBZIP2
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::compressAllFilesBZIP2 - Compresses all files in the current Phar
archive using Bzip2 compression
Description
bool Phar::compressAllFilesBZIP2 ( void )
Note:
This method has been removed from the phar extension as of version
2.0.0. Alternative implementations are available using Phar::compress(),
Phar::decompress(), Phar::compressFiles() and Phar::decompressFiles().
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
This method compresses all files in the Phar archive using bzip2
compression. The bzip2 extension must be enabled to take advantage of this
feature. In addition, if any files are already compressed using gzip
compression, the zlib extension must be enabled in order to decompress the
files prior to re-compressing with bzip2 compression. As with all
functionality that modifies the contents of a phar, the phar.readonly INI
variable must be off in order to succeed.
Return Values
Returns TRUE on success or FALSE on failure.
Errors/Exceptions
Throws BadMethodCallException if the phar.readonly INI variable is on, the
bzip2 extension is not available, or if any files are compressed using
gzip compression and the zlib extension is not enabled.
Examples
Example #1 A Phar::compressAllFilesBZIP2() example
getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressedBZIP2());
var_dump($file->isCompressedGZ());
}
$p->compressAllFilesBZIP2();
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressedBZIP2());
var_dump($file->isCompressedGZ());
}
?>
The above example will output:
string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
string(10) "myfile.txt"
bool(true)
bool(true)
bool(false)
string(11) "myfile2.txt"
bool(true)
bool(true)
bool(false)
See Also
* PharFileInfo::getCompressedSize() - Returns the actual size of the
file (with compression) inside the Phar archive
* PharFileInfo::isCompressedBZIP2() - Returns whether the entry is
compressed using bzip2
* PharFileInfo::isCompressed() - Returns whether the entry is compressed
* PharFileInfo::isCompressedGZ() - Returns whether the entry is
compressed using gz
* PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry
within the phar using Bzip2 compression
* PharFileInfo::setUncompressed() - Uncompresses the current Phar entry
within the phar, if it is compressed
* PharFileInfo::setCompressedGZ() - Compresses the current Phar entry
within the phar using gz compression
* Phar::canCompress() - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire
phar archive is compressed (.tar.gz/tar.bz and so on)
* Phar::compressAllFilesGZ() - Compresses all files in the current Phar
archive using Gzip compression
* Phar::getSupportedCompression() - Return array of supported
compression algorithms
* Phar::uncompressAllFiles() - Uncompresses all files in the current
Phar archive
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::compressAllFilesGZ
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::compressAllFilesGZ - Compresses all files in the current Phar
archive using Gzip compression
Description
bool Phar::compressAllFilesGZ ( void )
Note:
This method has been removed from the phar extension as of version
2.0.0. Alternative implementations are available using Phar::compress(),
Phar::decompress(), Phar::compressFiles() and Phar::decompressFiles().
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
For tar-based phar archives, this method compresses the entire archive
using gzip compression. The resulting file can be processed with the
gunzip command, or accessed directly and transparently with the Phar
extension.
For Zip-based and phar-based phar archives, this method compresses all
files in the Phar archive using gzip compression. The zlib extension must
be enabled to take advantage of this feature. In addition, if any files
are already compressed using bzip2 compression, the bzip2 extension must
be enabled in order to decompress the files prior to re-compressing with
gzip compression. As with all functionality that modifies the contents of
a phar, the phar.readonly INI variable must be off in order to succeed.
Return Values
Returns TRUE on success or FALSE on failure.
Errors/Exceptions
Throws BadMethodCallException if the phar.readonly INI variable is on, the
zlib extension is not available, or if any files are compressed using
bzip2 compression and the bzip2 extension is not enabled.
Examples
Example #1 A Phar::compressAllFilesGZ() example
getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressedBZIP2());
var_dump($file->isCompressedGZ());
}
$p->compressAllFilesGZ();
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressedBZIP2());
var_dump($file->isCompressedGZ());
}
?>
The above example will output:
string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
string(10) "myfile.txt"
bool(true)
bool(false)
bool(true)
string(11) "myfile2.txt"
bool(true)
bool(false)
bool(true)
See Also
* PharFileInfo::getCompressedSize() - Returns the actual size of the
file (with compression) inside the Phar archive
* PharFileInfo::isCompressedBZIP2() - Returns whether the entry is
compressed using bzip2
* PharFileInfo::isCompressed() - Returns whether the entry is compressed
* PharFileInfo::isCompressedGZ() - Returns whether the entry is
compressed using gz
* PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry
within the phar using Bzip2 compression
* PharFileInfo::setUncompressed() - Uncompresses the current Phar entry
within the phar, if it is compressed
* PharFileInfo::setCompressedGZ() - Compresses the current Phar entry
within the phar using gz compression
* Phar::canCompress() - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire
phar archive is compressed (.tar.gz/tar.bz and so on)
* Phar::compressAllFilesBZIP2() - Compresses all files in the current
Phar archive using Bzip2 compression
* Phar::getSupportedCompression() - Return array of supported
compression algorithms
* Phar::uncompressAllFiles() - Uncompresses all files in the current
Phar archive
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::compressFiles
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::compressFiles - Compresses all files in the current Phar archive
Description
void Phar::compressFiles ( int $compression )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
For tar-based phar archives, this method throws a BadMethodCallException,
as compression of individual files within a tar archive is not supported
by the file format. Use Phar::compress() to compress an entire tar-based
phar archive.
For Zip-based and phar-based phar archives, this method compresses all
files in the Phar archive using the specified compression. The zlib or
bzip2 extensions must be enabled to take advantage of this feature. In
addition, if any files are already compressed using bzip2/zlib
compression, the respective extension must be enabled in order to
decompress the files prior to re-compressing. As with all functionality
that modifies the contents of a phar, the phar.readonly INI variable must
be off in order to succeed.
Parameters
compression
Compression must be one of Phar::GZ, Phar::BZ2 to add compression,
or Phar::NONE to remove compression.
Return Values
No value is returned.
Errors/Exceptions
Throws BadMethodCallException if the phar.readonly INI variable is on, the
zlib extension is not available, or if any files are compressed using
bzip2 compression and the bzip2 extension is not enabled.
Examples
Example #1 A Phar::compressFiles() example
getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressed(Phar::BZ2));
var_dump($file->isCompressed(Phar::GZ));
}
$p->compressFiles(Phar::GZ);
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressed(Phar::BZ2));
var_dump($file->isCompressed(Phar::GZ));
}
?>
The above example will output:
string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
string(10) "myfile.txt"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)
See Also
* PharFileInfo::getCompressedSize() - Returns the actual size of the
file (with compression) inside the Phar archive
* PharFileInfo::isCompressed() - Returns whether the entry is compressed
* PharFileInfo::compress() - Compresses the current Phar entry with
either zlib or bzip2 compression
* PharFileInfo::decompress() - Decompresses the current Phar entry
within the phar
* Phar::canCompress() - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire
phar archive is compressed (.tar.gz/tar.bz and so on)
* Phar::decompressFiles() - Decompresses all files in the current Phar
archive
* Phar::getSupportedCompression() - Return array of supported
compression algorithms
* Phar::compress() - Compresses the entire Phar archive using Gzip or
Bzip2 compression
* Phar::decompress() - Decompresses the entire Phar archive
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::__construct
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::__construct - Construct a Phar archive object
Description
void Phar::__construct ( string $fname [, int $flags [, string $alias ]] )
Parameters
fname
Path to an existing Phar archive or to-be-created archive
flags
Flags to pass to parent class RecursiveDirectoryIterator.
alias
Alias with which this Phar archive should be referred to in calls
to stream functionality.
Errors/Exceptions
Throws BadMethodCallException if called twice, UnexpectedValueException if
the phar archive can't be opened.
Examples
Example #1 A Phar::__construct() example
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::convertToData
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::convertToData - Convert a phar archive to a non-executable tar or
zip file
Description
PharData Phar::convertToData ([ int $format = 9021976 [, int $compression
= 9021976 [, string $extension ]]] )
This method is used to convert an executable phar archive to either a tar
or zip file. To make the tar or zip non-executable, the phar stub and phar
alias files are removed from the newly created archive.
If no changes are specified, this method throws a BadMethodCallException
if the archive is in phar file format. For archives in tar or zip file
format, this method converts the archive to a non-executable archive.
If successful, the method creates a new archive on disk and returns a
PharData object. The old archive is not removed from disk, and should be
done manually after the process has finished.
Parameters
format
This should be one of Phar::TAR or Phar::ZIP. If set to NULL, the
existing file format will be preserved.
compression
This should be one of Phar::NONE for no whole-archive compression,
Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based
compression.
extension
This parameter is used to override the default file extension for
a converted archive. Note that .phar cannot be used anywhere in
the filename for a non-executable tar or zip archive.
If converting to a tar-based phar archive, the default extensions
are .tar, .tar.gz, and .tar.bz2 depending on specified
compression. For zip-based archives, the default extension is
.zip.
Return Values
The method returns a PharData object on success and throws an exception on
failure.
Errors/Exceptions
This method throws BadMethodCallException when unable to compress, an
unknown compression method has been specified, the requested archive is
buffering with Phar::startBuffering() and has not concluded with
Phar::stopBuffering(), and a PharException if any problems are encountered
during the phar creation process.
Examples
Example #1 A Phar::convertToData() example
Using Phar::convertToData():
convertToData();
// convert to non-executable zip format, creates myphar.zip
$zip = $tarphar->convertToData(Phar::ZIP);
// create myphar.tbz
$tgz = $tarphar->convertToData(Phar::TAR, Phar::BZ2, '.tbz');
// creates myphar.phar.tgz
$phar = $tarphar->convertToData(Phar::PHAR); // throws exception
} catch (Exception $e) {
// handle the error here
}
?>
See Also
* Phar::convertToExecutable() - Convert a phar archive to another
executable phar archive file format
* PharData::convertToExecutable() - Convert a non-executable tar/zip
archive to an executable phar archive
* PharData::convertToData() - Convert a phar archive to a non-executable
tar or zip file
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::convertToExecutable
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::convertToExecutable - Convert a phar archive to another executable
phar archive file format
Description
Phar Phar::convertToExecutable ([ int $format = 9021976 [, int
$compression = 9021976 [, string $extension ]]] )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
This method is used to convert a phar archive to another file format. For
instance, it can be used to create a tar-based executable phar archive
from a zip-based executable phar archive, or from an executable phar
archive in the phar file format. In addition, it can be used to apply
whole-archive compression to a tar or phar-based archive.
If no changes are specified, this method throws a BadMethodCallException.
If successful, the method creates a new archive on disk and returns a Phar
object. The old archive is not removed from disk, and should be done
manually after the process has finished.
Parameters
format
This should be one of Phar::PHAR, Phar::TAR, or Phar::ZIP. If set
to NULL, the existing file format will be preserved.
compression
This should be one of Phar::NONE for no whole-archive compression,
Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based
compression.
extension
This parameter is used to override the default file extension for
a converted archive. Note that all zip- and tar-based phar
archives must contain .phar in their file extension in order to be
processed as a phar archive.
If converting to a phar-based archive, the default extensions are
.phar, .phar.gz, or .phar.bz2 depending on the specified
compression. For tar-based phar archives, the default extensions
are .phar.tar, .phar.tar.gz, and .phar.tar.bz2. For zip-based phar
archives, the default extension is .phar.zip.
Return Values
The method returns a Phar object on success and throws an exception on
failure.
Errors/Exceptions
This method throws BadMethodCallException when unable to compress, an
unknown compression method has been specified, the requested archive is
buffering with Phar::startBuffering() and has not concluded with
Phar::stopBuffering(), an UnexpectedValueException if write support is
disabled, and a PharException if any problems are encountered during the
phar creation process.
Examples
Example #1 A Phar::convertToExecutable() example
Using Phar::convertToExecutable():
convertToExecutable(Phar::PHAR); // creates myphar.phar
$phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
// creates myphar.phar.tgz
$compressed = $phar->convertToExecutable(Phar::TAR, Phar::GZ, '.phar.tgz');
} catch (Exception $e) {
// handle the error here
}
?>
See Also
* Phar::convertToData() - Convert a phar archive to a non-executable tar
or zip file
* PharData::convertToExecutable() - Convert a non-executable tar/zip
archive to an executable phar archive
* PharData::convertToData() - Convert a phar archive to a non-executable
tar or zip file
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::copy
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::copy - Copy a file internal to the phar archive to another new file
within the phar
Description
bool Phar::copy ( string $oldfile , string $newfile )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
Copy a file internal to the phar archive to another new file within the
phar. This is an object-oriented alternative to using copy() with the phar
stream wrapper.
Parameters
oldfile
newfile
Return Values
returns TRUE on success, but it is safer to encase method call in a
try/catch block and assume success if no exception is thrown.
Errors/Exceptions
throws UnexpectedValueException if the source file does not exist, the
destination file already exists, write access is disabled, opening either
file fails, reading the source file fails, or a PharException if writing
the changes to the phar fails.
Examples
Example #1 A Phar::copy() example
This example shows using Phar::copy() and the equivalent stream wrapper
performance of the same thing. The primary difference between the two
approaches is error handling. All Phar methods throw exceptions, whereas
the stream wrapper uses trigger_error().
copy('a', 'b');
echo $phar['b']; // outputs "hi"
} catch (Exception $e) {
// handle error
}
// the stream wrapper equivalent of the above code.
// E_WARNINGS are triggered on error rather than exceptions.
copy('phar://myphar.phar/a', 'phar//myphar.phar/c');
echo file_get_contents('phar://myphar.phar/c'); // outputs "hi"
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::count
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::count - Returns the number of entries (files) in the Phar archive
Description
int Phar::count ( void )
Parameters
Return Values
The number of files contained within this phar, or 0 (the number zero) if
none.
Examples
Example #1 A Phar::count() example
count() . " entries\n";
$p['file.txt'] = 'hi';
echo 'The new phar has ' . $p->count() . " entries\n";
?>
The above example will output:
The new phar has 0 entries
The new phar has 1 entries
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::createDefaultStub
(Unknown)
Phar::createDefaultStub - Create a phar-file format specific stub
Description
string Phar::createDefaultStub ([ string $indexfile [, string
$webindexfile ]] )
This method is intended for creation of phar-file format-specific stubs,
and is not intended for use with tar- or zip-based phar archives.
Phar archives contain a bootstrap loader, or stub written in PHP that is
executed when the archive is executed in PHP either via include:
or by simple execution:
php myphar.phar
This method provides a simple and easy method to create a stub that will
run a startup file from the phar archive. In addition, different files can
be specified for running the phar archive from the command line versus
through a web server. The loader stub also calls
Phar::interceptFileFuncs() to allow easy bundling of a PHP application
that accesses the file system. If the phar extension is not present, the
loader stub will extract the phar archive to a temporary directory and
then operate on the files. A shutdown function erases the temporary files
on exit.
Return Values
Returns a string containing the contents of a customized bootstrap loader
(stub) that allows the created Phar archive to work with or without the
Phar extension enabled.
Errors/Exceptions
Throws UnexpectedValueException if either parameter is longer than 400
bytes.
Examples
Example #1 A Phar::createDefaultStub() example
setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
} catch (Exception $e) {
// handle errors
}
?>
See Also
* Phar::setStub() - Used to set the PHP loader or bootstrap stub of a
Phar archive
* Phar::getStub() - Return the PHP loader or bootstrap stub of a Phar
archive
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::decompress
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::decompress - Decompresses the entire Phar archive
Description
object Phar::decompress ([ string $extension ] )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
For tar-based and phar-based phar archives, this method decompresses the
entire archive.
For Zip-based phar archives, this method fails with an exception. The zlib
extension must be enabled to decompress an archive compressed with gzip
compression, and the bzip2 extension must be enabled in order to
decompress an archive compressed with bzip2 compression. As with all
functionality that modifies the contents of a phar, the phar.readonly INI
variable must be off in order to succeed.
In addition, this method automatically changes the file extension of the
archive, .phar by default for phar archives, or .phar.tar for tar-based
phar archives. Alternatively, a file extension may be specified with the
second parameter.
Parameters
extension
For decompressing, the default file extensions are .phar and
.phar.tar. Use this parameter to specify another file extension.
Be aware that all executable phar archives must contain .phar in
their filename.
Return Values
A Phar object is returned.
Errors/Exceptions
Throws BadMethodCallException if the phar.readonly INI variable is on, the
zlib extension is not available, or the bzip2 extension is not enabled.
Examples
Example #1 A Phar::decompress() example
decompress(); // creates /path/to/my.phar
?>
See Also
* PharFileInfo::getCompressedSize() - Returns the actual size of the
file (with compression) inside the Phar archive
* PharFileInfo::isCompressed() - Returns whether the entry is compressed
* PharFileInfo::compress() - Compresses the current Phar entry with
either zlib or bzip2 compression
* PharFileInfo::decompress() - Decompresses the current Phar entry
within the phar
* PharData::compress() - Compresses the entire tar/zip archive using
Gzip or Bzip2 compression
* Phar::canCompress() - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire
phar archive is compressed (.tar.gz/tar.bz and so on)
* Phar::compress() - Compresses the entire Phar archive using Gzip or
Bzip2 compression
* Phar::getSupportedCompression() - Return array of supported
compression algorithms
* Phar::compressFiles() - Compresses all files in the current Phar
archive
* Phar::decompressFiles() - Decompresses all files in the current Phar
archive
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::decompressFiles
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::decompressFiles - Decompresses all files in the current Phar archive
Description
bool Phar::decompressFiles ( void )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
For tar-based phar archives, this method throws a BadMethodCallException,
as compression of individual files within a tar archive is not supported
by the file format. Use Phar::compress() to compress an entire tar-based
phar archive.
For Zip-based and phar-based phar archives, this method decompresses all
files in the Phar archive. The zlib or bzip2 extensions must be enabled to
take advantage of this feature if any files are compressed using
bzip2/zlib compression. As with all functionality that modifies the
contents of a phar, the phar.readonly INI variable must be off in order to
succeed.
Return Values
Returns TRUE on success or FALSE on failure.
Errors/Exceptions
Throws BadMethodCallException if the phar.readonly INI variable is on, the
zlib extension is not available, or if any files are compressed using
bzip2 compression and the bzip2 extension is not enabled.
Examples
Example #1 A Phar::decompressFiles() example
compressFiles(Phar::GZ);
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressed(Phar::BZ2));
var_dump($file->isCompressed(Phar::GZ));
}
$p->decompressFiles();
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressed(Phar::BZ2));
var_dump($file->isCompressed(Phar::GZ));
}
?>
The above example will output:
string(10) "myfile.txt"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)
string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
See Also
* PharFileInfo::getCompressedSize() - Returns the actual size of the
file (with compression) inside the Phar archive
* PharFileInfo::isCompressed() - Returns whether the entry is compressed
* PharFileInfo::compress() - Compresses the current Phar entry with
either zlib or bzip2 compression
* PharFileInfo::decompress() - Decompresses the current Phar entry
within the phar
* Phar::canCompress() - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire
phar archive is compressed (.tar.gz/tar.bz and so on)
* Phar::compressFiles() - Compresses all files in the current Phar
archive
* Phar::getSupportedCompression() - Return array of supported
compression algorithms
* Phar::compress() - Compresses the entire Phar archive using Gzip or
Bzip2 compression
* Phar::decompress() - Decompresses the entire Phar archive
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::delMetadata
(PHP >= 5.3.0, PECL phar >= 1.2.0)
Phar::delMetadata - Deletes the global metadata of the phar
Description
bool Phar::delMetadata ( void )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
Deletes the global metadata of the phar
Parameters
Return Values
returns TRUE on success, but it is better to check for thrown exception,
and assume success if none is thrown.
Errors/Exceptions
Throws PharException if errors occur while flushing changes to disk.
Examples
Example #1 A Phar::delMetaData() example
getMetadata());
$phar->setMetadata("hi there");
var_dump($phar->getMetadata());
$phar->delMetadata();
var_dump($phar->getMetadata());
} catch (Exception $e) {
// handle errors
}
?>
The above example will output:
NULL
string(8) "hi there"
NULL
See Also
* Phar::getMetadata() - Returns phar archive meta-data
* Phar::setMetadata() - Sets phar archive meta-data
* Phar::hasMetadata() - Returns whether phar has global meta-data
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::delete
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::delete - Delete a file within a phar archive
Description
bool Phar::delete ( string $entry )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
Delete a file within an archive. This is the functional equivalent of
calling unlink() on the stream wrapper equivalent, as shown in the example
below.
Parameters
entry
Path within an archive to the file to delete.
Return Values
returns TRUE on success, but it is better to check for thrown exception,
and assume success if none is thrown.
Errors/Exceptions
Throws PharException if errors occur while flushing changes to disk.
Examples
Example #1 A Phar::delete() example
delete('unlink/me.php');
// this is equivalent to:
unlink('phar://myphar.phar/unlink/me.php');
} catch (Exception $e) {
// handle errors
}
?>
See Also
* PharData::delete() - Delete a file within a tar/zip archive
* Phar::unlinkArchive() - Completely remove a phar archive from disk and
from memory
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::extractTo
(Unknown)
Phar::extractTo - Extract the contents of a phar archive to a directory
Description
bool Phar::extractTo ( string $pathto [, string|array $files [, bool
$overwrite = false ]] )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
Extract all files within a phar archive to disk. Extracted files and
directories preserve permissions as stored in the archive. The optional
parameters allow optional control over which files are extracted, and
whether existing files on disk can be overwritten. The second parameter
files can be either the name of a file or directory to extract, or an
array of names of files and directories to extract. By default, this
method will not overwrite existing files, the third parameter can be set
to true to enable overwriting of files. This method is similar to
ZipArchive::extractTo().
Parameters
pathto
Path within an archive to the file to delete.
files
The name of a file or directory to extract, or an array of
files/directories to extract
overwrite
Set to TRUE to enable overwriting existing files
Return Values
returns TRUE on success, but it is better to check for thrown exception,
and assume success if none is thrown.
Errors/Exceptions
Throws PharException if errors occur while flushing changes to disk.
Examples
Example #1 A Phar::extractTo() example
extractTo('/full/path'); // extract all files
$phar->extractTo('/another/path', 'file.txt'); // extract only file.txt
$phar->extractTo('/this/path',
array('file1.txt', 'file2.txt')); // extract 2 files only
$phar->extractTo('/third/path', null, true); // extract all files, and overwrite
} catch (Exception $e) {
// handle errors
}
?>
See Also
* PharData::extractTo() - Extract the contents of a tar/zip archive to a
directory
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::getMetaData
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::getMetaData - Returns phar archive meta-data
Description
mixed Phar::getMetaData ( void )
Retrieve archive meta-data. Meta-data can be any PHP variable that can be
serialized.
Parameters
No parameters.
Return Values
any PHP variable that can be serialized and is stored as meta-data for the
Phar archive, or NULL if no meta-data is stored.
Examples
Example #1 A Phar::getMetaData() example
setMetaData(array('bootstrap' => 'file.php'));
var_dump($p->getMetaData());
} catch (Exception $e) {
echo 'Could not modify phar:', $e;
}
?>
The above example will output:
array(1) {
["bootstrap"]=>
string(8) "file.php"
}
See Also
* Phar::setMetadata() - Sets phar archive meta-data
* Phar::delMetadata() - Deletes the global metadata of the phar
* Phar::hasMetadata() - Returns whether phar has global meta-data
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::getModified
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::getModified - Return whether phar was modified
Description
bool Phar::getModified ( void )
This method can be used to determine whether a phar has either had an
internal file deleted, or contents of a file changed in some way.
Parameters
No parameters.
Return Values
TRUE if the phar has been modified since opened, FALSE if not.
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::getSignature
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::getSignature - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a
Phar archive
Description
array Phar::getSignature ( void )
Returns the verification signature of a phar archive in a hexadecimal
string.
Parameters
Return Values
Array with the opened archive's signature in hash key and MD5, SHA-1,
SHA-256, SHA-512, or OpenSSL in hash_type. This signature is a hash
calculated on the entire phar's contents, and may be used to verify the
integrity of the archive. A valid signature is absolutely required of all
executable phar archives if the phar.require_hash INI variable is set to
true.
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::getStub
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::getStub - Return the PHP loader or bootstrap stub of a Phar archive
Description
string Phar::getStub ( void )
Phar archives contain a bootstrap loader, or stub written in PHP that is
executed when the archive is executed in PHP either via include:
or by simple execution:
php myphar.phar
Return Values
Returns a string containing the contents of the bootstrap loader (stub) of
the current Phar archive.
Errors/Exceptions
Throws RuntimeException if it is not possible to read the stub from the
Phar archive.
Examples
Example #1 A Phar::getStub() example
getStub();
echo "==NEXT==\n";
$p->setStub("");
echo $p->getStub();
?>
The above example will output:
==NEXT==
See Also
* Phar::setStub() - Used to set the PHP loader or bootstrap stub of a
Phar archive
* Phar::createDefaultStub() - Create a phar-file format specific stub
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::getSupportedCompression
(PHP >= 5.3.0, PECL phar >= 1.2.0)
Phar::getSupportedCompression - Return array of supported compression
algorithms
Description
array Phar::getSupportedCompression ( void )
Parameters
No parameters.
Return Values
Returns an array containing any of Phar::GZ or Phar::BZ2, depending on the
availability of the zlib extension or the bz2 extension.
See Also
* PharFileInfo::getCompressedSize() - Returns the actual size of the
file (with compression) inside the Phar archive
* PharFileInfo::isCompressed() - Returns whether the entry is compressed
* PharFileInfo::compress() - Compresses the current Phar entry with
either zlib or bzip2 compression
* PharFileInfo::decompress() - Decompresses the current Phar entry
within the phar
* Phar::compress() - Compresses the entire Phar archive using Gzip or
Bzip2 compression
* Phar::decompress() - Decompresses the entire Phar archive
* Phar::canCompress() - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire
phar archive is compressed (.tar.gz/tar.bz and so on)
* Phar::compressFiles() - Compresses all files in the current Phar
archive
* Phar::decompressFiles() - Decompresses all files in the current Phar
archive
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::getSupportedSignatures
(PHP >= 5.3.0, PECL phar >= 1.1.0)
Phar::getSupportedSignatures - Return array of supported signature types
Description
array Phar::getSupportedSignatures ( void )
Return array of supported signature types
Parameters
No parameters.
Return Values
Returns an array containing any of MD5, SHA-1, SHA-256, SHA-512, or
OpenSSL.
See Also
* Phar::getSignature() - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature
of a Phar archive
* Phar::setSignatureAlgorithm() - set the signature algorithm for a phar
and apply it. The
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::getVersion
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::getVersion - Return version info of Phar archive
Description
string Phar::getVersion ( void )
Returns the API version of an opened Phar archive.
Parameters
Return Values
The opened archive's API version. This is not to be confused with the API
version that the loaded phar extension will use to create new phars. Each
Phar archive has the API version hard-coded into its manifest. See Phar
file format documentation for more information.
See Also
* Phar::apiVersion() - Returns the api version
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::hasMetaData
(PHP >= 5.3.0, PECL phar >= 1.2.0)
Phar::hasMetaData - Returns whether phar has global meta-data
Description
bool Phar::hasMetadata ( void )
Returns whether phar has global meta-data set.
Parameters
No parameters.
Return Values
Returns TRUE if meta-data has been set, and FALSE if not.
Examples
Example #1 A Phar::hasMetaData() example
hasMetadata());
$phar->setMetadata(array('thing' => 'hi'));
var_dump($phar->hasMetadata());
$phar->delMetadata();
var_dump($phar->hasMetadata());
} catch (Exception $e) {
// handle error
}
?>
The above example will output:
bool(false)
bool(true)
bool(false)
See Also
* Phar::getMetadata() - Returns phar archive meta-data
* Phar::setMetadata() - Sets phar archive meta-data
* Phar::delMetadata() - Deletes the global metadata of the phar
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::interceptFileFuncs
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::interceptFileFuncs - instructs phar to intercept fopen,
file_get_contents, opendir, and all of the stat-related functions
Description
void Phar::interceptFileFuncs ( void )
instructs phar to intercept fopen(), readfile(), file_get_contents(),
opendir(), and all of the stat-related functions. If any of these
functions is called from within a phar archive with a relative path, the
call is modified to access a file within the phar archive. Absolute paths
are assumed to be attempts to load external files from the filesystem.
This function makes it possible to run PHP applications designed to run
off of a hard disk as a phar application.
Parameters
No parameters.
Return Values
Examples
Example #1 A Phar::interceptFileFuncs() example
Assuming that this phar is at /path/to/myphar.phar and it contains
file.php and file2.txt, if file.php contains this code:
Example #2 A Phar::interceptFileFuncs() example
Normally PHP would search the current directory for file2.txt, which would
translate as the directory of file.php, or the current directory of a
command-line user. Phar::interceptFileFuncs() instructs PHP to consider
the current directory to be phar:///path/to/myphar.phar/ and so opens
phar:///path/to/myphar.phar/file2.txt in the above example code.
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::isBuffering
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::isBuffering - Used to determine whether Phar write operations are
being buffered, or are flushing directly to disk
Description
bool Phar::isBuffering ( void )
This method can be used to determine whether a Phar will save changes to
disk immediately, or whether a call to Phar->stopBuffering() is needed to
enable saving changes.
Phar write buffering is per-archive, buffering active for the foo.phar
Phar archive does not affect changes to the bar.phar Phar archive.
Return Values
Returns TRUE if the write operations are being buffer, FALSE otherwise.
Examples
Example #1 A Phar::isBuffering() example
isBuffering());
var_dump($p2->isBuffering());
?>
=2=
startBuffering();
var_dump($p->isBuffering());
var_dump($p2->isBuffering());
$p->stopBuffering();
?>
=3=
isBuffering());
var_dump($p2->isBuffering());
?>
The above example will output:
bool(false)
bool(false)
=2=
bool(true)
bool(false)
=3=
bool(false)
bool(false)
See Also
* Phar::startBuffering() - Start buffering Phar write operations, do not
modify the Phar object on disk
* Phar::stopBuffering() - Stop buffering write requests to the Phar
archive, and save changes to disk
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::isCompressed
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::isCompressed - Returns Phar::GZ or PHAR::BZ2 if the entire phar
archive is compressed (.tar.gz/tar.bz and so on)
Description
mixed Phar::isCompressed ( void )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed
(.tar.gz/tar.bz and so on). Zip-based phar archives cannot be compressed
as a file, and so this method will always return FALSE if a zip-based phar
archive is queried.
Parameters
No parameters.
Return Values
Phar::GZ, Phar::BZ2 or FALSE
Examples
Example #1 A Phar::isCompressed() example
isCompressed());
$phar2 = new Phar('myuncompressed.tar.phar');
var_dump($phar2->isCompressed());
$phar2->compressAllFilesGZ();
var_dump($phar2->isCompressed() == Phar::GZ);
} catch (Exception $e) {
}
?>
The above example will output:
bool(false)
bool(false)
bool(true)
See Also
* PharFileInfo::getCompressedSize() - Returns the actual size of the
file (with compression) inside the Phar archive
* PharFileInfo::isCompressed() - Returns whether the entry is compressed
* PharFileInfo::decompress() - Decompresses the current Phar entry
within the phar
* PharFileInfo::compress() - Compresses the current Phar entry with
either zlib or bzip2 compression
* Phar::decompress() - Decompresses the entire Phar archive
* Phar::compress() - Compresses the entire Phar archive using Gzip or
Bzip2 compression
* Phar::canCompress() - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::compressFiles() - Compresses all files in the current Phar
archive
* Phar::decompressFiles() - Decompresses all files in the current Phar
archive
* Phar::getSupportedCompression() - Return array of supported
compression algorithms
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::isFileFormat
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::isFileFormat - Returns true if the phar archive is based on the
tar/phar/zip file format depending on the parameter
Description
bool Phar::isFileFormat ( int $format )
Parameters
format
Either Phar::PHAR, Phar::TAR, or Phar::ZIP to test for the format
of the archive.
Return Values
Returns TRUE if the phar archive matches the file format requested by the
parameter
Errors/Exceptions
PharException is thrown if the parameter is an unknown file format
specifier.
See Also
* Phar::convertToExecutable() - Convert a phar archive to another
executable phar archive file format
* Phar::convertToData() - Convert a phar archive to a non-executable tar
or zip file
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::isValidPharFilename
(PHP >= 5.3.0, PECL phar >= 1.2.0)
Phar::isValidPharFilename - Returns whether the given filename is a valid
phar filename
Description
bool Phar::isValidPharFilename ( string $filename [, bool $executable =
true ] )
Returns whether the given filename is a valid phar filename that will be
recognized as a phar archive by the phar extension. This can be used to
test a name without having to instantiate a phar archive and catch the
inevitable Exception that will be thrown if an invalid name is specified.
Parameters
filename
The name or full path to a phar archive not yet created
executable
This parameter determines whether the filename should be treated
as a phar executable archive, or a data non-executable archive
Return Values
Returns TRUE if the filename is valid, FALSE if not.
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::isWritable
(Unknown)
Phar::isWritable - Returns true if the phar archive can be modified
Description
bool Phar::isWritable ( void )
This method returns TRUE if phar.readonly is 0, and the actual phar
archive on disk is not read-only.
Parameters
No parameters.
Return Values
Returns TRUE if the phar archive can be modified
See Also
* Phar::canWrite() - Returns whether phar extension supports writing and
creating phars
* PharData::isWritable() - Returns true if the tar/zip archive can be
modified
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::loadPhar
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::loadPhar - Loads any phar archive with an alias
Description
bool Phar::loadPhar ( string $filename [, string $alias ] )
This can be used to read the contents of an external Phar archive. This is
most useful for assigning an alias to a phar so that subsequent references
to the phar can use the shorter alias, or for loading Phar archives that
only contain data and are not intended for execution/inclusion in PHP
scripts.
Parameters
filename
the full or relative path to the phar archive to open
alias
The alias that may be used to refer to the phar archive. Note that
many phar archives specify an explicit alias inside the phar
archive, and a PharException will be thrown if a new alias is
specified in this case.
Return Values
Returns TRUE on success or FALSE on failure.
Errors/Exceptions
PharException is thrown if an alias is passed in and the phar archive
already has an explicit alias
Examples
Example #1 A Phar::loadPhar() example
Phar::loadPhar can be used anywhere to load an external Phar archive,
whereas Phar::mapPhar should be used in a loader stub for a Phar.
See Also
* Phar::mapPhar() - Reads the currently executed file (a phar) and
registers its manifest
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::mapPhar
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::mapPhar - Reads the currently executed file (a phar) and registers
its manifest
Description
bool Phar::mapPhar ([ string $alias [, int $dataoffset = 0 ]] )
This static method can only be used inside a Phar archive's loader stub in
order to initialize the phar when it is directly executed, or when it is
included in another script.
Parameters
alias
The alias that can be used in phar:// URLs to refer to this
archive, rather than its full path.
dataoffset
Unused variable, here for compatibility with PEAR's PHP_Archive.
Return Values
Returns TRUE on success or FALSE on failure.
Errors/Exceptions
PharException is thrown if not called directly within PHP execution, if no
__HALT_COMPILER(); token is found in the current source file, or if the
file cannot be opened for reading.
Examples
Example #1 A Phar::mapPhar() example
mapPhar should be used only inside a phar's loader stub. Use loadPhar to
load an external phar into memory.
Here is a sample Phar loader stub that uses mapPhar.
getMessage();
die('Cannot initialize Phar');
}
__HALT_COMPILER();
See Also
* Phar::loadPhar() - Loads any phar archive with an alias
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::mount
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::mount - Mount an external path or file to a virtual location within
the phar archive
Description
void Phar::mount ( string $pharpath , string $externalpath )
Much like the unix file system concept of mounting external devices to
paths within the directory tree, Phar::mount() allows referring to
external files and directories as if they were inside of an archive. This
allows powerful abstraction such as referring to external configuration
files as if they were inside the archive.
Parameters
pharpath
The internal path within the phar archive to use as the mounted
path location. If executed within a phar archive, this may be a
relative path, otherwise this must be a full phar URL.
externalpath
A path or URL to an external file or directory to mount within the
phar archive
Return Values
No return. PharException is thrown on failure.
Errors/Exceptions
Throws PharException if any problems occur mounting the path.
Examples
Example #1 A Phar::mount() example
The following example shows accessing an external configuration file as if
it were a path within a phar archive.
First, the code inside of a phar archive:
Next the external code used to mount the configuration file:
Another method is to put the mounting code inside the stub of the phar
archive. Here is an example of setting up a default configuration file if
no user configuration is specified:
...and the code externally to load this phar archive:
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::mungServer
(Unknown)
Phar::mungServer - Defines a list of up to 4 $_SERVER variables that
should be modified for execution
Description
void Phar::mungServer ( array $munglist )
Phar::mungServer() should only be called within the stub of a phar
archive.
Defines a list of up to 4 $_SERVER variables that should be modified for
execution. Variables that can be modified to remove traces of phar
execution are REQUEST_URI, PHP_SELF, SCRIPT_NAME and SCRIPT_FILENAME.
On its own, this method does nothing. Only when combined with
Phar::webPhar() does it take effect, and only when the requested file is a
PHP file to be parsed. Note that the PATH_INFO and PATH_TRANSLATED
variables are always modified.
The original values of variables that are modified are stored in the
SERVER array with PHAR_ prepended, so for instance SCRIPT_NAME would be
saved as PHAR_SCRIPT_NAME.
Parameters
munglist
an array containing as string indices any of REQUEST_URI,
PHP_SELF, SCRIPT_NAME and SCRIPT_FILENAME. Other values trigger an
exception, and Phar::mungServer() is case-sensitive.
Return Values
No return.
Errors/Exceptions
Throws UnexpectedValueException if any problems are found with the passed
in data.
Examples
Example #1 A Phar::mungServer() example
See Also
* Phar::webPhar() - mapPhar for web-based phars. front controller for
web applications
* Phar::setStub() - Used to set the PHP loader or bootstrap stub of a
Phar archive
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::offsetExists
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::offsetExists - determines whether a file exists in the phar
Description
bool Phar::offsetExists ( string $offset )
This is an implementation of the ArrayAccess interface allowing direct
manipulation of the contents of a Phar archive using array access
brackets.
offsetExists() is called whenever isset() is called.
Parameters
offset
The filename (relative path) to look for in a Phar.
Return Values
Returns TRUE if the file exists within the phar, or FALSE if not.
Examples
Example #1 A Phar::offsetExists() example
The above example will output:
bool(true)
bool(false)
See Also
* Phar::offsetGet() - Gets a PharFileInfo object for a specific file
* Phar::offsetSet() - set the contents of an internal file to those of
an external file
* Phar::offsetUnset() - remove a file from a phar
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::offsetGet
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::offsetGet - Gets a PharFileInfo object for a specific file
Description
int Phar::offsetGet ( string $offset )
This is an implementation of the ArrayAccess interface allowing direct
manipulation of the contents of a Phar archive using array access
brackets. Phar::offsetGet() is used for retrieving files from a Phar
archive.
Parameters
offset
The filename (relative path) to look for in a Phar.
Return Values
A PharFileInfo object is returned that can be used to iterate over a
file's contents or to retrieve information about the current file.
Errors/Exceptions
This method throws BadMethodCallException if the file does not exist in
the Phar archive.
Examples
Example #1 Phar::offsetGet() example
As with all classes that implement the ArrayAccess interface,
Phar::offsetGet() is automatically called when using the [] angle bracket
operator.
The above example will output:
file exists
Entry doesnotexist.txt does not exist
See Also
* Phar::offsetExists() - determines whether a file exists in the phar
* Phar::offsetSet() - set the contents of an internal file to those of
an external file
* Phar::offsetUnset() - remove a file from a phar
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::offsetSet
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::offsetSet - set the contents of an internal file to those of an
external file
Description
void Phar::offsetSet ( string $offset , string $value )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
This is an implementation of the ArrayAccess interface allowing direct
manipulation of the contents of a Phar archive using array access
brackets. offsetSet is used for modifying an existing file, or adding a
new file to a Phar archive.
Parameters
offset
The filename (relative path) to modify in a Phar.
value
Content of the file.
Return Values
No return values.
Errors/Exceptions
if phar.readonly is 1, BadMethodCallException is thrown, as modifying a
Phar is only allowed when phar.readonly is set to 0. Throws PharException
if there are any problems flushing changes made to the Phar archive to
disk.
Examples
Example #1 A Phar::offsetSet() example
offsetSet should not be accessed directly, but instead used via array
access with the [] operator.
See Also
* Phar::offsetExists() - determines whether a file exists in the phar
* Phar::offsetGet() - Gets a PharFileInfo object for a specific file
* Phar::offsetUnset() - remove a file from a phar
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::offsetUnset
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::offsetUnset - remove a file from a phar
Description
bool Phar::offsetUnset ( string $offset )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
This is an implementation of the ArrayAccess interface allowing direct
manipulation of the contents of a Phar archive using array access
brackets. offsetUnset is used for deleting an existing file, and is called
by the unset() language construct.
Parameters
offset
The filename (relative path) to modify in a Phar.
Return Values
Returns TRUE on success or FALSE on failure.
Errors/Exceptions
if phar.readonly is 1, BadMethodCallException is thrown, as modifying a
Phar is only allowed when phar.readonly is set to 0. Throws PharException
if there are any problems flushing changes made to the Phar archive to
disk.
Examples
Example #1 A Phar::offsetUnset() example
See Also
* Phar::offsetExists() - determines whether a file exists in the phar
* Phar::offsetGet() - Gets a PharFileInfo object for a specific file
* Phar::offsetSet() - set the contents of an internal file to those of
an external file
* Phar::unlinkArchive() - Completely remove a phar archive from disk and
from memory
* Phar::delete() - Delete a file within a phar archive
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::running
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::running - Returns the full path on disk or full phar URL to the
currently executing Phar archive
Description
string Phar::running ([ bool $retphar = true ] )
Returns the full path to the running phar archive. This is intended for
use much like the __FILE__ magic constant, and only has effect inside an
executing phar archive.
Inside the stub of an archive, Phar::running() returns "". Simply use
__FILE__ to access the current running phar inside a stub.
Parameters
retphar
If FALSE, the full path on disk to the phar archive is returned.
If TRUE, a full phar URL is returned.
Return Values
Returns the filename if valid, empty string otherwise.
Examples
Example #1 A Phar::running() example
For the following example, assume the file is within phar archive
/path/to/phar/my.phar and the file is located at path my/file.txt within
the phar archive.
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::setAlias
(PHP >= 5.3.0, PECL phar >= 1.2.1)
Phar::setAlias - Set the alias for the Phar archive
Description
bool Phar::setAlias ( string $alias )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
Set the alias for the Phar archive, and write it as the permanent alias
for this phar archive. An alias can be used internally to a phar archive
to ensure that use of the phar stream wrapper to access internal files
always works regardless of the location of the phar archive on the
filesystem. Another alternative is to rely upon Phar's interception of
include() or to use Phar::interceptFileFuncs() and use relative paths.
Parameters
alias
A shorthand string that this archive can be referred to in phar
stream wrapper access.
Return Values
Errors/Exceptions
Throws UnexpectedValueException when write access is disabled, and
PharException if the alias is already in use or any problems were
encountered flushing changes to disk.
Examples
Example #1 A Phar::setAlias() example
setAlias('myp.phar');
} catch (Exception $e) {
// handle error
}
?>
See Also
* Phar::__construct() - Construct a Phar archive object
* Phar::interceptFileFuncs() - instructs phar to intercept fopen,
file_get_contents, opendir, and all of the stat-related functions
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::setDefaultStub
(Unknown)
Phar::setDefaultStub - Used to set the PHP loader or bootstrap stub of a
Phar archive to the default loader
Description
bool Phar::setDefaultStub ([ string $index [, string $webindex ]] )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
This method is a convenience method that combines the functionality of
Phar::createDefaultStub() and Phar::setStub().
Parameters
index
Relative path within the phar archive to run if accessed on the
command-line
webindex
Relative path within the phar archive to run if accessed through a
web browser
Return Values
Returns TRUE on success or FALSE on failure.
Errors/Exceptions
UnexpectedValueException is thrown if phar.readonly is enabled in php.ini.
PharException is thrown if any problems are encountered flushing changes
to disk.
Examples
Example #1 A Phar::setDefaultStub() example
setDefaultStub('cli.php', 'web/index.php');
// this is the same as:
// $phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
} catch (Exception $e) {
// handle errors
}
?>
See Also
* Phar::setStub() - Used to set the PHP loader or bootstrap stub of a
Phar archive
* Phar::createDefaultStub() - Create a phar-file format specific stub
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::setMetadata
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::setMetadata - Sets phar archive meta-data
Description
void Phar::setMetadata ( mixed $metadata )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
Phar::setMetadata() should be used to store customized data that describes
something about the phar archive as a complete entity.
PharFileInfo::setMetadata() should be used for file-specific meta-data.
Meta-data can slow down the performance of loading a phar archive if the
data is large.
Some possible uses for meta-data include specifying which file within the
archive should be used to bootstrap the archive, or the location of a file
manifest like >> PEAR's package.xml file. However, any useful data that
describes the phar archive may be stored.
Parameters
metadata
Any PHP variable containing information to store that describes
the phar archive
Return Values
No value is returned.
Examples
Example #1 A Phar::setMetadata() example
setMetadata(array('bootstrap' => 'file.php'));
var_dump($p->getMetadata());
} catch (Exception $e) {
echo 'Could not create and/or modify phar:', $e;
}
?>
The above example will output:
array(1) {
["bootstrap"]=>
string(8) "file.php"
}
See Also
* Phar::getMetadata() - Returns phar archive meta-data
* Phar::delMetadata() - Deletes the global metadata of the phar
* Phar::hasMetadata() - Returns whether phar has global meta-data
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::setSignatureAlgorithm
(PHP >= 5.3.0, PECL phar >= 1.1.0)
Phar::setSignatureAlgorithm - set the signature algorithm for a phar and
apply it.
Description
void Phar::setSignatureAlgorithm ( int $sigtype [, string $privatekey ] )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
set the signature algorithm for a phar and apply it. The signature
algorithm must be one of Phar::MD5, Phar::SHA1, Phar::SHA256,
Phar::SHA512, or Phar::OPENSSL.
Note that all executable phar archives have a signature created
automatically, SHA1 by default. data tar- or zip-based archives (archives
created with the PharData class) must have their signature created and set
explicitly via Phar::setSignatureAlgorithm().
Parameters
sigtype
One of Phar::MD5, Phar::SHA1, Phar::SHA256, Phar::SHA512, or
Phar::OPENSSL
privatekey
The contents of an OpenSSL private key, as extracted from a
certificate or OpenSSL key file:
setSignatureAlgorithm(Phar::OPENSSL, $pkey);
?>
See phar introduction for instructions on naming and placement of
the public key file.
Return Values
No value is returned.
Errors/Exceptions
Throws UnexpectedValueException for many errors, and a PharException if
any problems occur flushing changes to disk.
See Also
* Phar::getSupportedSignatures() - Return array of supported signature
types
* Phar::getSignature() - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature
of a Phar archive
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::setStub
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::setStub - Used to set the PHP loader or bootstrap stub of a Phar
archive
Description
bool Phar::setStub ( string $stub )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
This method is used to add a PHP bootstrap loader stub to a new Phar
archive, or to replace the loader stub in an existing Phar archive.
The loader stub for a Phar archive is used whenever an archive is included
directly as in this example:
The loader is not accessed when including a file through the phar stream
wrapper like so:
Parameters
stub
A string or an open stream handle to use as the executable stub
for this phar archive.
Return Values
Returns TRUE on success or FALSE on failure.
Errors/Exceptions
UnexpectedValueException is thrown if phar.readonly is enabled in php.ini.
PharException is thrown if any problems are encountered flushing changes
to disk.
Examples
Example #1 A Phar::setStub() example
setStub('');
include 'phar://brandnewphar.phar/a.php';
var_dump($p->getStub());
$p['b.php'] = 'setStub('');
include 'phar://brandnewphar.phar/b.php';
var_dump($p->getStub());
} catch (Exception $e) {
echo 'Write operations failed on brandnewphar.phar: ', $e;
}
?>
The above example will output:
string(5) "Hello"
string(82) ""
string(5) "World"
string(83) ""
See Also
* Phar::getStub() - Return the PHP loader or bootstrap stub of a Phar
archive
* Phar::createDefaultStub() - Create a phar-file format specific stub
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::startBuffering
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::startBuffering - Start buffering Phar write operations, do not
modify the Phar object on disk
Description
void Phar::startBuffering ( void )
Although technically unnecessary, the Phar::startBuffering() method can
provide a significant performance boost when creating or modifying a Phar
archive with a large number of files. Ordinarily, every time a file within
a Phar archive is created or modified in any way, the entire Phar archive
will be recreated with the changes. In this way, the archive will be
up-to-date with the activity performed on it.
However, this can be unnecessary when simply creating a new Phar archive,
when it would make more sense to write the entire archive out at once.
Similarly, it is often necessary to make a series of changes and to ensure
that they all are possible before making any changes on disk, similar to
the relational database concept of transactions. the
Phar::startBuffering()/Phar::stopBuffering() pair of methods is provided
for this purpose.
Phar write buffering is per-archive, buffering active for the foo.phar
Phar archive does not affect changes to the bar.phar Phar archive.
Return Values
No value is returned.
Examples
Example #1 A Phar::startBuffering() example
count() . " entries\n";
$p->startBuffering();
$p['file.txt'] = 'hi';
$p['file2.txt'] = 'there';
$p['file2.txt']->setCompressedGZ();
$p['file3.txt'] = 'babyface';
$p['file3.txt']->setMetaData(42);
$p->setStub("stopBuffering();
?>
See Also
* Phar::stopBuffering() - Stop buffering write requests to the Phar
archive, and save changes to disk
* Phar::isBuffering() - Used to determine whether Phar write operations
are being buffered, or are flushing directly to disk
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::stopBuffering
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::stopBuffering - Stop buffering write requests to the Phar archive,
and save changes to disk
Description
void Phar::stopBuffering ( void )
Phar::stopBuffering() is used in conjunction with the
Phar::startBuffering() method. Phar::startBuffering() can provide a
significant performance boost when creating or modifying a Phar archive
with a large number of files. Ordinarily, every time a file within a Phar
archive is created or modified in any way, the entire Phar archive will be
recreated with the changes. In this way, the archive will be up-to-date
with the activity performed on it.
However, this can be unnecessary when simply creating a new Phar archive,
when it would make more sense to write the entire archive out at once.
Similarly, it is often necessary to make a series of changes and to ensure
that they all are possible before making any changes on disk, similar to
the relational database concept of transactions. The
Phar::startBuffering()/Phar::stopBuffering() pair of methods is provided
for this purpose.
Phar write buffering is per-archive, buffering active for the foo.phar
Phar archive does not affect changes to the bar.phar Phar archive.
Return Values
No value is returned.
Errors/Exceptions
PharException is thrown if any problems are encountered flushing changes
to disk.
Examples
Example #1 A Phar::stopBuffering() example
startBuffering();
var_dump($p->getStub());
$p->setStub("stopBuffering();
var_dump($p->getStub());
?>
The above example will output:
string(24) "compressAllFilesGZ();
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressedBZIP2());
var_dump($file->isCompressedGZ());
}
$p->uncompressAllFiles();
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressedBZIP2());
var_dump($file->isCompressedGZ());
}
} catch (Exception $e) {
echo 'Write operations failed on my.phar: ', $e;
}
?>
The above example will output:
string(10) "myfile.txt"
bool(true)
bool(false)
bool(true)
string(11) "myfile2.txt"
bool(true)
bool(false)
bool(true)
string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
See Also
* PharFileInfo::getCompressedSize() - Returns the actual size of the
file (with compression) inside the Phar archive
* PharFileInfo::isCompressedBZIP2() - Returns whether the entry is
compressed using bzip2
* PharFileInfo::isCompressed() - Returns whether the entry is compressed
* PharFileInfo::isCompressedGZ() - Returns whether the entry is
compressed using gz
* PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry
within the phar using Bzip2 compression
* PharFileInfo::setUncompressed() - Uncompresses the current Phar entry
within the phar, if it is compressed
* PharFileInfo::setCompressedGZ() - Compresses the current Phar entry
within the phar using gz compression
* Phar::canCompress() - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire
phar archive is compressed (.tar.gz/tar.bz and so on)
* Phar::compressAllFilesBZIP2() - Compresses all files in the current
Phar archive using Bzip2 compression
* Phar::compressAllFilesGZ() - Compresses all files in the current Phar
archive using Gzip compression
* Phar::getSupportedCompression() - Return array of supported
compression algorithms
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::unlinkArchive
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::unlinkArchive - Completely remove a phar archive from disk and from
memory
Description
bool Phar::unlinkArchive ( string $archive )
Removes a phar archive for disk and memory.
Parameters
archive
The path on disk to the phar archive.
Return Values
Returns TRUE on success or FALSE on failure.
Errors/Exceptions
PharException is thrown if there are any open file pointers to the phar
archive, or any existing Phar, PharData, or PharFileInfo objects referring
to the phar archive.
Examples
Example #1 A Phar::unlinkArchive() example
compress(Phar::GZ);
// remove all references to the archive
unset($p);
fclose($fp);
// now remove all traces of the archive
Phar::unlinkArchive('my.phar');
?>
See Also
* Phar::delete() - Delete a file within a phar archive
* Phar::offsetUnset() - remove a file from a phar
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::webPhar
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::webPhar - mapPhar for web-based phars. front controller for web
applications
Description
void Phar::webPhar ([ string $alias [, string $index = "index.php" [,
string $f404 [, array $mimetypes [, array $rewrites ]]]]] )
Phar::mapPhar() for web-based phars. This method parses
$_SERVER['REQUEST_URI'] and routes a request from a web browser to an
internal file within the phar archive. In essence, it simulates a web
server, routing requests to the correct file, echoing the correct headers
and parsing PHP files as needed. This powerful method is part of what
makes it easy to convert an existing PHP application into a phar archive.
Combined with Phar::mungServer() and Phar::interceptFileFuncs(), any web
application can be used unmodified from a phar archive.
Phar::webPhar() should only be called from the stub of a phar archive (see
here for more information on what a stub is).
Parameters
alias
The alias that can be used in phar:// URLs to refer to this
archive, rather than its full path.
index
The location within the phar of the directory index.
f404
The location of the script to run when a file is not found. This
script should output the proper HTTP 404 headers.
mimetypes
An array mapping additional file extensions to MIME type. By
default, these extensions are mapped to these mime types:
2, // pass to highlight_file()
'c' => 'text/plain',
'cc' => 'text/plain',
'cpp' => 'text/plain',
'c++' => 'text/plain',
'dtd' => 'text/plain',
'h' => 'text/plain',
'log' => 'text/plain',
'rng' => 'text/plain',
'txt' => 'text/plain',
'xsd' => 'text/plain',
'php' => 1, // parse as PHP
'inc' => 1, // parse as PHP
'avi' => 'video/avi',
'bmp' => 'image/bmp',
'css' => 'text/css',
'gif' => 'image/gif',
'htm' => 'text/html',
'html' => 'text/html',
'htmls' => 'text/html',
'ico' => 'image/x-ico',
'jpe' => 'image/jpeg',
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'js' => 'application/x-javascript',
'midi' => 'audio/midi',
'mid' => 'audio/midi',
'mod' => 'audio/mod',
'mov' => 'movie/quicktime',
'mp3' => 'audio/mp3',
'mpg' => 'video/mpeg',
'mpeg' => 'video/mpeg',
'pdf' => 'application/pdf',
'png' => 'image/png',
'swf' => 'application/shockwave-flash',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'wav' => 'audio/wav',
'xbm' => 'image/xbm',
'xml' => 'text/xml',
);
?>
rewrites
An array mapping URI to internal file, simulating mod_rewrite of
apache. For example:
'myinfo.php'
);
?>
would route calls to http:///myphar.phar/myinfo to the file
phar:///path/to/myphar.phar/myinfo.php, preserving GET/POST. This
does not quite work like mod_rewrite in that it would not match
http:///myphar.phar/myinfo/another.
Return Values
No value is returned.
Errors/Exceptions
Throws PharException when unable to open the internal file to output, or
if called from a non-stub. If an invalid array value is passed into
mimetypes or to rewrites, then UnexpectedValueException is thrown.
Examples
Example #1 A Phar::webPhar() example
With the example below, the created phar will display Hello World if one
browses to /myphar.phar/index.php or to /myphar.phar, and will display the
source of index.phps if one browses to /myphar.phar/index.phps.
';
$phar['index.phps'] = '';
$phar->setStub('');
} catch (Exception $e) {
// handle error here
}
?>
See Also
* Phar::mungServer() - Defines a list of up to 4 $_SERVER variables that
should be modified for execution
* Phar::interceptFileFuncs() - instructs phar to intercept fopen,
file_get_contents, opendir, and all of the stat-related functions
----------------------------------------------------------------------
Table of Contents
* Phar::addEmptyDir - Add an empty directory to the phar archive
* Phar::addFile - Add a file from the filesystem to the phar archive
* Phar::addFromString - Add a file from the filesystem to the phar
archive
* Phar::apiVersion - Returns the api version
* Phar::buildFromDirectory - Construct a phar archive from the files
within a directory.
* Phar::buildFromIterator - Construct a phar archive from an iterator.
* Phar::canCompress - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::canWrite - Returns whether phar extension supports writing and
creating phars
* Phar::compress - Compresses the entire Phar archive using Gzip or
Bzip2 compression
* Phar::compressAllFilesBZIP2 - Compresses all files in the current Phar
archive using Bzip2 compression
* Phar::compressAllFilesGZ - Compresses all files in the current Phar
archive using Gzip compression
* Phar::compressFiles - Compresses all files in the current Phar archive
* Phar::__construct - Construct a Phar archive object
* Phar::convertToData - Convert a phar archive to a non-executable tar
or zip file
* Phar::convertToExecutable - Convert a phar archive to another
executable phar archive file format
* Phar::copy - Copy a file internal to the phar archive to another new
file within the phar
* Phar::count - Returns the number of entries (files) in the Phar
archive
* Phar::createDefaultStub - Create a phar-file format specific stub
* Phar::decompress - Decompresses the entire Phar archive
* Phar::decompressFiles - Decompresses all files in the current Phar
archive
* Phar::delMetadata - Deletes the global metadata of the phar
* Phar::delete - Delete a file within a phar archive
* Phar::extractTo - Extract the contents of a phar archive to a
directory
* Phar::getMetaData - Returns phar archive meta-data
* Phar::getModified - Return whether phar was modified
* Phar::getSignature - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature
of a Phar archive
* Phar::getStub - Return the PHP loader or bootstrap stub of a Phar
archive
* Phar::getSupportedCompression - Return array of supported compression
algorithms
* Phar::getSupportedSignatures - Return array of supported signature
types
* Phar::getVersion - Return version info of Phar archive
* Phar::hasMetaData - Returns whether phar has global meta-data
* Phar::interceptFileFuncs - instructs phar to intercept fopen,
file_get_contents, opendir, and all of the stat-related functions
* Phar::isBuffering - Used to determine whether Phar write operations
are being buffered, or are flushing directly to disk
* Phar::isCompressed - Returns Phar::GZ or PHAR::BZ2 if the entire phar
archive is compressed (.tar.gz/tar.bz and so on)
* Phar::isFileFormat - Returns true if the phar archive is based on the
tar/phar/zip file format depending on the parameter
* Phar::isValidPharFilename - Returns whether the given filename is a
valid phar filename
* Phar::isWritable - Returns true if the phar archive can be modified
* Phar::loadPhar - Loads any phar archive with an alias
* Phar::mapPhar - Reads the currently executed file (a phar) and
registers its manifest
* Phar::mount - Mount an external path or file to a virtual location
within the phar archive
* Phar::mungServer - Defines a list of up to 4 $_SERVER variables that
should be modified for execution
* Phar::offsetExists - determines whether a file exists in the phar
* Phar::offsetGet - Gets a PharFileInfo object for a specific file
* Phar::offsetSet - set the contents of an internal file to those of an
external file
* Phar::offsetUnset - remove a file from a phar
* Phar::running - Returns the full path on disk or full phar URL to the
currently executing Phar archive
* Phar::setAlias - Set the alias for the Phar archive
* Phar::setDefaultStub - Used to set the PHP loader or bootstrap stub of
a Phar archive to the default loader
* Phar::setMetadata - Sets phar archive meta-data
* Phar::setSignatureAlgorithm - set the signature algorithm for a phar
and apply it.
* Phar::setStub - Used to set the PHP loader or bootstrap stub of a Phar
archive
* Phar::startBuffering - Start buffering Phar write operations, do not
modify the Phar object on disk
* Phar::stopBuffering - Stop buffering write requests to the Phar
archive, and save changes to disk
* Phar::uncompressAllFiles - Uncompresses all files in the current Phar
archive
* Phar::unlinkArchive - Completely remove a phar archive from disk and
from memory
* Phar::webPhar - mapPhar for web-based phars. front controller for web
applications
----------------------------------------------------------------------
----------------------------------------------------------------------
The PharData class
Introduction
The PharData class provides a high-level interface to accessing and
creating non-executable tar and zip archives. Because these archives do
not contain a stub and cannot be executed by the phar extension, it is
possible to create and manipulate regular zip and tar files using the
PharData class even if phar.readonly php.ini setting is 1.
Class synopsis
PharData extends Phar {
/* Properties */
/* Methods */
bool addEmptyDir ( string $dirname )
void Phar::addFile ( string $file [, string $localname ] )
bool addFromString ( string $localname , string $contents )
array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )
array buildFromIterator ( Iterator $iter [, string $base_directory ] )
object compress ( int $compression [, string $extension ] )
bool compressFiles ( int $compression )
void __construct ( string $fname [, int $flags [, string $alias [, int
$format = Phar::TAR ]]] )
PharData convertToData ([ int $format [, int $compression [, string
$extension ]]] )
Phar convertToExecutable ([ int $format [, int $compression [, string
$extension ]]] )
bool copy ( string $oldfile , string $newfile )
object decompress ([ string $extension ] )
bool decompressFiles ( void )
bool delMetadata ( void )
bool delete ( string $entry )
bool extractTo ( string $pathto [, string|array $files [, bool $overwrite
= false ]] )
bool isWritable ( void )
void offsetSet ( string $offset , string $value )
bool offsetUnset ( string $offset )
bool setAlias ( string $alias )
bool setDefaultStub ([ string $index [, string $webindex ]] )
void Phar::setMetadata ( mixed $metadata )
void Phar::setSignatureAlgorithm ( int $sigtype )
bool setStub ( string $stub )
/* Inherited methods */
void Phar::addEmptyDir ( string $dirname )
void Phar::addFile ( string $file [, string $localname ] )
void Phar::addFromString ( string $localname , string $contents )
string Phar::apiVersion ( void )
array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )
array Phar::buildFromIterator ( Iterator $iter [, string $base_directory ]
)
bool Phar::canCompress ([ int $type = 0 ] )
bool Phar::canWrite ( void )
object Phar::compress ( int $compression [, string $extension ] )
bool Phar::compressAllFilesBZIP2 ( void )
bool Phar::compressAllFilesGZ ( void )
void Phar::compressFiles ( int $compression )
void Phar::__construct ( string $fname [, int $flags [, string $alias ]] )
PharData Phar::convertToData ([ int $format = 9021976 [, int $compression
= 9021976 [, string $extension ]]] )
Phar Phar::convertToExecutable ([ int $format = 9021976 [, int
$compression = 9021976 [, string $extension ]]] )
bool Phar::copy ( string $oldfile , string $newfile )
int Phar::count ( void )
string Phar::createDefaultStub ([ string $indexfile [, string
$webindexfile ]] )
object Phar::decompress ([ string $extension ] )
bool Phar::decompressFiles ( void )
bool Phar::delMetadata ( void )
bool Phar::delete ( string $entry )
bool Phar::extractTo ( string $pathto [, string|array $files [, bool
$overwrite = false ]] )
mixed Phar::getMetaData ( void )
bool Phar::getModified ( void )
array Phar::getSignature ( void )
string Phar::getStub ( void )
array Phar::getSupportedCompression ( void )
array Phar::getSupportedSignatures ( void )
string Phar::getVersion ( void )
bool Phar::hasMetadata ( void )
void Phar::interceptFileFuncs ( void )
bool Phar::isBuffering ( void )
mixed Phar::isCompressed ( void )
bool Phar::isFileFormat ( int $format )
bool Phar::isValidPharFilename ( string $filename [, bool $executable =
true ] )
bool Phar::isWritable ( void )
bool Phar::loadPhar ( string $filename [, string $alias ] )
bool Phar::mapPhar ([ string $alias [, int $dataoffset = 0 ]] )
void Phar::mount ( string $pharpath , string $externalpath )
void Phar::mungServer ( array $munglist )
bool Phar::offsetExists ( string $offset )
int Phar::offsetGet ( string $offset )
void Phar::offsetSet ( string $offset , string $value )
bool Phar::offsetUnset ( string $offset )
string Phar::running ([ bool $retphar = true ] )
bool Phar::setAlias ( string $alias )
bool Phar::setDefaultStub ([ string $index [, string $webindex ]] )
void Phar::setMetadata ( mixed $metadata )
void Phar::setSignatureAlgorithm ( int $sigtype [, string $privatekey ] )
bool Phar::setStub ( string $stub )
void Phar::startBuffering ( void )
void Phar::stopBuffering ( void )
bool Phar::uncompressAllFiles ( void )
bool Phar::unlinkArchive ( string $archive )
void Phar::webPhar ([ string $alias [, string $index = "index.php" [,
string $f404 [, array $mimetypes [, array $rewrites ]]]]] )
}
----------------------------------------------------------------------
PharData::addEmptyDir
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharData::addEmptyDir - Add an empty directory to the tar/zip archive
Description
bool PharData::addEmptyDir ( string $dirname )
With this method, an empty directory is created with path dirname. This
method is similar to ZipArchive::addEmptyDir().
Parameters
dirname
The name of the empty directory to create in the phar archive
Return Values
no return value, exception is thrown on failure.
Examples
Example #1 A PharData::addEmptyDir() example
addEmptyDir('/full/path/to/file');
// demonstrates how this file is stored
$b = $a['full/path/to/file']->isDir();
} catch (Exception $e) {
// handle errors here
}
?>
See Also
* Phar::addEmptyDir() - Add an empty directory to the phar archive
* PharData::addFile() - Add a file from the filesystem to the tar/zip
archive
* PharData::addFromString() - Add a file from the filesystem to the
tar/zip archive
----------------------------------------------------------------------
----------------------------------------------------------------------
PharData::addFile
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharData::addFile - Add a file from the filesystem to the tar/zip archive
Description
void Phar::addFile ( string $file [, string $localname ] )
With this method, any file or URL can be added to the tar/zip archive. If
the optional second parameter localname is specified, the file will be
stored in the archive with that name, otherwise the file parameter is used
as the path to store within the archive. URLs must have a localname or an
exception is thrown. This method is similar to ZipArchive::addFile().
Parameters
file
Full or relative path to a file on disk to be added to the phar
archive.
localname
Path that the file will be stored in the archive.
Return Values
no return value, exception is thrown on failure.
Examples
Example #1 A PharData::addFile() example
addFile('/full/path/to/file');
// demonstrates how this file is stored
$b = $a['full/path/to/file']->getContent();
$a->addFile('/full/path/to/file', 'my/file.txt');
$c = $a['my/file.txt']->getContent();
// demonstrate URL usage
$a->addFile('http://www.example.com', 'example.html');
} catch (Exception $e) {
// handle errors here
}
?>
See Also
* PharData::offsetSet() - set the contents of a file within the tar/zip
to those of an external file or string
* Phar::addFile() - Add a file from the filesystem to the phar archive
* PharData::addFromString() - Add a file from the filesystem to the
tar/zip archive
* PharData::addEmptyDir() - Add an empty directory to the tar/zip
archive
----------------------------------------------------------------------
----------------------------------------------------------------------
PharData::addFromString
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharData::addFromString - Add a file from the filesystem to the tar/zip
archive
Description
bool PharData::addFromString ( string $localname , string $contents )
With this method, any string can be added to the tar/zip archive. The file
will be stored in the archive with localname as its path. This method is
similar to ZipArchive::addFromString().
Parameters
localname
Path that the file will be stored in the archive.
contents
The file contents to store
Return Values
no return value, exception is thrown on failure.
Examples
Example #1 A PharData::addFromString() example
addFromString('path/to/file.txt', 'my simple file');
$b = $a['path/to/file.txt']->getContent();
// to add contents from a stream handle for large files, use offsetSet()
$c = fopen('/path/to/hugefile.bin');
$a['largefile.bin'] = $c;
fclose($c);
} catch (Exception $e) {
// handle errors here
}
?>
See Also
* PharData::offsetSet() - set the contents of a file within the tar/zip
to those of an external file or string
* Phar::addFromString() - Add a file from the filesystem to the phar
archive
* PharData::addFile() - Add a file from the filesystem to the tar/zip
archive
* PharData::addEmptyDir() - Add an empty directory to the tar/zip
archive
----------------------------------------------------------------------
----------------------------------------------------------------------
PharData::buildFromDirectory
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharData::buildFromDirectory - Construct a tar/zip archive from the files
within a directory.
Description
array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )
Populate a tar/zip archive from directory contents. The optional second
parameter is a regular expression (pcre) that is used to exclude files.
Any filename that matches the regular expression will be included, all
others will be excluded. For more fine-grained control, use
PharData::buildFromIterator().
Parameters
base_dir
The full or relative path to the directory that contains all files
to add to the archive.
regex
An optional pcre regular expression that is used to filter the
list of files. Only file paths matching the regular expression
will be included in the archive.
Return Values
Phar::buildFromDirectory() returns an associative array mapping internal
path of file to the full path of the file on the filesystem.
Errors/Exceptions
This method throws BadMethodCallException when unable to instantiate the
internal directory iterators, or a PharException if there were errors
saving the phar archive.
Examples
Example #1 A PharData::buildFromDirectory() example
buildFromDirectory(dirname(__FILE__) . '/project');
$phar2 = new PharData('project2.zip');
// add all files in the project, only include php files
$phar->buildFromDirectory(dirname(__FILE__) . '/project', '/\.php$/');
?>
See Also
* Phar::buildFromDirectory() - Construct a phar archive from the files
within a directory.
* PharData::buildFromIterator() - Construct a tar or zip archive from an
iterator.
----------------------------------------------------------------------
----------------------------------------------------------------------
PharData::buildFromIterator
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharData::buildFromIterator - Construct a tar or zip archive from an
iterator.
Description
array PharData::buildFromIterator ( Iterator $iter [, string
$base_directory ] )
Populate a tar or zip archive from an iterator. Two styles of iterators
are supported, iterators that map the filename within the tar/zip to the
name of a file on disk, and iterators like DirectoryIterator that return
SplFileInfo objects. For iterators that return SplFileInfo objects, the
second parameter is required.
Examples
Example #1 A PharData::buildFromIterator() with SplFileInfo
For most tar/zip archives, the archive will reflect an actual directory
layout, and the second style is the most useful. For instance, to create a
tar/zip archive containing the files in this sample directory layout:
/path/to/project/
config/
dist.xml
debug.xml
lib/
file1.php
file2.php
src/
processthing.php
www/
index.php
cli/
index.php
This code could be used to add these files to the "project.tar" tar
archive:
buildFromIterator(
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/path/to/project')),
'/path/to/project');
?>
The file project.tar can then be used immediately.
PharData::buildFromIterator() does not set values such as compression,
metadata, and this can be done after creating the tar/zip archive.
As an interesting note, PharData::buildFromIterator() can also be used to
copy the contents of an existing phar, tar or zip archive, as the PharData
object descends from DirectoryIterator:
buildFromIterator(
new RecursiveIteratorIterator(
new Phar('/path/to/anotherphar.phar')),
'phar:///path/to/anotherphar.phar/path/to/project');
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>
Example #2 A PharData::buildFromIterator() with other iterators
The second form of the iterator can be used with any iterator that returns
a key => value mapping, such as an ArrayIterator:
buildFromIterator(
new ArrayIterator(
array(
'internal/file.php' => dirname(__FILE__) . '/somefile.php',
'another/file.jpg' => fopen('/path/to/bigfile.jpg', 'rb'),
)));
?>
Parameters
iter
Any iterator that either associatively maps tar/zip file to
location or returns SplFileInfo objects
base_directory
For iterators that return SplFileInfo objects, the portion of each
file's full path to remove when adding to the tar/zip archive
Return Values
PharData::buildFromIterator() returns an associative array mapping
internal path of file to the full path of the file on the filesystem.
Errors/Exceptions
This method returns UnexpectedValueException when the iterator returns
incorrect values, such as an integer key instead of a string, a
BadMethodCallException when an SplFileInfo-based iterator is passed
without a base_directory parameter, or a PharException if there were
errors saving the phar archive.
See Also
* Phar::buildFromIterator() - Construct a phar archive from an iterator.
----------------------------------------------------------------------
----------------------------------------------------------------------
PharData::compress
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharData::compress - Compresses the entire tar/zip archive using Gzip or
Bzip2 compression
Description
object PharData::compress ( int $compression [, string $extension ] )
For tar archives, this method compresses the entire archive using gzip
compression or bzip2 compression. The resulting file can be processed with
the gunzip command/bunzip command, or accessed directly and transparently
with the Phar extension.
For zip archives, this method fails with an exception. The zlib extension
must be enabled to compress with gzip compression, the bzip2 extension
must be enabled in order to compress with bzip2 compression.
In addition, this method automatically renames the archive, appending .gz,
.bz2 or removing the extension if passed Phar::NONE to remove compression.
Alternatively, a file extension may be specified with the second
parameter.
Parameters
compression
Compression must be one of Phar::GZ, Phar::BZ2 to add compression,
or Phar::NONE to remove compression.
extension
By default, the extension is .tar.gz or .tar.bz2 for compressing a
tar, and .tar for decompressing.
Return Values
A PharData object is returned.
Errors/Exceptions
Throws BadMethodCallException if the zlib extension is not available, or
the bzip2 extension is not enabled.
Examples
Example #1 A PharData::compress() example
compress(Phar::GZ); // copies to /path/to/my.phar.gz
$p2 = $p->compress(Phar::BZ2); // copies to /path/to/my.phar.bz2
$p3 = $p2->compress(Phar::NONE); // exception: /path/to/my.phar already exists
?>
See Also
* Phar::compress() - Compresses the entire Phar archive using Gzip or
Bzip2 compression
----------------------------------------------------------------------
----------------------------------------------------------------------
PharData::compressFiles
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharData::compressFiles - Compresses all files in the current tar/zip
archive
Description
bool PharData::compressFiles ( int $compression )
For tar-based archives, this method throws a BadMethodCallException, as
compression of individual files within a tar archive is not supported by
the file format. Use PharData::compress() to compress an entire tar-based
archive.
For Zip-based archives, this method compresses all files in the archive
using the specified compression. The zlib or bzip2 extensions must be
enabled to take advantage of this feature. In addition, if any files are
already compressed using bzip2/zlib compression, the respective extension
must be enabled in order to decompress the files prior to re-compressing.
Parameters
compression
Compression must be one of Phar::GZ, Phar::BZ2 to add compression,
or Phar::NONE to remove compression.
Return Values
Returns TRUE on success or FALSE on failure.
Errors/Exceptions
Throws BadMethodCallException if the phar.readonly INI variable is on, the
zlib extension is not available, or if any files are compressed using
bzip2 compression and the bzip2 extension is not enabled.
Examples
Example #1 A PharData::compressFiles() example
getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressed(Phar::BZ2));
var_dump($file->isCompressed(Phar::GZ));
}
$p->compressFiles(Phar::GZ);
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressed(Phar::BZ2));
var_dump($file->isCompressed(Phar::GZ));
}
?>
The above example will output:
string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
string(10) "myfile.txt"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)
See Also
* PharFileInfo::getCompressedSize() - Returns the actual size of the
file (with compression) inside the Phar archive
* PharFileInfo::isCompressed() - Returns whether the entry is compressed
* PharFileInfo::compress() - Compresses the current Phar entry with
either zlib or bzip2 compression
* PharFileInfo::decompress() - Decompresses the current Phar entry
within the phar
* Phar::canCompress() - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire
phar archive is compressed (.tar.gz/tar.bz and so on)
* PharData::decompressFiles() - Decompresses all files in the current
zip archive
* Phar::getSupportedCompression() - Return array of supported
compression algorithms
* PharData::compress() - Compresses the entire tar/zip archive using
Gzip or Bzip2 compression
* PharData::decompress() - Decompresses the entire Phar archive
----------------------------------------------------------------------
----------------------------------------------------------------------
PharData::__construct
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharData::__construct - Construct a non-executable tar or zip archive
object
Description
void PharData::__construct ( string $fname [, int $flags [, string $alias
[, int $format = Phar::TAR ]]] )
Parameters
fname
Path to an existing tar/zip archive or to-be-created archive
flags
Flags to pass to Phar parent class RecursiveDirectoryIterator.
alias
Alias with which this Phar archive should be referred to in calls
to stream functionality.
format
One of the file format constants available within the Phar class.
Errors/Exceptions
Throws BadMethodCallException if called twice; UnexpectedValueException if
the Phar archive can't be opened.
Examples
Example #1 A PharData::__construct() example
----------------------------------------------------------------------
----------------------------------------------------------------------
PharData::convertToData
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharData::convertToData - Convert a phar archive to a non-executable tar
or zip file
Description
PharData PharData::convertToData ([ int $format [, int $compression [,
string $extension ]]] )
This method is used to convert a non-executable tar or zip archive to
another non-executable format.
If no changes are specified, this method throws a BadMethodCallException.
This method should be used to convert a tar archive to zip format or
vice-versa. Although it is possible to simply change the compression of a
tar archive using this method, it is better to use the
PharData::compress() method for logical consistency.
If successful, the method creates a new archive on disk and returns a
PharData object. The old archive is not removed from disk, and should be
done manually after the process has finished.
Parameters
format
This should be one of Phar::TAR or Phar::ZIP. If set to NULL, the
existing file format will be preserved.
compression
This should be one of Phar::NONE for no whole-archive compression,
Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based
compression.
extension
This parameter is used to override the default file extension for
a converted archive. Note that .phar cannot be used anywhere in
the filename for a non-executable tar or zip archive.
If converting to a tar-based phar archive, the default extensions
are .tar, .tar.gz, and .tar.bz2 depending on specified
compression. For zip-based archives, the default extension is
.zip.
Return Values
The method returns a PharData object on success and throws an exception on
failure.
Errors/Exceptions
This method throws BadMethodCallException when unable to compress, an
unknown compression method has been specified, the requested archive is
buffering with Phar::startBuffering() and has not concluded with
Phar::stopBuffering(), and a PharException if any problems are encountered
during the phar creation process.
Examples
Example #1 A PharData::convertToData() example
Using PharData::convertToData():
convertToData(Phar::ZIP);
// create myphar.tbz
$tgz = $zip->convertToData(Phar::TAR, Phar::BZ2, '.tbz');
// creates myphar.phar.tgz
$phar = $tarphar->convertToData(Phar::PHAR); // throws exception
} catch (Exception $e) {
// handle the error here
}
?>
See Also
* Phar::convertToExecutable() - Convert a phar archive to another
executable phar archive file format
* Phar::convertToData() - Convert a phar archive to a non-executable tar
or zip file
* PharData::convertToExecutable() - Convert a non-executable tar/zip
archive to an executable phar archive
----------------------------------------------------------------------
----------------------------------------------------------------------
PharData::convertToExecutable
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharData::convertToExecutable - Convert a non-executable tar/zip archive
to an executable phar archive
Description
Phar PharData::convertToExecutable ([ int $format [, int $compression [,
string $extension ]]] )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
This method is used to convert a non-executable tar or zip archive to an
executable phar archive. Any of the three executable file formats (phar,
tar or zip) can be used, and whole-archive compression can also be
performed.
If no changes are specified, this method throws a BadMethodCallException.
If successful, the method creates a new archive on disk and returns a Phar
object. The old archive is not removed from disk, and should be done
manually after the process has finished.
Parameters
format
This should be one of Phar::PHAR, Phar::TAR, or Phar::ZIP. If set
to NULL, the existing file format will be preserved.
compression
This should be one of Phar::NONE for no whole-archive compression,
Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based
compression.
extension
This parameter is used to override the default file extension for
a converted archive. Note that all zip- and tar-based phar
archives must contain .phar in their file extension in order to be
processed as a phar archive.
If converting to a phar-based archive, the default extensions are
.phar, .phar.gz, or .phar.bz2 depending on the specified
compression. For tar-based phar archives, the default extensions
are .phar.tar, .phar.tar.gz, and .phar.tar.bz2. For zip-based phar
archives, the default extension is .phar.zip.
Return Values
The method returns a Phar object on success and throws an exception on
failure.
Errors/Exceptions
This method throws BadMethodCallException when unable to compress, an
unknown compression method has been specified, the requested archive is
buffering with Phar::startBuffering() and has not concluded with
Phar::stopBuffering(), an UnexpectedValueException if write support is
disabled, and a PharException if any problems are encountered during the
phar creation process.
Examples
Example #1 A PharData::convertToExecutable() example
Using PharData::convertToExecutable():
convertToExecutable(Phar::PHAR); // creates myphar.phar
$phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
// creates myphar.phar.tgz
$compressed = $tarphar->convertToExecutable(Phar::TAR, Phar::GZ, '.phar.tgz');
} catch (Exception $e) {
// handle the error here
}
?>
See Also
* Phar::convertToExecutable() - Convert a phar archive to another
executable phar archive file format
* Phar::convertToData() - Convert a phar archive to a non-executable tar
or zip file
* PharData::convertToData() - Convert a phar archive to a non-executable
tar or zip file
----------------------------------------------------------------------
----------------------------------------------------------------------
PharData::copy
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharData::copy - Copy a file internal to the phar archive to another new
file within the phar
Description
bool PharData::copy ( string $oldfile , string $newfile )
Copy a file internal to the tar/zip archive to another new file within the
same archive. This is an object-oriented alternative to using copy() with
the phar stream wrapper.
Parameters
oldfile
newfile
Return Values
returns TRUE on success, but it is safer to encase method call in a
try/catch block and assume success if no exception is thrown.
Errors/Exceptions
throws UnexpectedValueException if the source file does not exist, the
destination file already exists, write access is disabled, opening either
file fails, reading the source file fails, or a PharException if writing
the changes to the phar fails.
Examples
Example #1 A PharData::copy() example
This example shows using PharData::copy() and the equivalent stream
wrapper performance of the same thing. The primary difference between the
two approaches is error handling. All PharData methods throw exceptions,
whereas the stream wrapper uses trigger_error().
copy('a', 'b');
echo $phar['b']; // outputs "phar://myphar.tar/b"
} catch (Exception $e) {
// handle error
}
// the stream wrapper equivalent of the above code.
// E_WARNINGS are triggered on error rather than exceptions.
copy('phar://myphar.tar/a', 'phar//myphar.tar/c');
echo file_get_contents('phar://myphar.tar/c'); // outputs "hi"
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
PharData::decompress
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharData::decompress - Decompresses the entire Phar archive
Description
object PharData::decompress ([ string $extension ] )
For tar-based archives, this method decompresses the entire archive.
For Zip-based archives, this method fails with an exception. The zlib
extension must be enabled to decompress an archive compressed with gzip
compression, and the bzip2 extension must be enabled in order to
decompress an archive compressed with bzip2 compression.
In addition, this method automatically renames the file extension of the
archive, .tar by default. Alternatively, a file extension may be specified
with the second parameter.
Parameters
extension
For decompressing, the default file extension is .phar.tar. Use
this parameter to specify another file extension. Be aware that no
non-executable archives cannot contain .phar in their filename.
Return Values
A PharData object is returned.
Errors/Exceptions
Throws BadMethodCallException if the zlib extension is not available, or
the bzip2 extension is not enabled.
Examples
Example #1 A PharData::decompress() example
decompress(); // creates /path/to/my.tar
?>
See Also
* PharFileInfo::getCompressedSize() - Returns the actual size of the
file (with compression) inside the Phar archive
* PharFileInfo::isCompressed() - Returns whether the entry is compressed
* PharFileInfo::compress() - Compresses the current Phar entry with
either zlib or bzip2 compression
* PharFileInfo::decompress() - Decompresses the current Phar entry
within the phar
* PharData::compress() - Compresses the entire tar/zip archive using
Gzip or Bzip2 compression
* Phar::canCompress() - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire
phar archive is compressed (.tar.gz/tar.bz and so on)
* PharData::compress() - Compresses the entire tar/zip archive using
Gzip or Bzip2 compression
* Phar::getSupportedCompression() - Return array of supported
compression algorithms
* PharData::compressFiles() - Compresses all files in the current
tar/zip archive
* PharData::decompressFiles() - Decompresses all files in the current
zip archive
----------------------------------------------------------------------
----------------------------------------------------------------------
PharData::decompressFiles
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharData::decompressFiles - Decompresses all files in the current zip
archive
Description
bool PharData::decompressFiles ( void )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
For tar-based archives, this method throws a BadMethodCallException, as
compression of individual files within a tar archive is not supported by
the file format. Use PharData::compress() to compress an entire tar-based
archive.
For Zip-based archives, this method decompresses all files in the archive.
The zlib or bzip2 extensions must be enabled to take advantage of this
feature if any files are compressed using bzip2/zlib compression.
Return Values
Returns TRUE on success or FALSE on failure.
Errors/Exceptions
Throws BadMethodCallException if the zlib extension is not available, or
if any files are compressed using bzip2 compression and the bzip2
extension is not enabled.
Examples
Example #1 A PharData::decompressFiles() example
compressFiles(Phar::GZ);
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressed(Phar::BZ2));
var_dump($file->isCompressed(Phar::GZ));
}
$p->decompressFiles();
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressed(Phar::BZ2));
var_dump($file->isCompressed(Phar::GZ));
}
?>
The above example will output:
string(10) "myfile.txt"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)
string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
See Also
* PharFileInfo::getCompressedSize() - Returns the actual size of the
file (with compression) inside the Phar archive
* PharFileInfo::isCompressed() - Returns whether the entry is compressed
* PharFileInfo::compress() - Compresses the current Phar entry with
either zlib or bzip2 compression
* PharFileInfo::decompress() - Decompresses the current Phar entry
within the phar
* Phar::canCompress() - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire
phar archive is compressed (.tar.gz/tar.bz and so on)
* PharData::compressFiles() - Compresses all files in the current
tar/zip archive
* Phar::getSupportedCompression() - Return array of supported
compression algorithms
* PharData::compress() - Compresses the entire tar/zip archive using
Gzip or Bzip2 compression
* PharData::decompress() - Decompresses the entire Phar archive
----------------------------------------------------------------------
----------------------------------------------------------------------
PharData::delMetadata
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharData::delMetadata - Deletes the global metadata of a zip archive
Description
bool PharData::delMetadata ( void )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
Deletes the global metadata of the zip archive
Parameters
Return Values
returns TRUE on success, but it is better to check for thrown exception,
and assume success if none is thrown.
Errors/Exceptions
Throws PharException if errors occur while flushing changes to disk.
Examples
Example #1 A PharData::delMetaData() example
getMetadata());
$phar->setMetadata("hi there");
var_dump($phar->getMetadata());
$phar->delMetadata();
var_dump($phar->getMetadata());
} catch (Exception $e) {
// handle errors
}
?>
The above example will output:
NULL
string(8) "hi there"
NULL
See Also
* Phar::delMetadata() - Deletes the global metadata of the phar
----------------------------------------------------------------------
----------------------------------------------------------------------
PharData::delete
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharData::delete - Delete a file within a tar/zip archive
Description
bool PharData::delete ( string $entry )
Delete a file within an archive. This is the functional equivalent of
calling unlink() on the stream wrapper equivalent, as shown in the example
below.
Parameters
entry
Path within an archive to the file to delete.
Return Values
returns TRUE on success, but it is better to check for thrown exception,
and assume success if none is thrown.
Errors/Exceptions
Throws PharException if errors occur while flushing changes to disk.
Examples
Example #1 A PharData::delete() example
delete('unlink/me.php');
// this is equivalent to:
unlink('phar://myphar.phar/unlink/me.php');
} catch (Exception $e) {
// handle errors
}
?>
See Also
* Phar::delete() - Delete a file within a phar archive
----------------------------------------------------------------------
----------------------------------------------------------------------
PharData::extractTo
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharData::extractTo - Extract the contents of a tar/zip archive to a
directory
Description
bool PharData::extractTo ( string $pathto [, string|array $files [, bool
$overwrite = false ]] )
Extract all files within a tar/zip archive to disk. Extracted files and
directories preserve permissions as stored in the archive. The optional
parameters allow optional control over which files are extracted, and
whether existing files on disk can be overwritten. The second parameter
files can be either the name of a file or directory to extract, or an
array of names of files and directories to extract. By default, this
method will not overwrite existing files, the third parameter can be set
to true to enable overwriting of files. This method is similar to
ZipArchive::extractTo().
Parameters
pathto
Path within an archive to the file to delete.
files
The name of a file or directory to extract, or an array of
files/directories to extract
overwrite
Set to TRUE to enable overwriting existing files
Return Values
returns TRUE on success, but it is better to check for thrown exception,
and assume success if none is thrown.
Errors/Exceptions
Throws PharException if errors occur while flushing changes to disk.
Examples
Example #1 A PharData::extractTo() example
extractTo('/full/path'); // extract all files
$phar->extractTo('/another/path', 'file.txt'); // extract only file.txt
$phar->extractTo('/this/path',
array('file1.txt', 'file2.txt')); // extract 2 files only
$phar->extractTo('/third/path', null, true); // extract all files, and overwrite
} catch (Exception $e) {
// handle errors
}
?>
See Also
* Phar::extractTo() - Extract the contents of a phar archive to a
directory
----------------------------------------------------------------------
----------------------------------------------------------------------
PharData::isWritable
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharData::isWritable - Returns true if the tar/zip archive can be modified
Description
bool PharData::isWritable ( void )
This method returns TRUE if the tar/zip archive on disk is not read-only.
Unlike Phar::isWritable(), data-only tar/zip archives can be modified even
if phar.readonly is set to 1.
Parameters
No parameters.
Return Values
Returns TRUE if the tar/zip archive can be modified
See Also
* Phar::canWrite() - Returns whether phar extension supports writing and
creating phars
* Phar::isWritable() - Returns true if the phar archive can be modified
----------------------------------------------------------------------
----------------------------------------------------------------------
PharData::offsetSet
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharData::offsetSet - set the contents of a file within the tar/zip to
those of an external file or string
Description
void PharData::offsetSet ( string $offset , string $value )
This is an implementation of the ArrayAccess interface allowing direct
manipulation of the contents of a tar/zip archive using array access
brackets. offsetSet is used for modifying an existing file, or adding a
new file to a tar/zip archive.
Parameters
offset
The filename (relative path) to modify in a tar or zip archive.
value
Content of the file.
Return Values
No return values.
Errors/Exceptions
Throws PharException if there are any problems flushing changes made to
the tar/zip archive to disk.
Examples
Example #1 A PharData::offsetSet() example
offsetSet should not be accessed directly, but instead used via array
access with the [] operator.
See Also
* Phar::offsetSet() - set the contents of an internal file to those of
an external file
----------------------------------------------------------------------
----------------------------------------------------------------------
PharData::offsetUnset
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharData::offsetUnset - remove a file from a tar/zip archive
Description
bool PharData::offsetUnset ( string $offset )
This is an implementation of the ArrayAccess interface allowing direct
manipulation of the contents of a tar/zip archive using array access
brackets. offsetUnset is used for deleting an existing file, and is called
by the unset() language construct.
Parameters
offset
The filename (relative path) to modify in the tar/zip archive.
Return Values
Returns TRUE on success or FALSE on failure.
Errors/Exceptions
Throws PharException if there are any problems flushing changes made to
the tar/zip archive to disk.
Examples
Example #1 A PharData::offsetUnset() example
See Also
* Phar::offsetUnset() - remove a file from a phar
----------------------------------------------------------------------
----------------------------------------------------------------------
PharData::setAlias
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharData::setAlias - dummy function (Phar::setAlias is not valid for
PharData)
Description
bool PharData::setAlias ( string $alias )
Non-executable tar/zip archives cannot have an alias, so this method
simply throws an exception.
Parameters
alias
A shorthand string that this archive can be referred to in phar
stream wrapper access. This parameter is ignored.
Return Values
Errors/Exceptions
Throws PharException on all method calls
See Also
* Phar::setAlias() - Set the alias for the Phar archive
----------------------------------------------------------------------
----------------------------------------------------------------------
PharData::setDefaultStub
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharData::setDefaultStub - dummy function (Phar::setDefaultStub is not
valid for PharData)
Description
bool PharData::setDefaultStub ([ string $index [, string $webindex ]] )
Non-executable tar/zip archives cannot have a stub, so this method simply
throws an exception.
Parameters
index
Relative path within the phar archive to run if accessed on the
command-line
webindex
Relative path within the phar archive to run if accessed through a
web browser
Return Values
Returns TRUE on success or FALSE on failure.
Errors/Exceptions
Throws PharException on all method calls
See Also
* Phar::setDefaultStub() - Used to set the PHP loader or bootstrap stub
of a Phar archive to the default loader
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::setMetadata
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::setMetadata - Sets phar archive meta-data
Description
void Phar::setMetadata ( mixed $metadata )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
Phar::setMetadata() should be used to store customized data that describes
something about the phar archive as a complete entity.
PharFileInfo::setMetadata() should be used for file-specific meta-data.
Meta-data can slow down the performance of loading a phar archive if the
data is large.
Some possible uses for meta-data include specifying which file within the
archive should be used to bootstrap the archive, or the location of a file
manifest like >> PEAR's package.xml file. However, any useful data that
describes the phar archive may be stored.
Parameters
metadata
Any PHP variable containing information to store that describes
the phar archive
Return Values
No value is returned.
Examples
Example #1 A Phar::setMetadata() example
setMetadata(array('bootstrap' => 'file.php'));
var_dump($p->getMetadata());
} catch (Exception $e) {
echo 'Could not create and/or modify phar:', $e;
}
?>
The above example will output:
array(1) {
["bootstrap"]=>
string(8) "file.php"
}
See Also
* Phar::getMetadata() - Returns phar archive meta-data
* Phar::delMetadata() - Deletes the global metadata of the phar
* Phar::hasMetadata() - Returns whether phar has global meta-data
----------------------------------------------------------------------
----------------------------------------------------------------------
Phar::setSignatureAlgorithm
(PHP >= 5.3.0, PECL phar >= 1.1.0)
Phar::setSignatureAlgorithm - set the signature algorithm for a phar and
apply it. The
Description
void Phar::setSignatureAlgorithm ( int $sigtype )
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in
order to work for Phar objects. Otherwise, a PharException will be
thrown.
set the signature algorithm for a phar and apply it. The signature
algorithm must be one of Phar::MD5, Phar::SHA1, Phar::SHA256,
Phar::SHA512, or Phar::PGP (pgp not yet supported and falls back to
SHA-1).
Parameters
sigtype
One of Phar::MD5, Phar::SHA1, Phar::SHA256, Phar::SHA512, or
Phar::PGP
Return Values
No value is returned.
Errors/Exceptions
Throws UnexpectedValueException for many errors, BadMethodCallException if
called for a zip- or a tar-based phar archive, and a PharException if any
problems occur flushing changes to disk.
See Also
* Phar::getSupportedSignatures() - Return array of supported signature
types
* Phar::getSignature() - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature
of a Phar archive
----------------------------------------------------------------------
----------------------------------------------------------------------
PharData::setStub
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharData::setStub - dummy function (Phar::setStub is not valid for
PharData)
Description
bool PharData::setStub ( string $stub )
Non-executable tar/zip archives cannot have a stub, so this method simply
throws an exception.
Parameters
stub
A string or an open stream handle to use as the executable stub
for this phar archive. This parameter is ignored.
Return Values
Returns TRUE on success or FALSE on failure.
Errors/Exceptions
Throws PharException on all method calls
See Also
* Phar::setStub() - Used to set the PHP loader or bootstrap stub of a
Phar archive
----------------------------------------------------------------------
Table of Contents
* PharData::addEmptyDir - Add an empty directory to the tar/zip archive
* PharData::addFile - Add a file from the filesystem to the tar/zip
archive
* PharData::addFromString - Add a file from the filesystem to the
tar/zip archive
* PharData::buildFromDirectory - Construct a tar/zip archive from the
files within a directory.
* PharData::buildFromIterator - Construct a tar or zip archive from an
iterator.
* PharData::compress - Compresses the entire tar/zip archive using Gzip
or Bzip2 compression
* PharData::compressFiles - Compresses all files in the current tar/zip
archive
* PharData::__construct - Construct a non-executable tar or zip archive
object
* PharData::convertToData - Convert a phar archive to a non-executable
tar or zip file
* PharData::convertToExecutable - Convert a non-executable tar/zip
archive to an executable phar archive
* PharData::copy - Copy a file internal to the phar archive to another
new file within the phar
* PharData::decompress - Decompresses the entire Phar archive
* PharData::decompressFiles - Decompresses all files in the current zip
archive
* PharData::delMetadata - Deletes the global metadata of a zip archive
* PharData::delete - Delete a file within a tar/zip archive
* PharData::extractTo - Extract the contents of a tar/zip archive to a
directory
* PharData::isWritable - Returns true if the tar/zip archive can be
modified
* PharData::offsetSet - set the contents of a file within the tar/zip to
those of an external file or string
* PharData::offsetUnset - remove a file from a tar/zip archive
* PharData::setAlias - dummy function (Phar::setAlias is not valid for
PharData)
* PharData::setDefaultStub - dummy function (Phar::setDefaultStub is not
valid for PharData)
* Phar::setMetadata - Sets phar archive meta-data
* Phar::setSignatureAlgorithm - set the signature algorithm for a phar
and apply it. The
* PharData::setStub - dummy function (Phar::setStub is not valid for
PharData)
----------------------------------------------------------------------
----------------------------------------------------------------------
The PharFileInfo class
Introduction
The PharFileInfo class provides a high-level interface to the contents and
attributes of a single file within a phar archive.
Class synopsis
PharFileInfo extends SplFileInfo {
/* Properties */
/* Methods */
void chmod ( int $permissions )
bool compress ( int $compression )
void __construct ( string $entry )
bool decompress ( void )
bool delMetadata ( void )
int getCRC32 ( void )
int getCompressedSize ( void )
mixed getMetaData ( void )
int getPharFlags ( void )
bool hasMetadata ( void )
bool isCRCChecked ( void )
bool isCompressed ([ int $compression_type = 9021976 ] )
bool isCompressedBZIP2 ( void )
bool isCompressedGZ ( void )
bool setCompressedBZIP2 ( void )
bool setCompressedGZ ( void )
void setMetaData ( mixed $metadata )
bool setUncompressed ( void )
}
----------------------------------------------------------------------
PharFileInfo::chmod
(PHP >= 5.3.0, PECL phar >= 1.0.0)
PharFileInfo::chmod - Sets file-specific permission bits
Description
void PharFileInfo::chmod ( int $permissions )
PharFileInfo::chmod() allows setting of the executable file permissions
bit, as well as read-only bits. Writeable bits are ignored, and set at
runtime based on the phar.readonly INI variable. As with all functionality
that modifies the contents of a phar, the phar.readonly INI variable must
be off in order to succeed if the file is within a Phar archive. Files
within PharData archives do not have this restriction.
Parameters
permissions
permissions (see chmod())
Return Values
No value is returned.
Examples
Example #1 A PharFileInfo::chmod() example
';
// set executable bit
$p['file.sh']->chmod(0555);
var_dump($p['file.sh']->isExecutable());
} catch (Exception $e) {
echo 'Could not create/modify phar: ', $e;
}
?>
The above example will output:
bool(true)
----------------------------------------------------------------------
----------------------------------------------------------------------
PharFileInfo::compress
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharFileInfo::compress - Compresses the current Phar entry with either
zlib or bzip2 compression
Description
bool PharFileInfo::compress ( int $compression )
This method compresses the file inside the Phar archive using either bzip2
compression or zlib compression. The bzip2 or zlib extension must be
enabled to take advantage of this feature. In addition, if the file is
already compressed, the respective extension must be enabled in order to
decompress the file. As with all functionality that modifies the contents
of a phar, the phar.readonly INI variable must be off in order to succeed
if the file is within a Phar archive. Files within PharData archives do
not have this restriction.
Return Values
Returns TRUE on success or FALSE on failure.
Errors/Exceptions
Throws BadMethodCallException if the phar.readonly INI variable is on, or
if the bzip2/zlib extension is not available.
Examples
Example #1 A PharFileInfo::compress() example
isCompressed(Phar::BZ2));
$p['myfile.txt']->compress(Phar::BZ2);
var_dump($file->isCompressed(Phar::BZ2));
} catch (Exception $e) {
echo 'Create/modify operations on my.phar failed: ', $e;
}
?>
The above example will output:
bool(false)
bool(true)
See Also
* PharFileInfo::getCompressedSize() - Returns the actual size of the
file (with compression) inside the Phar archive
* PharFileInfo::isCompressed() - Returns whether the entry is compressed
* PharFileInfo::decompress() - Decompresses the current Phar entry
within the phar
* Phar::canCompress() - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire
phar archive is compressed (.tar.gz/tar.bz and so on)
* Phar::compressFiles() - Compresses all files in the current Phar
archive
* Phar::decompressFiles() - Decompresses all files in the current Phar
archive
* Phar::compress() - Compresses the entire Phar archive using Gzip or
Bzip2 compression
* Phar::decompress() - Decompresses the entire Phar archive
* Phar::getSupportedCompression() - Return array of supported
compression algorithms
----------------------------------------------------------------------
----------------------------------------------------------------------
PharFileInfo::__construct
(PHP >= 5.3.0, PECL phar >= 1.0.0)
PharFileInfo::__construct - Construct a Phar entry object
Description
void PharFileInfo::__construct ( string $entry )
This should not be called directly. Instead, a PharFileInfo object is
initialized by calling Phar::offsetGet() through array access.
Parameters
entry
The full url to retrieve a file. If you wish to retrieve the
information for the file my/file.php from the phar boo.phar, the
entry should be phar://boo.phar/my/file.php.
Errors/Exceptions
Throws BadMethodCallException if __construct() is called twice. Throws
UnexpectedValueException if the phar URL requested is malformed, the
requested phar cannot be opened, or the file can't be found within the
phar.
Examples
Example #1 A PharFileInfo::__construct() example
$text) {
echo "line number $line: $text";
}
// this also works
$file = new PharFileInfo('phar:///path/to/my.phar/testfile.txt');
foreach ($file as $line => $text) {
echo "line number $line: $text";
}
} catch (Exception $e) {
echo 'Phar operations failed: ', $e;
}
?>
The above example will output:
line number 1: hi
line number 2: there
line number 3: dude
line number 1: hi
line number 2: there
line number 3: dude
----------------------------------------------------------------------
----------------------------------------------------------------------
PharFileInfo::decompress
(PHP >= 5.3.0, PECL phar >= 2.0.0)
PharFileInfo::decompress - Decompresses the current Phar entry within the
phar
Description
bool PharFileInfo::decompress ( void )
This method decompresses the file inside the Phar archive. Depending on
how the file is compressed, the bzip2 or zlib extensions must be enabled
to take advantage of this feature. As with all functionality that modifies
the contents of a phar, the phar.readonly INI variable must be off in
order to succeed if the file is within a Phar archive. Files within
PharData archives do not have this restriction.
Return Values
Returns TRUE on success or FALSE on failure.
Errors/Exceptions
Throws BadMethodCallException if the phar.readonly INI variable is on, or
if the bzip2/zlib extension is not available.
Examples
Example #1 A PharFileInfo::decompress() example
compress(Phar::GZ);
var_dump($file->isCompressed());
$p['myfile.txt']->decompress();
var_dump($file->isCompressed());
} catch (Exception $e) {
echo 'Create/modify failed for my.phar: ', $e;
}
?>
The above example will output:
int(4096)
bool(false)
See Also
* PharFileInfo::getCompressedSize() - Returns the actual size of the
file (with compression) inside the Phar archive
* PharFileInfo::isCompressed() - Returns whether the entry is compressed
* PharFileInfo::compress() - Compresses the current Phar entry with
either zlib or bzip2 compression
* Phar::canCompress() - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire
phar archive is compressed (.tar.gz/tar.bz and so on)
* Phar::compressFiles() - Compresses all files in the current Phar
archive
* Phar::decompressFiles() - Decompresses all files in the current Phar
archive
* Phar::compress() - Compresses the entire Phar archive using Gzip or
Bzip2 compression
* Phar::decompress() - Decompresses the entire Phar archive
* Phar::getSupportedCompression() - Return array of supported
compression algorithms
----------------------------------------------------------------------
----------------------------------------------------------------------
PharFileInfo::delMetadata
(PHP >= 5.3.0, PECL phar >= 1.2.0)
PharFileInfo::delMetadata - Deletes the metadata of the entry
Description
bool PharFileInfo::delMetadata ( void )
Deletes the metadata of the entry, if any.
Parameters
No parameters.
Return Values
Returns TRUE if successful, FALSE if the entry had no metadata. As with
all functionality that modifies the contents of a phar, the phar.readonly
INI variable must be off in order to succeed if the file is within a Phar
archive. Files within PharData archives do not have this restriction.
Errors/Exceptions
Throws PharException if errors occurred while flushing changes to disk,
and BadMethodCallException if write access is disabled.
Examples
Example #1 A PharFileInfo::delMetaData() example
delMetadata());
$a['hi']->setMetadata('there');
var_dump($a['hi']->delMetadata());
var_dump($a['hi']->delMetadata());
} catch (Exception $e) {
// handle errors
}
?>
The above example will output:
bool(false)
bool(true)
bool(false)
See Also
* PharFileInfo::setMetadata() - Sets file-specific meta-data saved with
a file
* PharFileInfo::hasMetadata() - Returns the metadata of the entry
* PharFileInfo::getMetadata() - Returns file-specific meta-data saved
with a file
* Phar::setMetadata() - Sets phar archive meta-data
* Phar::hasMetadata() - Returns whether phar has global meta-data
* Phar::getMetadata() - Returns phar archive meta-data
----------------------------------------------------------------------
----------------------------------------------------------------------
PharFileInfo::getCRC32
(PHP >= 5.3.0, PECL phar >= 1.0.0)
PharFileInfo::getCRC32 - Returns CRC32 code or throws an exception if CRC
has not been verified
Description
int PharFileInfo::getCRC32 ( void )
This returns the crc32() checksum of the file within the Phar archive.
Return Values
The crc32() checksum of the file within the Phar archive.
Errors/Exceptions
Throws BadMethodCallException if the file has not yet had its CRC32
verified. This should be impossible with normal use, as the CRC is
verified upon opening the file for reading or writing.
Examples
Example #1 A PharFileInfo::getCRC32() example
getCRC32();
} catch (Exception $e) {
echo 'Write operations on my.phar.phar failed: ', $e;
}
?>
The above example will output:
3633523372
----------------------------------------------------------------------
----------------------------------------------------------------------
PharFileInfo::getCompressedSize
(PHP >= 5.3.0, PECL phar >= 1.0.0)
PharFileInfo::getCompressedSize - Returns the actual size of the file
(with compression) inside the Phar archive
Description
int PharFileInfo::getCompressedSize ( void )
This returns the size of the file within the Phar archive. Uncompressed
files will return the same value for getCompressedSize as they will with
filesize()
Return Values
The size in bytes of the file within the Phar archive on disk.
Examples
Example #1 A PharFileInfo::getCompressedSize() example
getCompressedSize();
} catch (Exception $e) {
echo 'Write operations failed on my.phar: ', $e;
}
?>
The above example will output:
2
See Also
* PharFileInfo::isCompressed() - Returns whether the entry is compressed
* PharFileInfo::decompress() - Decompresses the current Phar entry
within the phar
* PharFileInfo::compress() - Compresses the current Phar entry with
either zlib or bzip2 compression
* Phar::canCompress() - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire
phar archive is compressed (.tar.gz/tar.bz and so on)
* Phar::compress() - Compresses the entire Phar archive using Gzip or
Bzip2 compression
* Phar::decompress() - Decompresses the entire Phar archive
* Phar::getSupportedCompression() - Return array of supported
compression algorithms
* Phar::decompressFiles() - Decompresses all files in the current Phar
archive
* Phar::compressFiles() - Compresses all files in the current Phar
archive
----------------------------------------------------------------------
----------------------------------------------------------------------
PharFileInfo::getMetaData
(PHP >= 5.3.0, PECL phar >= 1.0.0)
PharFileInfo::getMetaData - Returns file-specific meta-data saved with a
file
Description
mixed PharFileInfo::getMetaData ( void )
Return meta-data that was saved in the Phar archive's manifest for this
file.
Parameters
Return Values
any PHP variable that can be serialized and is stored as meta-data for the
file, or NULL if no meta-data is stored.
Examples
Example #1 A PharFileInfo::getMetaData() example
setMetaData(array('user' => 'bill', 'mime-type' => 'text/plain'));
var_dump($p['file.txt']->getMetaData());
} catch (Exception $e) {
echo 'Could not create/modify brandnewphar.phar: ', $e;
}
?>
The above example will output:
array(2) {
["user"]=>
string(4) "bill"
["mime-type"]=>
string(10) "text/plain"
}
See Also
* PharFileInfo::setMetadata() - Sets file-specific meta-data saved with
a file
* PharFileInfo::hasMetadata() - Returns the metadata of the entry
* PharFileInfo::delMetadata() - Deletes the metadata of the entry
* Phar::setMetadata() - Sets phar archive meta-data
* Phar::hasMetadata() - Returns whether phar has global meta-data
* Phar::getMetadata() - Returns phar archive meta-data
----------------------------------------------------------------------
----------------------------------------------------------------------
PharFileInfo::getPharFlags
(PHP >= 5.3.0, PECL phar >= 1.0.0)
PharFileInfo::getPharFlags - Returns the Phar file entry flags
Description
int PharFileInfo::getPharFlags ( void )
This returns the flags set in the manifest for a Phar. This will always
return 0 in the current implementation.
Return Values
The Phar flags (always 0 in the current implementation)
Examples
Example #1 A PharFileInfo::getPharFlags() example
getPharFlags());
} catch (Exception $e) {
echo 'Could not create/modify my.phar: ', $e;
}
?>
The above example will output:
int(0)
----------------------------------------------------------------------
----------------------------------------------------------------------
PharFileInfo::hasMetadata
(PHP >= 5.3.0, PECL phar >= 1.2.0)
PharFileInfo::hasMetadata - Returns the metadata of the entry
Description
bool PharFileInfo::hasMetadata ( void )
Returns the metadata of a file within a phar archive.
Parameters
No parameters.
Return Values
Returns FALSE if no metadata is set or is NULL, TRUE if metadata is not
NULL
See Also
* PharFileInfo::setMetadata() - Sets file-specific meta-data saved with
a file
* PharFileInfo::getMetadata() - Returns file-specific meta-data saved
with a file
* PharFileInfo::delMetadata() - Deletes the metadata of the entry
* Phar::setMetadata() - Sets phar archive meta-data
* Phar::hasMetadata() - Returns whether phar has global meta-data
* Phar::getMetadata() - Returns phar archive meta-data
----------------------------------------------------------------------
----------------------------------------------------------------------
PharFileInfo::isCRCChecked
(PHP >= 5.3.0, PECL phar >= 1.0.0)
PharFileInfo::isCRCChecked - Returns whether file entry has had its CRC
verified
Description
bool PharFileInfo::isCRCChecked ( void )
This returns whether a file within a Phar archive has had its CRC
verified.
Return Values
TRUE if the file has had its CRC verified, FALSE if not.
Examples
Example #1 A PharFileInfo::isCRCChecked() example
isCRCChecked());
} catch (Exception $e) {
echo 'Create/modify operations failed on my.phar: ', $e;
}
?>
The above example will output:
bool(true)
----------------------------------------------------------------------
----------------------------------------------------------------------
PharFileInfo::isCompressed
(PHP >= 5.3.0, PECL phar >= 1.0.0)
PharFileInfo::isCompressed - Returns whether the entry is compressed
Description
bool PharFileInfo::isCompressed ([ int $compression_type = 9021976 ] )
This returns whether a file is compressed within a Phar archive with
either Gzip or Bzip2 compression.
Parameters
compression_type
One of Phar::GZ or Phar::BZ2, defaults to any compression.
Return Values
TRUE if the file is compressed within the Phar archive, FALSE if not.
Examples
Example #1 A PharFileInfo::isCompressed() example
setCompressedGZ();
$file = $p['myfile.txt'];
$file2 = $p['myfile2.txt'];
var_dump($file->isCompressed());
var_dump($file2->isCompressed());
} catch (Exception $e) {
echo 'Create/modify on phar my.phar failed: ', $e;
}
?>
The above example will output:
bool(false)
bool(true)
See Also
* PharFileInfo::getCompressedSize() - Returns the actual size of the
file (with compression) inside the Phar archive
* PharFileInfo::decompress() - Decompresses the current Phar entry
within the phar
* PharFileInfo::compress() - Compresses the current Phar entry with
either zlib or bzip2 compression
* Phar::decompress() - Decompresses the entire Phar archive
* Phar::compress() - Compresses the entire Phar archive using Gzip or
Bzip2 compression
* Phar::canCompress() - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire
phar archive is compressed (.tar.gz/tar.bz and so on)
* Phar::getSupportedCompression() - Return array of supported
compression algorithms
* Phar::decompressFiles() - Decompresses all files in the current Phar
archive
* Phar::compressFiles() - Compresses all files in the current Phar
archive
----------------------------------------------------------------------
----------------------------------------------------------------------
PharFileInfo::isCompressedBZIP2
(PHP >= 5.3.0, PECL phar >= 1.0.0)
PharFileInfo::isCompressedBZIP2 - Returns whether the entry is compressed
using bzip2
Description
bool PharFileInfo::isCompressedBZIP2 ( void )
Note:
This method has been removed from the phar extension as of version
2.0.0. Alternative implementations are available using
PharFileInfo::isCompressed(), PharFileInfo::decompress(), and
PharFileInfo::compress().
This returns whether a file is compressed within a Phar archive with Bzip2
compression.
Return Values
TRUE if the file is compressed within the Phar archive using Bzip2, FALSE
if not.
Examples
Example #1 A PharFileInfo::isCompressedBZIP2() example
setCompressedGZ();
$p['myfile3.txt']->setCompressedBZIP2();
$file = $p['myfile.txt'];
$file2 = $p['myfile2.txt'];
$file3 = $p['myfile3.txt'];
var_dump($file->isCompressedBZIP2());
var_dump($file2->isCompressedBZIP2());
var_dump($file3->isCompressedBZIP2());
} catch (Exception $e) {
echo 'Create/modify on phar my.phar failed: ', $e;
}
?>
The above example will output:
bool(false)
bool(false)
bool(true)
See Also
* PharFileInfo::getCompressedSize() - Returns the actual size of the
file (with compression) inside the Phar archive
* PharFileInfo::isCompressed() - Returns whether the entry is compressed
* PharFileInfo::isCompressedGZ() - Returns whether the entry is
compressed using gz
* PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry
within the phar using Bzip2 compression
* PharFileInfo::setUncompressed() - Uncompresses the current Phar entry
within the phar, if it is compressed
* PharFileInfo::setCompressedGZ() - Compresses the current Phar entry
within the phar using gz compression
* Phar::canCompress() - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire
phar archive is compressed (.tar.gz/tar.bz and so on)
* Phar::compressAllFilesBZIP2() - Compresses all files in the current
Phar archive using Bzip2 compression
* Phar::compressAllFilesGZ() - Compresses all files in the current Phar
archive using Gzip compression
* Phar::getSupportedCompression() - Return array of supported
compression algorithms
* Phar::uncompressAllFiles() - Uncompresses all files in the current
Phar archive
----------------------------------------------------------------------
----------------------------------------------------------------------
PharFileInfo::isCompressedGZ
(PHP >= 5.3.0, PECL phar >= 1.0.0)
PharFileInfo::isCompressedGZ - Returns whether the entry is compressed
using gz
Description
bool PharFileInfo::isCompressedGZ ( void )
Note:
This method has been removed from the phar extension as of version
2.0.0. Alternative implementations are available using
PharFileInfo::isCompressed(), PharFileInfo::decompress(), and
PharFileInfo::compress().
This returns whether a file is compressed within a Phar archive with Gzip
compression.
Return Values
TRUE if the file is compressed within the Phar archive using Gzip, FALSE
if not.
Examples
Example #1 A PharFileInfo::isCompressedGZ() example
setCompressedGZ();
$p['myfile3.txt']->setCompressedBZIP2();
$file = $p['myfile.txt'];
$file2 = $p['myfile2.txt'];
$file3 = $p['myfile3.txt'];
var_dump($file->isCompressedGZ());
var_dump($file2->isCompressedGZ());
var_dump($file3->isCompressedGZ());
} catch (Exception $e) {
echo 'Create/modify on phar my.phar failed: ', $e;
}
?>
The above example will output:
bool(false)
bool(true)
bool(false)
See Also
* PharFileInfo::getCompressedSize() - Returns the actual size of the
file (with compression) inside the Phar archive
* PharFileInfo::isCompressedBZIP2() - Returns whether the entry is
compressed using bzip2
* PharFileInfo::isCompressed() - Returns whether the entry is compressed
* PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry
within the phar using Bzip2 compression
* PharFileInfo::setUncompressed() - Uncompresses the current Phar entry
within the phar, if it is compressed
* PharFileInfo::setCompressedGZ() - Compresses the current Phar entry
within the phar using gz compression
* Phar::canCompress() - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire
phar archive is compressed (.tar.gz/tar.bz and so on)
* Phar::compressAllFilesBZIP2() - Compresses all files in the current
Phar archive using Bzip2 compression
* Phar::compressAllFilesGZ() - Compresses all files in the current Phar
archive using Gzip compression
* Phar::getSupportedCompression() - Return array of supported
compression algorithms
* Phar::uncompressAllFiles() - Uncompresses all files in the current
Phar archive
----------------------------------------------------------------------
----------------------------------------------------------------------
PharFileInfo::setCompressedBZIP2
(PHP >= 5.3.0, PECL phar >= 1.0.0)
PharFileInfo::setCompressedBZIP2 - Compresses the current Phar entry
within the phar using Bzip2 compression
Description
bool PharFileInfo::setCompressedBZIP2 ( void )
Note:
This method has been removed from the phar extension as of version
2.0.0. Alternative implementations are available using
PharFileInfo::isCompressed(), PharFileInfo::decompress(), and
PharFileInfo::compress().
This method compresses the file inside the Phar archive using bzip2
compression. The bzip2 extension must be enabled to take advantage of this
feature. In addition, if the file is already compressed using gzip
compression, the zlib extension must be enabled in order to decompress the
file. As with all functionality that modifies the contents of a phar, the
phar.readonly INI variable must be off in order to succeed.
Return Values
Returns TRUE on success or FALSE on failure.
Errors/Exceptions
Throws BadMethodCallException if the phar.readonly INI variable is on, or
if the bzip2 extension is not available.
Examples
Example #1 A PharFileInfo::setCompressedBZIP2() example
isCompressedBZIP2());
$p['myfile.txt']->setCompressedBZIP2();
var_dump($file->isCompressedBZIP2());
} catch (Exception $e) {
echo 'Create/modify operations on my.phar failed: ', $e;
}
?>
The above example will output:
bool(false)
bool(true)
See Also
* PharFileInfo::getCompressedSize() - Returns the actual size of the
file (with compression) inside the Phar archive
* PharFileInfo::isCompressedBZIP2() - Returns whether the entry is
compressed using bzip2
* PharFileInfo::isCompressed() - Returns whether the entry is compressed
* PharFileInfo::isCompressedGZ() - Returns whether the entry is
compressed using gz
* PharFileInfo::setUncompressed() - Uncompresses the current Phar entry
within the phar, if it is compressed
* PharFileInfo::setCompressedGZ() - Compresses the current Phar entry
within the phar using gz compression
* Phar::canCompress() - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire
phar archive is compressed (.tar.gz/tar.bz and so on)
* Phar::compressAllFilesBZIP2() - Compresses all files in the current
Phar archive using Bzip2 compression
* Phar::compressAllFilesGZ() - Compresses all files in the current Phar
archive using Gzip compression
* Phar::getSupportedCompression() - Return array of supported
compression algorithms
* Phar::uncompressAllFiles() - Uncompresses all files in the current
Phar archive
----------------------------------------------------------------------
----------------------------------------------------------------------
PharFileInfo::setCompressedGZ
(PHP >= 5.3.0, PECL phar >= 1.0.0)
PharFileInfo::setCompressedGZ - Compresses the current Phar entry within
the phar using gz compression
Description
bool PharFileInfo::setCompressedGZ ( void )
Note:
This method has been removed from the phar extension as of version
2.0.0. Alternative implementations are available using
PharFileInfo::isCompressed(), PharFileInfo::decompress(), and
PharFileInfo::compress().
This method compresses the file inside the Phar archive using gzip
compression. The zlib extension must be enabled to take advantage of this
feature. In addition, if the file is already compressed using bzip2
compression, the bzip2 extension must be enabled in order to decompress
the file. As with all functionality that modifies the contents of a phar,
the phar.readonly INI variable must be off in order to succeed.
Return Values
Returns TRUE on success or FALSE on failure.
Errors/Exceptions
Throws BadMethodCallException if the phar.readonly INI variable is on, or
if the zlib extension is not available.
Examples
Example #1 A PharFileInfo::setCompressedGZ() example
isCompressedGZ());
$p['myfile.txt']->setCompressedGZ();
var_dump($file->isCompressedGZ());
} catch (Exception $e) {
echo 'Create/modify operations on my.phar failed: ', $e;
}
?>
The above example will output:
bool(false)
bool(true)
See Also
* PharFileInfo::getCompressedSize() - Returns the actual size of the
file (with compression) inside the Phar archive
* PharFileInfo::isCompressedBZIP2() - Returns whether the entry is
compressed using bzip2
* PharFileInfo::isCompressed() - Returns whether the entry is compressed
* PharFileInfo::isCompressedGZ() - Returns whether the entry is
compressed using gz
* PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry
within the phar using Bzip2 compression
* PharFileInfo::setUncompressed() - Uncompresses the current Phar entry
within the phar, if it is compressed
* Phar::canCompress() - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire
phar archive is compressed (.tar.gz/tar.bz and so on)
* Phar::compressAllFilesBZIP2() - Compresses all files in the current
Phar archive using Bzip2 compression
* Phar::compressAllFilesGZ() - Compresses all files in the current Phar
archive using Gzip compression
* Phar::getSupportedCompression() - Return array of supported
compression algorithms
* Phar::uncompressAllFiles() - Uncompresses all files in the current
Phar archive
----------------------------------------------------------------------
----------------------------------------------------------------------
PharFileInfo::setMetaData
(PHP >= 5.3.0, PECL phar >= 1.0.0)
PharFileInfo::setMetaData - Sets file-specific meta-data saved with a file
Description
void PharFileInfo::setMetaData ( mixed $metadata )
PharFileInfo::setMetaData() should only be used to store customized data
in a file that cannot be represented with existing information stored with
a file. Meta-data can significantly slow down the performance of loading a
phar archive if the data is large, or if there are many files containing
meta-data. It is important to note that file permissions are natively
supported inside a phar; it is possible to set them with the
PharFileInfo::chmod() method. As with all functionality that modifies the
contents of a phar, the phar.readonly INI variable must be off in order to
succeed if the file is within a Phar archive. Files within PharData
archives do not have this restriction.
Some possible uses for meta-data include passing a user/group that should
be set when a file is extracted from the phar to disk. Other uses could
include explicitly specifying a MIME type to return. However, any useful
data that describes a file, but should not be contained inside of it may
be stored.
Parameters
metadata
Any PHP variable containing information to store alongside a file
Return Values
No value is returned.
Examples
Example #1 A PharFileInfo::setMetaData() example
setMetaData(array('user' => 'bill', 'mime-type' => 'text/plain'));
var_dump($p['file.txt']->getMetaData());
} catch (Exception $e) {
echo 'Could not create/modify phar: ', $e;
}
?>
The above example will output:
array(2) {
["user"]=>
string(4) "bill"
["mime-type"]=>
string(10) "text/plain"
}
See Also
* PharFileInfo::hasMetadata() - Returns the metadata of the entry
* PharFileInfo::getMetadata() - Returns file-specific meta-data saved
with a file
* PharFileInfo::delMetadata() - Deletes the metadata of the entry
* Phar::setMetadata() - Sets phar archive meta-data
* Phar::hasMetadata() - Returns whether phar has global meta-data
* Phar::getMetadata() - Returns phar archive meta-data
----------------------------------------------------------------------
----------------------------------------------------------------------
PharFileInfo::setUncompressed
(PHP >= 5.3.0, PECL phar >= 1.0.0)
PharFileInfo::setUncompressed - Uncompresses the current Phar entry within
the phar, if it is compressed
Description
bool PharFileInfo::setUncompressed ( void )
Note:
This method has been removed from the phar extension as of version
2.0.0. Alternative implementations are available using
PharFileInfo::isCompressed(), PharFileInfo::decompress(), and
PharFileInfo::compress().
This method decompresses the file inside the Phar archive. Depending on
how the file is compressed, the bzip2 or zlib extensions must be enabled
to take advantage of this feature. As with all functionality that modifies
the contents of a phar, the phar.readonly INI variable must be off in
order to succeed.
Return Values
Returns TRUE on success or FALSE on failure.
Errors/Exceptions
Throws BadMethodCallException if the phar.readonly INI variable is on, or
if the bzip2/zlib extension is not available.
Examples
Example #1 A PharFileInfo::setUncompressed() example
setCompressedGZ();
var_dump($file->isCompressed());
$p['myfile.txt']->setUncompressed();
var_dump($file->isCompressed());
} catch (Exception $e) {
echo 'Create/modify failed for my.phar: ', $e;
}
?>
The above example will output:
bool(true)
bool(false)
See Also
* PharFileInfo::getCompressedSize() - Returns the actual size of the
file (with compression) inside the Phar archive
* PharFileInfo::isCompressedBZIP2() - Returns whether the entry is
compressed using bzip2
* PharFileInfo::isCompressed() - Returns whether the entry is compressed
* PharFileInfo::isCompressedGZ() - Returns whether the entry is
compressed using gz
* PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry
within the phar using Bzip2 compression
* PharFileInfo::setCompressedGZ() - Compresses the current Phar entry
within the phar using gz compression
* Phar::canCompress() - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire
phar archive is compressed (.tar.gz/tar.bz and so on)
* Phar::compressAllFilesBZIP2() - Compresses all files in the current
Phar archive using Bzip2 compression
* Phar::compressAllFilesGZ() - Compresses all files in the current Phar
archive using Gzip compression
* Phar::getSupportedCompression() - Return array of supported
compression algorithms
* Phar::uncompressAllFiles() - Uncompresses all files in the current
Phar archive
----------------------------------------------------------------------
Table of Contents
* PharFileInfo::chmod - Sets file-specific permission bits
* PharFileInfo::compress - Compresses the current Phar entry with either
zlib or bzip2 compression
* PharFileInfo::__construct - Construct a Phar entry object
* PharFileInfo::decompress - Decompresses the current Phar entry within
the phar
* PharFileInfo::delMetadata - Deletes the metadata of the entry
* PharFileInfo::getCRC32 - Returns CRC32 code or throws an exception if
CRC has not been verified
* PharFileInfo::getCompressedSize - Returns the actual size of the file
(with compression) inside the Phar archive
* PharFileInfo::getMetaData - Returns file-specific meta-data saved with
a file
* PharFileInfo::getPharFlags - Returns the Phar file entry flags
* PharFileInfo::hasMetadata - Returns the metadata of the entry
* PharFileInfo::isCRCChecked - Returns whether file entry has had its
CRC verified
* PharFileInfo::isCompressed - Returns whether the entry is compressed
* PharFileInfo::isCompressedBZIP2 - Returns whether the entry is
compressed using bzip2
* PharFileInfo::isCompressedGZ - Returns whether the entry is compressed
using gz
* PharFileInfo::setCompressedBZIP2 - Compresses the current Phar entry
within the phar using Bzip2 compression
* PharFileInfo::setCompressedGZ - Compresses the current Phar entry
within the phar using gz compression
* PharFileInfo::setMetaData - Sets file-specific meta-data saved with a
file
* PharFileInfo::setUncompressed - Uncompresses the current Phar entry
within the phar, if it is compressed
----------------------------------------------------------------------
----------------------------------------------------------------------
The PharException class
Introduction
The PharException class provides a phar-specific exception class for
try/catch blocks.
Class synopsis
PharException extends Exception {
/* Properties */
}
----------------------------------------------------------------------
PharException
(Unknown)
PharException - The PharException class provides a phar-specific exception
class for try/catch blocks.
Description
----------------------------------------------------------------------
Table of Contents
* PharException - The PharException class provides a phar-specific
exception class for try/catch blocks.
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Using Phar Archives
* Using Phar Archives: Introduction
* Using Phar Archives: the phar stream wrapper
* Using Phar Archives: the Phar and PharData class
* Creating Phar Archives
* Creating Phar Archives: Introduction
* What makes a phar a phar and not a tar or a zip?
* Ingredients of all Phar archives, independent of file format
* Phar file stub
* Head-to-head comparison of Phar, Tar and Zip
* Tar-based phars
* Zip-based phars
* Phar File Format
* Global Phar bitmapped flags
* Phar manifest file entry definition
* Phar Signature format
* Phar - The Phar class
* Phar::addEmptyDir - Add an empty directory to the phar archive
* Phar::addFile - Add a file from the filesystem to the phar
archive
* Phar::addFromString - Add a file from the filesystem to the phar
archive
* Phar::apiVersion - Returns the api version
* Phar::buildFromDirectory - Construct a phar archive from the
files within a directory.
* Phar::buildFromIterator - Construct a phar archive from an
iterator.
* Phar::canCompress - Returns whether phar extension supports
compression using either zlib or bzip2
* Phar::canWrite - Returns whether phar extension supports writing
and creating phars
* Phar::compress - Compresses the entire Phar archive using Gzip or
Bzip2 compression
* Phar::compressAllFilesBZIP2 - Compresses all files in the current
Phar archive using Bzip2 compression
* Phar::compressAllFilesGZ - Compresses all files in the current
Phar archive using Gzip compression
* Phar::compressFiles - Compresses all files in the current Phar
archive
* Phar::__construct - Construct a Phar archive object
* Phar::convertToData - Convert a phar archive to a non-executable
tar or zip file
* Phar::convertToExecutable - Convert a phar archive to another
executable phar archive file format
* Phar::copy - Copy a file internal to the phar archive to another
new file within the phar
* Phar::count - Returns the number of entries (files) in the Phar
archive
* Phar::createDefaultStub - Create a phar-file format specific stub
* Phar::decompress - Decompresses the entire Phar archive
* Phar::decompressFiles - Decompresses all files in the current
Phar archive
* Phar::delMetadata - Deletes the global metadata of the phar
* Phar::delete - Delete a file within a phar archive
* Phar::extractTo - Extract the contents of a phar archive to a
directory
* Phar::getMetaData - Returns phar archive meta-data
* Phar::getModified - Return whether phar was modified
* Phar::getSignature - Return MD5/SHA1/SHA256/SHA512/OpenSSL
signature of a Phar archive
* Phar::getStub - Return the PHP loader or bootstrap stub of a Phar
archive
* Phar::getSupportedCompression - Return array of supported
compression algorithms
* Phar::getSupportedSignatures - Return array of supported
signature types
* Phar::getVersion - Return version info of Phar archive
* Phar::hasMetaData - Returns whether phar has global meta-data
* Phar::interceptFileFuncs - instructs phar to intercept fopen,
file_get_contents, opendir, and all of the stat-related functions
* Phar::isBuffering - Used to determine whether Phar write
operations are being buffered, or are flushing directly to disk
* Phar::isCompressed - Returns Phar::GZ or PHAR::BZ2 if the entire
phar archive is compressed (.tar.gz/tar.bz and so on)
* Phar::isFileFormat - Returns true if the phar archive is based on
the tar/phar/zip file format depending on the parameter
* Phar::isValidPharFilename - Returns whether the given filename is
a valid phar filename
* Phar::isWritable - Returns true if the phar archive can be
modified
* Phar::loadPhar - Loads any phar archive with an alias
* Phar::mapPhar - Reads the currently executed file (a phar) and
registers its manifest
* Phar::mount - Mount an external path or file to a virtual
location within the phar archive
* Phar::mungServer - Defines a list of up to 4 $_SERVER variables
that should be modified for execution
* Phar::offsetExists - determines whether a file exists in the phar
* Phar::offsetGet - Gets a PharFileInfo object for a specific file
* Phar::offsetSet - set the contents of an internal file to those
of an external file
* Phar::offsetUnset - remove a file from a phar
* Phar::running - Returns the full path on disk or full phar URL to
the currently executing Phar archive
* Phar::setAlias - Set the alias for the Phar archive
* Phar::setDefaultStub - Used to set the PHP loader or bootstrap
stub of a Phar archive to the default loader
* Phar::setMetadata - Sets phar archive meta-data
* Phar::setSignatureAlgorithm - set the signature algorithm for a
phar and apply it.
* Phar::setStub - Used to set the PHP loader or bootstrap stub of a
Phar archive
* Phar::startBuffering - Start buffering Phar write operations, do
not modify the Phar object on disk
* Phar::stopBuffering - Stop buffering write requests to the Phar
archive, and save changes to disk
* Phar::uncompressAllFiles - Uncompresses all files in the current
Phar archive
* Phar::unlinkArchive - Completely remove a phar archive from disk
and from memory
* Phar::webPhar - mapPhar for web-based phars. front controller for
web applications
* PharData - The PharData class
* PharData::addEmptyDir - Add an empty directory to the tar/zip
archive
* PharData::addFile - Add a file from the filesystem to the tar/zip
archive
* PharData::addFromString - Add a file from the filesystem to the
tar/zip archive
* PharData::buildFromDirectory - Construct a tar/zip archive from
the files within a directory.
* PharData::buildFromIterator - Construct a tar or zip archive from
an iterator.
* PharData::compress - Compresses the entire tar/zip archive using
Gzip or Bzip2 compression
* PharData::compressFiles - Compresses all files in the current
tar/zip archive
* PharData::__construct - Construct a non-executable tar or zip
archive object
* PharData::convertToData - Convert a phar archive to a
non-executable tar or zip file
* PharData::convertToExecutable - Convert a non-executable tar/zip
archive to an executable phar archive
* PharData::copy - Copy a file internal to the phar archive to
another new file within the phar
* PharData::decompress - Decompresses the entire Phar archive
* PharData::decompressFiles - Decompresses all files in the current
zip archive
* PharData::delMetadata - Deletes the global metadata of a zip
archive
* PharData::delete - Delete a file within a tar/zip archive
* PharData::extractTo - Extract the contents of a tar/zip archive
to a directory
* PharData::isWritable - Returns true if the tar/zip archive can be
modified
* PharData::offsetSet - set the contents of a file within the
tar/zip to those of an external file or string
* PharData::offsetUnset - remove a file from a tar/zip archive
* PharData::setAlias - dummy function (Phar::setAlias is not valid
for PharData)
* PharData::setDefaultStub - dummy function (Phar::setDefaultStub
is not valid for PharData)
* Phar::setMetadata - Sets phar archive meta-data
* Phar::setSignatureAlgorithm - set the signature algorithm for a
phar and apply it. The
* PharData::setStub - dummy function (Phar::setStub is not valid
for PharData)
* PharFileInfo - The PharFileInfo class
* PharFileInfo::chmod - Sets file-specific permission bits
* PharFileInfo::compress - Compresses the current Phar entry with
either zlib or bzip2 compression
* PharFileInfo::__construct - Construct a Phar entry object
* PharFileInfo::decompress - Decompresses the current Phar entry
within the phar
* PharFileInfo::delMetadata - Deletes the metadata of the entry
* PharFileInfo::getCRC32 - Returns CRC32 code or throws an
exception if CRC has not been verified
* PharFileInfo::getCompressedSize - Returns the actual size of the
file (with compression) inside the Phar archive
* PharFileInfo::getMetaData - Returns file-specific meta-data saved
with a file
* PharFileInfo::getPharFlags - Returns the Phar file entry flags
* PharFileInfo::hasMetadata - Returns the metadata of the entry
* PharFileInfo::isCRCChecked - Returns whether file entry has had
its CRC verified
* PharFileInfo::isCompressed - Returns whether the entry is
compressed
* PharFileInfo::isCompressedBZIP2 - Returns whether the entry is
compressed using bzip2
* PharFileInfo::isCompressedGZ - Returns whether the entry is
compressed using gz
* PharFileInfo::setCompressedBZIP2 - Compresses the current Phar
entry within the phar using Bzip2 compression
* PharFileInfo::setCompressedGZ - Compresses the current Phar entry
within the phar using gz compression
* PharFileInfo::setMetaData - Sets file-specific meta-data saved
with a file
* PharFileInfo::setUncompressed - Uncompresses the current Phar
entry within the phar, if it is compressed
* PharException - The PharException class
* PharException - The PharException class provides a phar-specific
exception class for try/catch blocks.
----------------------------------------------------------------------
----------------------------------------------------------------------
Rar Archiving
----------------------------------------------------------------------
Introduction
Rar is a powerful and effective archiver created by Eugene Roshal. This
extension gives you possibility to read Rar archives but doesn't support
writing Rar archives, because this is not supported by the UnRar library
and is directly prohibited by its license.
More information about Rar and UnRar can be found at
>> http://www.rarlabs.com/.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
Rar is currently available through PECL
>> http://pecl.php.net/package/rar.
Also you can use the PECL installer to install the Rar extension, using
the following command: pecl -v install rar.
You can always download the tar.gz package and install Rar by hand:
Example #1 Rar installation
gunzip rar-xxx.tgz
tar -xvf rar-xxx.tar
cd rar-xxx
phpize
./configure && make && make install
Windows users will enable php_rar.dll inside of php.ini in order to use
these functions. A DLL for this PECL extension is currently unavailable.
See also the building on Windows section.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension registers three internal classes: The archive
representations returned by rar_open() - RarArchive -, the entry
representations returned by rar_list() and rar_entry_get() - RarEntry and
the exception type RarException.
This extension also register a stream resource, called "rar" and a URL
wrapper called "rar wrapper" and registered under the prefix "rar".
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
RAR_HOST_MSDOS (integer)
Use RarEntry::HOST_MSDOS instead.
RAR_HOST_OS2 (integer)
Use RarEntry::HOST_OS2 instead.
RAR_HOST_WIN32 (integer)
Use RarEntry::HOST_WIN32 instead.
RAR_HOST_UNIX (integer)
Use RarEntry::HOST_UNIX instead.
RAR_HOST_BEOS (integer)
Use RarEntry::HOST_BEOS instead.
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
See also the examples under rar:// wrapper.
Example #1 On-the-fly decompression
getEntries();
if ($entries === FALSE)
die("Cannot retrieve entries");
if (!array_key_exists($index, $entries))
die("No such index: $index");
$orfilename = $entries[$index]->getName(); //UTF-8 encoded
$filesize = $entries[$index]->getUnpackedSize();
/* you could check HTTP_IF_MODIFIED_SINCE here and compare with
* $entries[$index]->getFileTime(). You could also send a
* "Last modified" header */
$fp = $entries[$index]->getStream();
if ($fp === FALSE)
die("Cannot open file with index $index insided the archive.");
$arch->close(); //no longer needed; stream is independent
function detectUserAgent() {
if (!array_key_exists('HTTP_USER_AGENT', $_SERVER))
return "Other";
$uas = $_SERVER['HTTP_USER_AGENT'];
if (preg_match("@Opera/@", $uas))
return "Opera";
if (preg_match("@Firefox/@", $uas))
return "Firefox";
if (preg_match("@Chrome/@", $uas))
return "Chrome";
if (preg_match("@MSIE ([0-9.]+);@", $uas, $matches)) {
if (((float)$matches[1]) >= 7.0)
return "IE";
}
return "Other";
}
/*
* We have 3 options:
* - For FF and Opera, which support RFC 2231, use that format.
* - For IE and Chrome, use attwithfnrawpctenclong
* (http://greenbytes.de/tech/tc2231/#attwithfnrawpctenclong)
* - For the others, convert to ISO-8859-1, if possible
*/
$formatRFC2231 = 'Content-Disposition: attachment; filename*=UTF-8\'\'%s';
$formatDef = 'Content-Disposition: attachment; filename="%s"';
switch (detectUserAgent()) {
case "Opera":
case "Firefox":
$orfilename = rawurlencode($orfilename);
$format = $formatRFC2231;
break;
case "IE":
case "Chrome":
$orfilename = rawurlencode($orfilename);
$format = $formatDef;
break;
default:
if (function_exists('iconv'))
$orfilename =
@iconv("UTF-8", "ISO-8859-1//TRANSLIT", $orfilename);
$format = $formatDef;
}
header(sprintf($format, $orfilename));
//cannot send error messages from now on (headers already sent)
//replace by real content type, perhaps infering from the file extension
$contentType = "application/octet-stream";
header("Content-Type: $contentType");
header("Content-Transfer-Encoding: binary");
header("Content-Length: $filesize");
if ($_SERVER['REQUEST_METHOD'] == "HEAD")
die();
while (!feof($fp)) {
$s = @fread($fp, 8192);
if ($s === false)
break; //useless to send error messages
echo $s;
}
?>
This example opens a RAR file and presents the requested file inside the
RAR archive for download to the client.
Example #2 RAR extension filesystem extraction example
getName() . "\n";
echo 'Packed size: ' . $entry->getPackedSize() . "\n";
echo 'Unpacked size: ' . $entry->getUnpackedSize() . "\n";
$entry->extract('/dir/extract/to/');
}
rar_close($rar_file);
?>
This example opens a RAR file archive and extracts each entry to the
specified directory.
----------------------------------------------------------------------
----------------------------------------------------------------------
Rar Functions
----------------------------------------------------------------------
rar_wrapper_cache_stats
(PECL rar >= 3.0.0)
rar_wrapper_cache_stats - Cache hits and misses for the URL wrapper
Description
string rar_wrapper_cache_stats ( void )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
This function has no parameters.
Return Values
----------------------------------------------------------------------
Table of Contents
* rar_wrapper_cache_stats - Cache hits and misses for the URL wrapper
----------------------------------------------------------------------
----------------------------------------------------------------------
The RarArchive class
Introduction
This class represents a RAR archive, which may be formed by several
volumes (parts) and which contains a number of RAR entries (i.e., files,
directories and other special objects such as symbolic links).
Objects of this class can be traversed, yielding the entries stored in the
respective RAR archive. Those entries can also be obtained through
RarArchive::getEntry() and RarArchive::getEntries().
Class synopsis
final RarArchive implements Traversable {
/* Methods */
public bool close ( void )
public string getComment ( void )
public array getEntries ( void )
public RarEntry getEntry ( string $entryname )
public bool isBroken ( void )
public bool isSolid ( void )
public static RarArchive open ( string $filename [, string $password =
NULL [, callback $volume_callback = NULL ]] )
public bool setAllowBroken ( bool $allow_broken )
public string __toString ( void )
}
----------------------------------------------------------------------
RarArchive::close
rar_close
(PECL rar >= 2.0.0)
RarArchive::close -- rar_close - Close RAR archive and free all resources
Description
Object oriented style (method):
public bool RarArchive::close ( void )
Procedural style:
bool rar_close ( RarArchive $rarfile )
Close RAR archive and free all allocated resources.
Parameters
rarfile
A RarArchive object, opened with rar_open().
Return Values
Returns TRUE on success or FALSE on failure.
Changelog
Version Description
The RAR entries returned by RarArchive::getEntry() and
2.0.0 RarArchive::getEntries() are now invalidated when calling this
method. This means that all instance methods called for such
entries and not guaranteed to succeed.
Examples
Example #1 Object oriented style
close();
echo $rar_arch."\n";
?>
The above example will output something similar to:
RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar"
RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar" (closed)
Example #2 Procedural style
----------------------------------------------------------------------
----------------------------------------------------------------------
RarArchive::getComment
rar_comment_get
(PECL rar >= 2.0.0)
RarArchive::getComment -- rar_comment_get - Get comment text from the RAR
archive
Description
Object oriented style (method):
public string RarArchive::getComment ( void )
Procedural style:
string rar_comment_get ( RarArchive $rarfile )
Get the (global) comment stored in the RAR archive. It may be up to 64 KiB
long.
Note:
This extension does not support comments at the entry level.
Parameters
rarfile
A RarArchive object, opened with rar_open().
Return Values
Returns the comment or NULL if there is none.
Note:
RAR has currently no support for unicode comments. The encoding of the
result of this function is not specified, but it will probably be
Windows-1252.
Examples
Example #1 Object oriented style
getComment();
?>
The above example will output something similar to:
This is the comment of the file commented.rar.
Example #2 Procedural style
----------------------------------------------------------------------
----------------------------------------------------------------------
RarArchive::getEntries
rar_list
(PECL rar >= 2.0.0)
RarArchive::getEntries -- rar_list - Get full list of entries from the RAR
archive
Description
Object oriented style (method):
public array RarArchive::getEntries ( void )
Procedural style:
array rar_list ( RarArchive $rarfile )
Get entries list (files and directories) from the RAR archive.
Note:
If the archive has entries with the same name, this method, together
with RarArchive foreach iteration and array-like access with numeric
indexes, are the only ones to access all the entries (i.e.,
RarArchive::getEntry() and the rar:// wrapper are insufficient).
Parameters
rarfile
A RarArchive object, opened with rar_open().
Return Values
rar_list() returns array of RarEntry objects or FALSE on failure.
Changelog
Version Description
3.0.0 Support for RAR archives with repeated entry names is no longer
defective.
Examples
Example #1 Object oriented style
getEntries();
if ($rar_entries === FALSE)
die("Could retrieve entries.");
echo "Found " . count($rar_entries) . " entries.\n";
foreach ($rar_entries as $e) {
echo $e;
echo "\n";
}
$rar_arch->close();
?>
The above example will output something similar to:
Found 2 entries.
RarEntry for file "tese.txt" (23b93a7a)
RarEntry for file "unrardll.txt" (2ed64b6e)
Example #2 Procedural style
See Also
* RarArchive::getEntry() - Get entry object from the RAR archive
* rar:// wrapper
----------------------------------------------------------------------
----------------------------------------------------------------------
RarArchive::getEntry
rar_entry_get
(PECL rar >= 2.0.0)
RarArchive::getEntry -- rar_entry_get - Get entry object from the RAR
archive
Description
Object oriented style (method):
public RarEntry RarArchive::getEntry ( string $entryname )
Procedural style:
RarEntry rar_entry_get ( RarArchive $rarfile , string $entryname )
Get entry object (file or directory) from the RAR archive.
Note:
You can also get entry objects using RarArchive::getEntries().
Note that a RAR archive can have multiple entries with the same name;
this method will retrieve only the first.
Parameters
rarfile
A RarArchive object, opened with rar_open().
entryname
Path to the entry within the RAR archive.
Note:
The path must be the same returned by RarEntry::getName().
Return Values
Returns the matching RarEntry object or FALSE on failure.
Examples
Example #1 Object oriented style
getEntry('tese.txt');
if ($rar_entry === FALSE)
die("Could get such entry");
echo get_class($rar_entry)."\n";
echo $rar_entry;
$rar_arch->close();
?>
The above example will output something similar to:
RarEntry
RarEntry for file "tese.txt" (23b93a7a)
Example #2 Procedural style
See Also
* RarArchive::getEntries() - Get full list of entries from the RAR
archive
* rar:// wrapper
----------------------------------------------------------------------
----------------------------------------------------------------------
RarArchive::isBroken
rar_broken_is
(PECL rar >= 3.0.0)
RarArchive::isBroken -- rar_broken_is - Test whether an archive is broken
(incomplete)
Description
Object oriented style (method):
public bool RarArchive::isBroken ( void )
Procedural style:
bool rar_broken_is ( RarArchive $rarfile )
This function determines whether an archive is incomplete, i.e., if a
volume is missing or a volume is truncated.
Parameters
rarfile
A RarArchive object, opened with rar_open().
Return Values
Returns TRUE if the archive is broken, FALSE otherwise. This function may
also return FALSE if the passed file has already been closed. The only way
to tell the two cases apart is to enable exceptions with
RarException::setUsingExceptions(); however, this should be unnecessary as
a program should not operate on closed files.
Examples
Example #1 Object oriented style
isBroken());
?>
The above example will output something similar to:
bool(true)
Example #2 Procedural style
See Also
* RarArchive::setAllowBroken() - Whether opening broken archives is
allowed
----------------------------------------------------------------------
----------------------------------------------------------------------
RarArchive::isSolid
rar_solid_is
(PECL rar >= 2.0.0)
RarArchive::isSolid -- rar_solid_is - Check whether the RAR archive is
solid
Description
Object oriented style (method):
public bool RarArchive::isSolid ( void )
Procedural style:
bool rar_solid_is ( RarArchive $rarfile )
Check whether the RAR archive is solid. Individual file extraction is
slower on solid archives.
Parameters
rarfile
A RarArchive object, opened with rar_open().
Return Values
Returns TRUE if the archive is solid, FALSE otherwise.
Examples
Example #1 Object oriented style
isSolid()?'yes':'no') ."\n";
echo "$arch2: " . ($arch2->isSolid()?'yes':'no') . "\n";
?>
The above example will output something similar to:
RAR Archive "C:\php_rar\trunk\tests\store_method.rar": no
RAR Archive "C:\php_rar\trunk\tests\solid.rar": yes
Example #2 Procedural style
----------------------------------------------------------------------
----------------------------------------------------------------------
RarArchive::open
rar_open
(PECL rar >= 2.0.0)
RarArchive::open -- rar_open - Open RAR archive
Description
Object oriented style (method):
public static RarArchive RarArchive::open ( string $filename [, string
$password = NULL [, callback $volume_callback = NULL ]] )
Procedural style:
RarArchive rar_open ( string $filename [, string $password = NULL [,
callback $volume_callback = NULL ]] )
Open specified RAR archive and return RarArchive instance representing it.
Note:
If opening a multi-volume archive, the path of the first volume should
be passed as the first parameter. Otherwise, not all files will be
shown. This is by design.
Parameters
filename
Path to the Rar archive.
password
A plain password, if needed to decrypt the headers. It will also
be used by default if encrypted files are found. Note that the
files may have different passwords in respect to the headers and
among them.
volume_callback
A function that receives one parameter - the path of the volume
that was not found - and returns a string with the correct path
for such volume or NULL if such volume does not exist or is not
known. The programmer should ensure the passed function doesn't
cause loops as this function is called repeatedly if the path
returned in a previous call did not correspond to the needed
volume. Specifying this parameter omits the notice that would
otherwise be emitted whenever a volume is not found; an
implementation that only returns NULL can therefore be used to
merely omit such notices.
Warning
Prior to version 2.0.0, this function would not handle relative paths
correctly. Use realpath() as a workaround.
Return Values
Returns the requested RarArchive instance or FALSE on failure.
Changelog
Version Description
3.0.0 volume_callback was added.
Examples
Example #1 Object oriented style
getEntries();
if ($entries === FALSE)
die("Failed fetching entries");
echo "Found " . count($entries) . " files.\n";
if (empty($entries))
die("No valid entries found.");
$stream = reset($entries)->getStream();
if ($stream === FALSE)
die("Failed opening first file");
$rar_arch->close();
echo "Content of first one follows:\n";
echo stream_get_contents($stream);
fclose($stream);
?>
The above example will output something similar to:
Found 2 files.
Content of first one follows:
Encrypted file 1 contents.
Example #2 Procedural style
getStream();
if ($stream === FALSE)
die("Failed opening first file");
rar_close($rar_arch);
echo "Content of first one follows:\n";
echo stream_get_contents($stream);
fclose($stream);
?>
Example #3 Volume Callback
getEntry('file2.txt');
$entry->extract(null, dirname(__FILE__) . "/temp_file2.txt");
?>
See Also
* rar:// wrapper
----------------------------------------------------------------------
----------------------------------------------------------------------
RarArchive::setAllowBroken
(PECL rar >= 3.0.0)
RarArchive::setAllowBroken - Whether opening broken archives is allowed
Description
Object oriented style (method):
public bool RarArchive::setAllowBroken ( bool $allow_broken )
Procedural style:
bool rar_allow_broken_set ( RarArchive $rarfile , bool $allow_broken )
This method defines whether broken archives can be read or all the
operations that attempt to extract the archive entries will fail. Broken
archives are archives for which no error is detected when the file is
opened but an error occurs when reading the entries.
Parameters
rarfile
A RarArchive object, opened with rar_open().
allow_broken
Whether to allow reading broken files (TRUE) or not (FALSE).
Return Values
Returns TRUE or FALSE on failure. It will only fail if the file has
already been closed.
Examples
Example #1 Object oriented style
setAllowBroken(true);
foreach ($a->getEntries() as $e) {
echo "$e\n";
}
var_dump(count($a));
?>
The above example will output something similar to:
RarEntry for file "file1.txt" (52b28202)
int(1)
Example #2 Procedural style
See Also
* RarArchive::isBroken() - Test whether an archive is broken
(incomplete)
----------------------------------------------------------------------
----------------------------------------------------------------------
RarArchive::__toString
(PECL rar >= 2.0.0)
RarArchive::__toString - Get text representation
Description
public string RarArchive::__toString ( void )
Provides a string representation for this RarArchive object. It currently
shows the full path name of the archive volume that was opened and whether
the resource is valid or was already closed through a call to
RarArchive::close().
This method may be used only for debugging purposes, as there are no
guarantees as to which information the result contains or how it is
formatted.
Parameters
This function has no parameters.
Return Values
A textual representation of this RarArchive object. The content of this
representation is unspecified.
Examples
Example #1 RarArchive::__toString() example
close();
echo $rar_arch."\n";
?>
The above example will output something similar to:
RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar"
RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar" (closed)
----------------------------------------------------------------------
Table of Contents
* RarArchive::close - Close RAR archive and free all resources
* RarArchive::getComment - Get comment text from the RAR archive
* RarArchive::getEntries - Get full list of entries from the RAR archive
* RarArchive::getEntry - Get entry object from the RAR archive
* RarArchive::isBroken - Test whether an archive is broken (incomplete)
* RarArchive::isSolid - Check whether the RAR archive is solid
* RarArchive::open - Open RAR archive
* RarArchive::setAllowBroken - Whether opening broken archives is
allowed
* RarArchive::__toString - Get text representation
----------------------------------------------------------------------
----------------------------------------------------------------------
The RarEntry class
Introduction
A RAR entry, representing a directory or a compressed file inside a RAR
archive.
Class synopsis
final RarEntry {
/* Constants */
const integer HOST_MSDOS = 0 ;
const integer HOST_OS2 = 1 ;
const integer HOST_WIN32 = 2 ;
const integer HOST_UNIX = 3 ;
const integer HOST_MACOS = 4 ;
const integer HOST_BEOS = 5 ;
const integer ATTRIBUTE_WIN_READONLY = 1 ;
const integer ATTRIBUTE_WIN_HIDDEN = 2 ;
const integer ATTRIBUTE_WIN_SYSTEM = 4 ;
const integer ATTRIBUTE_WIN_DIRECTORY = 16 ;
const integer ATTRIBUTE_WIN_ARCHIVE = 32 ;
const integer ATTRIBUTE_WIN_DEVICE = 64 ;
const integer ATTRIBUTE_WIN_NORMAL = 128 ;
const integer ATTRIBUTE_WIN_TEMPORARY = 256 ;
const integer ATTRIBUTE_WIN_SPARSE_FILE = 512 ;
const integer ATTRIBUTE_WIN_REPARSE_POINT = 1024 ;
const integer ATTRIBUTE_WIN_COMPRESSED = 2048 ;
const integer ATTRIBUTE_WIN_OFFLINE = 4096 ;
const integer ATTRIBUTE_WIN_NOT_CONTENT_INDEXED = 8192 ;
const integer ATTRIBUTE_WIN_ENCRYPTED = 16384 ;
const integer ATTRIBUTE_WIN_VIRTUAL = 65536 ;
const integer ATTRIBUTE_UNIX_WORLD_EXECUTE = 1 ;
const integer ATTRIBUTE_UNIX_WORLD_WRITE = 2 ;
const integer ATTRIBUTE_UNIX_WORLD_READ = 4 ;
const integer ATTRIBUTE_UNIX_GROUP_EXECUTE = 8 ;
const integer ATTRIBUTE_UNIX_GROUP_WRITE = 16 ;
const integer ATTRIBUTE_UNIX_GROUP_READ = 32 ;
const integer ATTRIBUTE_UNIX_OWNER_EXECUTE = 64 ;
const integer ATTRIBUTE_UNIX_OWNER_WRITE = 128 ;
const integer ATTRIBUTE_UNIX_OWNER_READ = 256 ;
const integer ATTRIBUTE_UNIX_STICKY = 512 ;
const integer ATTRIBUTE_UNIX_SETGID = 1024 ;
const integer ATTRIBUTE_UNIX_SETUID = 2048 ;
const integer ATTRIBUTE_UNIX_FINAL_QUARTET = 61440 ;
const integer ATTRIBUTE_UNIX_FIFO = 4096 ;
const integer ATTRIBUTE_UNIX_CHAR_DEV = 8192 ;
const integer ATTRIBUTE_UNIX_DIRECTORY = 16384 ;
const integer ATTRIBUTE_UNIX_BLOCK_DEV = 24576 ;
const integer ATTRIBUTE_UNIX_REGULAR_FILE = 32768 ;
const integer ATTRIBUTE_UNIX_SYM_LINK = 40960 ;
const integer ATTRIBUTE_UNIX_SOCKET = 49152 ;
/* Methods */
public bool extract ( string $dir [, string $filepath = '' [, string
$password = NULL [, bool $extended_data = false ]]] )
public int getAttr ( void )
public string getCrc ( void )
public string getFileTime ( void )
public int getHostOs ( void )
public int getMethod ( void )
public string getName ( void )
public int getPackedSize ( void )
public resource getStream ([ string $password ] )
public int getUnpackedSize ( void )
public int getVersion ( void )
public bool isDirectory ( void )
public bool isEncrypted ( void )
public string __toString ( void )
}
Predefined Constants
RarEntry Node Types
RarEntry::HOST_MSDOS
If the return value of RarEntry::getHostOs() equals this constant,
MS-DOS was used to add this entry. Use instead of RAR_HOST_MSDOS.
RarEntry::HOST_OS2
If the return value of RarEntry::getHostOs() equals this constant,
OS/2 was used to add this entry. Intended to replace RAR_HOST_OS2.
RarEntry::HOST_WIN32
If the return value of RarEntry::getHostOs() equals this constant,
Microsoft Windows was used to add this entry. Intended to replace
RAR_HOST_WIN32.
RarEntry::HOST_UNIX
If the return value of RarEntry::getHostOs() equals this constant,
an unspecified UNIX OS was used to add this entry. Intended to
replace RAR_HOST_UNIX.
RarEntry::HOST_MACOS
If the return value of RarEntry::getHostOs() equals this constant,
Mac OS was used to add this entry.
RarEntry::HOST_BEOS
If the return value of RarEntry::getHostOs() equals this constant,
BeOS was used to add this entry. Intended to replace
RAR_HOST_BEOS.
RarEntry::ATTRIBUTE_WIN_READONLY
Bit that represents a Windows entry with a read-only attribute. To
be used with RarEntry::getAttr() on entries whose host OS is
Microsoft Windows.
RarEntry::ATTRIBUTE_WIN_HIDDEN
Bit that represents a Windows entry with a hidden attribute. To be
used with RarEntry::getAttr() on entries whose host OS is
Microsoft Windows.
RarEntry::ATTRIBUTE_WIN_SYSTEM
Bit that represents a Windows entry with a system attribute. To be
used with RarEntry::getAttr() on entries whose host OS is
Microsoft Windows.
RarEntry::ATTRIBUTE_WIN_DIRECTORY
Bit that represents a Windows entry with a directory attribute
(entry is a directory). To be used with RarEntry::getAttr() on
entries whose host OS is Microsoft Windows. See also
RarEntry::isDirectory(), which also works with entries that were
not added in WinRAR.
RarEntry::ATTRIBUTE_WIN_ARCHIVE
Bit that represents a Windows entry with an archive attribute. To
be used with RarEntry::getAttr() on entries whose host OS is
Microsoft Windows.
RarEntry::ATTRIBUTE_WIN_DEVICE
Bit that represents a Windows entry with a device attribute. To be
used with RarEntry::getAttr() on entries whose host OS is
Microsoft Windows.
RarEntry::ATTRIBUTE_WIN_NORMAL
Bit that represents a Windows entry with a normal file attribute
(entry is NOT a directory). To be used with RarEntry::getAttr() on
entries whose host OS is Microsoft Windows. See also
RarEntry::isDirectory(), which also works with entries that were
not added in WinRAR.
RarEntry::ATTRIBUTE_WIN_TEMPORARY
Bit that represents a Windows entry with a temporary attribute. To
be used with RarEntry::getAttr() on entries whose host OS is
Microsoft Windows.
RarEntry::ATTRIBUTE_WIN_SPARSE_FILE
Bit that represents a Windows entry with a sparse file attribute
(file is an NTFS sparse file). To be used with RarEntry::getAttr()
on entries whose host OS is Microsoft Windows.
RarEntry::ATTRIBUTE_WIN_REPARSE_POINT
Bit that represents a Windows entry with a reparse point attribute
(entry is an NTFS reparse point, e.g. a directory junction or a
mount file system). To be used with RarEntry::getAttr() on entries
whose host OS is Microsoft Windows.
RarEntry::ATTRIBUTE_WIN_COMPRESSED
Bit that represents a Windows entry with a compressed attribute
(NTFS only). To be used with RarEntry::getAttr() on entries whose
host OS is Microsoft Windows.
RarEntry::ATTRIBUTE_WIN_OFFLINE
Bit that represents a Windows entry with an offline attribute
(entry is offline and not accessible). To be used with
RarEntry::getAttr() on entries whose host OS is Microsoft Windows.
RarEntry::ATTRIBUTE_WIN_NOT_CONTENT_INDEXED
Bit that represents a Windows entry with a not content indexed
attribute (entry is to be indexed). To be used with
RarEntry::getAttr() on entries whose host OS is Microsoft Windows.
RarEntry::ATTRIBUTE_WIN_ENCRYPTED
Bit that represents a Windows entry with an encrypted attribute
(NTFS only). To be used with RarEntry::getAttr() on entries whose
host OS is Microsoft Windows.
RarEntry::ATTRIBUTE_WIN_VIRTUAL
Bit that represents a Windows entry with a virtual attribute. To
be used with RarEntry::getAttr() on entries whose host OS is
Microsoft Windows.
RarEntry::ATTRIBUTE_UNIX_WORLD_EXECUTE
Bit that represents a UNIX entry that is world executable. To be
used with RarEntry::getAttr() on entries whose host OS is UNIX.
RarEntry::ATTRIBUTE_UNIX_WORLD_WRITE
Bit that represents a UNIX entry that is world writable. To be
used with RarEntry::getAttr() on entries whose host OS is UNIX.
RarEntry::ATTRIBUTE_UNIX_WORLD_READ
Bit that represents a UNIX entry that is world readable. To be
used with RarEntry::getAttr() on entries whose host OS is UNIX.
RarEntry::ATTRIBUTE_UNIX_GROUP_EXECUTE
Bit that represents a UNIX entry that is group executable. To be
used with RarEntry::getAttr() on entries whose host OS is UNIX.
RarEntry::ATTRIBUTE_UNIX_GROUP_WRITE
Bit that represents a UNIX entry that is group writable. To be
used with RarEntry::getAttr() on entries whose host OS is UNIX.
RarEntry::ATTRIBUTE_UNIX_GROUP_READ
Bit that represents a UNIX entry that is group readable. To be
used with RarEntry::getAttr() on entries whose host OS is UNIX.
RarEntry::ATTRIBUTE_UNIX_OWNER_EXECUTE
Bit that represents a UNIX entry that is owner executable. To be
used with RarEntry::getAttr() on entries whose host OS is UNIX.
RarEntry::ATTRIBUTE_UNIX_OWNER_WRITE
Bit that represents a UNIX entry that is owner writable. To be
used with RarEntry::getAttr() on entries whose host OS is UNIX.
RarEntry::ATTRIBUTE_UNIX_OWNER_READ
Bit that represents a UNIX entry that is owner readable. To be
used with RarEntry::getAttr() on entries whose host OS is UNIX.
RarEntry::ATTRIBUTE_UNIX_STICKY
Bit that represents the UNIX sticky bit. To be used with
RarEntry::getAttr() on entries whose host OS is UNIX.
RarEntry::ATTRIBUTE_UNIX_SETGID
Bit that represents the UNIX setgid attribute. To be used with
RarEntry::getAttr() on entries whose host OS is UNIX.
RarEntry::ATTRIBUTE_UNIX_SETUID
Bit that represents the UNIX setuid attribute. To be used with
RarEntry::getAttr() on entries whose host OS is UNIX.
RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET
Mask to isolate the last four bits (nibble) of UNIX attributes
(_S_IFMT, the type of file mask). To be used with
RarEntry::getAttr() on entries whose host OS is UNIX and with the
constants RarEntry::ATTRIBUTE_UNIX_FIFO,
RarEntry::ATTRIBUTE_UNIX_CHAR_DEV,
RarEntry::ATTRIBUTE_UNIX_DIRECTORY,
RarEntry::ATTRIBUTE_UNIX_BLOCK_DEV,
RarEntry::ATTRIBUTE_UNIX_REGULAR_FILE,
RarEntry::ATTRIBUTE_UNIX_SYM_LINK and
RarEntry::ATTRIBUTE_UNIX_SOCKET.
RarEntry::ATTRIBUTE_UNIX_FIFO
Unix FIFOs will have attributes whose last four bits have this
value. To be used with RarEntry::getAttr() on entries whose host
OS is UNIX and with the constant
RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.
RarEntry::ATTRIBUTE_UNIX_CHAR_DEV
Unix character devices will have attributes whose last four bits
have this value. To be used with RarEntry::getAttr() on entries
whose host OS is UNIX and with the constant
RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.
RarEntry::ATTRIBUTE_UNIX_DIRECTORY
Unix directories will have attributes whose last four bits have
this value. To be used with RarEntry::getAttr() on entries whose
host OS is UNIX and with the constant
RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET. See also
RarEntry::isDirectory(), which also works with entries that were
added in other operating systems.
RarEntry::ATTRIBUTE_UNIX_BLOCK_DEV
Unix block devices will have attributes whose last four bits have
this value. To be used with RarEntry::getAttr() on entries whose
host OS is UNIX and with the constant
RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.
RarEntry::ATTRIBUTE_UNIX_REGULAR_FILE
Unix regular files (not directories) will have attributes whose
last four bits have this value. To be used with
RarEntry::getAttr() on entries whose host OS is UNIX and with the
constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET. See also
RarEntry::isDirectory(), which also works with entries that were
added in other operating systems.
RarEntry::ATTRIBUTE_UNIX_SYM_LINK
Unix symbolic links will have attributes whose last four bits have
this value. To be used with RarEntry::getAttr() on entries whose
host OS is UNIX and with the constant
RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.
RarEntry::ATTRIBUTE_UNIX_SOCKET
Unix sockets will have attributes whose last four bits have this
value. To be used with RarEntry::getAttr() on entries whose host
OS is UNIX and with the constant
RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.
----------------------------------------------------------------------
RarEntry::extract
(PECL rar >= 0.1)
RarEntry::extract - Extract entry from the archive
Description
public bool RarEntry::extract ( string $dir [, string $filepath = '' [,
string $password = NULL [, bool $extended_data = false ]]] )
RarEntry::extract() extracts the entry's data. It will create new file in
the specified dir with the name identical to the entry's name, unless the
second argument is specified. See below for more information.
Parameters
dir
Path to the directory where files should be extracted. This
parameter is considered if and only if filepath is not. If both
parameters are empty an extraction to the current directory will
be attempted.
filepath
Path (relative or absolute) containing the directory and filename
of the extracted file. This parameter overrides both the parameter
dir and the original file name.
password
The password used to encrypt this entry. If the entry is not
encrypted, this value will not be used and can be omitted. If this
parameter is omitted and the entry is encrypted, the password
given to rar_open(), if any, will be used. If a wrong password is
given, either explicitly or implicitly via rar_open(), CRC
checking will fail and this method will fail and return FALSE. If
no password is given and one is required, this method will fail
and return FALSE. You can check whether an entry is encrypted with
RarEntry::isEncrypted().
extended_data
If TRUE, extended information such as NTFS ACLs and Unix owner
information will be set in the extract files, as long as it's
present in the archive.
Warning
Prior to version 2.0.0, this function would not handle relative paths
correctly. Use realpath() as a workaround.
Return Values
Returns TRUE on success or FALSE on failure.
Changelog
Version Description
3.0.0 extended_data was added.
3.0.0 Support for RAR archives with repeated entry names is no longer
defective.
Examples
Example #1 RarEntry::extract() example
extract('/dir/to'); // create /dir/to/Dir/file.txt
$entry->extract(false, '/dir/to/new_name.txt'); // create /dir/to/new_name.txt
?>
Example #2 How to extract all files in archive:
extract("."); // extract to the current dir
}
rar_close($rar_file);
?>
See Also
* RarEntry::getStream() - Get file handler for entry
* rar:// wrapper
----------------------------------------------------------------------
----------------------------------------------------------------------
RarEntry::getAttr
(PECL rar >= 0.1)
RarEntry::getAttr - Get attributes of the entry
Description
public int RarEntry::getAttr ( void )
Returns the OS-dependent attributes of the archive entry.
Parameters
This function has no parameters.
Return Values
Returns the attributes or FALSE on error.
Examples
Example #1 RarEntry::getAttr() example
getHostOs();
$attr = $entry->getAttr();
switch($host_os) {
case RAR_HOST_MSDOS:
case RAR_HOST_OS2:
case RAR_HOST_WIN32:
case RAR_HOST_MACOS:
printf("%c%c%c%c%c%c\n",
($attr & 0x08) ? 'V' : '.',
($attr & 0x10) ? 'D' : '.',
($attr & 0x01) ? 'R' : '.',
($attr & 0x02) ? 'H' : '.',
($attr & 0x04) ? 'S' : '.',
($attr & 0x20) ? 'A' : '.');
break;
case RAR_HOST_UNIX:
case RAR_HOST_BEOS:
switch ($attr & 0xF000)
{
case 0x4000:
printf("d");
break;
case 0xA000:
printf("l");
break;
default:
printf("-");
break;
}
printf("%c%c%c%c%c%c%c%c%c\n",
($attr & 0x0100) ? 'r' : '-',
($attr & 0x0080) ? 'w' : '-',
($attr & 0x0040) ? (($attr & 0x0800) ? 's':'x'):(($attr & 0x0800) ? 'S':'-'),
($attr & 0x0020) ? 'r' : '-',
($attr & 0x0010) ? 'w' : '-',
($attr & 0x0008) ? (($attr & 0x0400) ? 's':'x'):(($attr & 0x0400) ? 'S':'-'),
($attr & 0x0004) ? 'r' : '-',
($attr & 0x0002) ? 'w' : '-',
($attr & 0x0001) ? 'x' : '-');
break;
}
rar_close($rar_file);
?>
See Also
* RarEntry::getHostOs() - Get entry host OS
* The constants in RarEntry
----------------------------------------------------------------------
----------------------------------------------------------------------
RarEntry::getCrc
(PECL rar >= 0.1)
RarEntry::getCrc - Get CRC of the entry
Description
public string RarEntry::getCrc ( void )
Returns an hexadecimal string representation of the CRC of the archive
entry.
Parameters
This function has no parameters.
Return Values
Returns the CRC of the archive entry or FALSE on error.
Changelog
Version Description
2.0.0 This method now returns correct values for multiple volume
archives.
----------------------------------------------------------------------
----------------------------------------------------------------------
RarEntry::getFileTime
(PECL rar >= 0.1)
RarEntry::getFileTime - Get entry last modification time
Description
public string RarEntry::getFileTime ( void )
Gets entry last modification time.
Parameters
This function has no parameters.
Return Values
Returns entry last modification time as string in format YYYY-MM-DD
HH:II:SS, or FALSE on error.
----------------------------------------------------------------------
----------------------------------------------------------------------
RarEntry::getHostOs
(PECL rar >= 0.1)
RarEntry::getHostOs - Get entry host OS
Description
public int RarEntry::getHostOs ( void )
Returns the code of the host OS of the archive entry.
Parameters
This function has no parameters.
Return Values
Returns the code of the host OS, or FALSE on error.
Examples
Example #1 RarEntry::getHostOs() example (version >= 2.0.0)
getHostOs()) {
case RarEntry::HOST_MSDOS:
echo "MS-DOS\n";
break;
case RarEntry::HOST_OS2:
echo "OS2\n";
break;
case RarEntry::HOST_WIN32:
echo "Win32\n";
break;
case RarEntry::HOST_MACOS:
echo "MacOS\n";
break;
case RarEntry::HOST_UNIX:
echo "Unix/Linux\n";
break;
case RarEntry::HOST_BEOS:
echo "BeOS\n";
break;
}
?>
Example #2 RarEntry::getHostOs() example (version <= 1.0.0)
getHostOs()) {
case RAR_HOST_MSDOS:
echo "MS-DOS\n";
break;
case RAR_HOST_OS2:
echo "OS2\n";
break;
case RAR_HOST_WIN32:
echo "Win32\n";
break;
case RAR_HOST_MACOS:
echo "MacOS\n";
break;
case RAR_HOST_UNIX:
echo "Unix/Linux\n";
break;
case RAR_HOST_BEOS:
echo "BeOS\n";
break;
}
?>
See Also
* RarEntry::extract() - Extract entry from the archive
----------------------------------------------------------------------
----------------------------------------------------------------------
RarEntry::getMethod
(PECL rar >= 0.1)
RarEntry::getMethod - Get pack method of the entry
Description
public int RarEntry::getMethod ( void )
RarEntry::getMethod() returns number of the method used when adding
current archive entry.
Parameters
This function has no parameters.
Return Values
Returns the method number or FALSE on error.
Examples
Example #1 RarEntry::getMethod() example
getMethod();
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
RarEntry::getName
(PECL rar >= 0.1)
RarEntry::getName - Get name of the entry
Description
public string RarEntry::getName ( void )
Returns the name (with path) of the archive entry.
Parameters
This function has no parameters.
Return Values
Returns the entry name as a string, or FALSE on error.
Changelog
Version Description
2.0.0 As of version 2.0.0, the returned string is encoded in
Unicode/UTF-8.
Examples
Example #1 RarEntry::getName() example
getName(),
ENT_COMPAT,
"UTF-8"
),
"HTML-ENTITIES",
"UTF-8"
);
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
RarEntry::getPackedSize
(PECL rar >= 0.1)
RarEntry::getPackedSize - Get packed size of the entry
Description
public int RarEntry::getPackedSize ( void )
Get packed size of the archive entry.
Note:
Note that on platforms with 32-bit longs (that includes Windows x64),
the maximum size returned is capped at 2 GiB. Check the constant
PHP_INT_MAX.
Parameters
This function has no parameters.
Return Values
Returns the packed size, or FALSE on error.
Changelog
Version Description
This method now returns correct values of packed sizes bigger than
2.0.0 2 GiB on platforms with 64-bit integers and never returns negative
values on other platforms.
Examples
Example #1 RarEntry::getPackedSize() example
getName() . " = " . $entry->getPackedSize() . " bytes";
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
RarEntry::getStream
(PECL rar >= 2.0.0)
RarEntry::getStream - Get file handler for entry
Description
public resource RarEntry::getStream ([ string $password ] )
Returns a file handler that supports read operations. This handler
provides on-the-fly decompression for this entry.
The handler is not invalidated by calling rar_close().
Warning
The resulting stream has no integrity verification. In particular, file
corruption and decryption with a wrong a key will not be detected. It is
the programmer's responsability to use the entry's CRC to check for
integrity, if he so wishes.
Parameters
password
The password used to encrypt this entry. If the entry is not
encrypted, this value will not be used and can be omitted. If this
parameter is omitted and the entry is encrypted, the password
given to rar_open(), if any, will be used. If a wrong password is
given, either explicitly or implicitly via rar_open(), this
method's resulting stream will produce wrong output. If no
password is given and one is required, this method will fail and
return FALSE. You can check whether an entry is encrypted with
RarEntry::isEncrypted().
Return Values
The file handler or FALSE on failure.
Changelog
Version Description
3.0.0 Support for RAR archives with repeated entry names is no longer
defective.
Examples
Example #1 RarEntry::getStream() example
getStream();
if ($stream === false)
die("Failed to obtain stream.");
rar_close($rar_file); //stream is independent from file
while (!feof($stream)) {
$buff = fread($stream, 8192);
if ($buff !== false)
echo $buff;
else
break; //fread error
}
fclose($stream);
?>
See Also
* RarEntry::extract() - Extract entry from the archive
* rar:// wrapper
----------------------------------------------------------------------
----------------------------------------------------------------------
RarEntry::getUnpackedSize
(PECL rar >= 0.1)
RarEntry::getUnpackedSize - Get unpacked size of the entry
Description
public int RarEntry::getUnpackedSize ( void )
Get unpacked size of the archive entry.
Note:
Note that on platforms with 32-bit longs (that includes Windows x64),
the maximum size returned is capped at 2 GiB. Check the constant
PHP_INT_MAX.
Parameters
This function has no parameters.
Return Values
Returns the unpacked size, or FALSE on error.
Changelog
Version Description
This method now returns correct values of unpacked sizes bigger
2.0.0 than 2 GiB on platforms with 64-bit integers and never returns
negative values on other platforms.
Return Values
Example #1 RarEntry::getUnpackedSize() example
getName() . " = " . $entry->getPackedSize() . " bytes";
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
RarEntry::getVersion
(PECL rar >= 0.1)
RarEntry::getVersion - Get minimum version of RAR program required to
unpack the entry
Description
public int RarEntry::getVersion ( void )
Returns minimum version of RAR program (e.g. WinRAR) required to unpack
the entry. It is encoded as 10 * major version + minor version.
Parameters
This function has no parameters.
Return Values
Returns the version or FALSE on error.
Examples
Example #1 RarEntry::getVersion() example
getVersion();
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
RarEntry::isDirectory
(PECL rar >= 2.0.0)
RarEntry::isDirectory - Test whether an entry represents a directory
Description
public bool RarEntry::isDirectory ( void )
Tests whether the current entry is a directory.
Parameters
This function has no parameters.
Return Values
Returns TRUE if this entry is a directory and FALSE otherwise.
Notes
This function is only available starting with version 2.0.0, but one can
also test whether an entry is a directory by checking the entry
attributes, like this (only works for files compressed in RAR for Windows
or Unix):
getHostOs() == RAR_HOST_WIN32) && ($e->getAttr() & 0x10)) ||
(($e->getHostOs() == RAR_HOST_UNIX) && (($e->getAttr() & 0xf000) == 0x4000)));
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
RarEntry::isEncrypted
(PECL rar >= 2.0.0)
RarEntry::isEncrypted - Test whether an entry is encrypted
Description
public bool RarEntry::isEncrypted ( void )
Tests whether the current entry contents are encrypted.
Note:
The password used may differ between files inside the same RAR archive.
Parameters
This function has no parameters.
Return Values
Returns TRUE if the current entry is encrypted and FALSE otherwise.
----------------------------------------------------------------------
----------------------------------------------------------------------
RarEntry::__toString
(PECL rar >= 2.0.0)
RarEntry::__toString - Get text representation of entry
Description
public string RarEntry::__toString ( void )
RarEntry::__toString() returns a textual representation for this entry. It
includes whether the entry is a file or a directory (symbolic links and
other special objects will be treated as files), the UTF-8 name of the
entry and its CRC. The form and content of this representation may be
changed in the future, so they cannot be relied upon.
Parameters
This function has no parameters.
Return Values
A textual representation for the entry.
----------------------------------------------------------------------
Table of Contents
* RarEntry::extract - Extract entry from the archive
* RarEntry::getAttr - Get attributes of the entry
* RarEntry::getCrc - Get CRC of the entry
* RarEntry::getFileTime - Get entry last modification time
* RarEntry::getHostOs - Get entry host OS
* RarEntry::getMethod - Get pack method of the entry
* RarEntry::getName - Get name of the entry
* RarEntry::getPackedSize - Get packed size of the entry
* RarEntry::getStream - Get file handler for entry
* RarEntry::getUnpackedSize - Get unpacked size of the entry
* RarEntry::getVersion - Get minimum version of RAR program required to
unpack the entry
* RarEntry::isDirectory - Test whether an entry represents a directory
* RarEntry::isEncrypted - Test whether an entry is encrypted
* RarEntry::__toString - Get text representation of entry
----------------------------------------------------------------------
----------------------------------------------------------------------
The RarException class
Introduction
This class serves two purposes: it is the type of the exceptions thrown by
the RAR extension functions and methods and it allows, through static
methods to query and define the error behaviour of the extension, i.e.,
whether exceptions are thrown or only warnings are emitted.
The following error codes are used:
* -1 - error outside UnRAR library
* 11 - insufficient memory
* 12 - bad data
* 13 - bad archive
* 14 - unknown format
* 15 - file open error
* 16 - file create error
* 17 - file close error
* 18 - read error
* 19 - write error
* 20 - buffer too small
* 21 - unkown RAR error
* 22 - password required but not given
Class synopsis
final RarException extends Exception {
/* Methods */
public static bool isUsingExceptions ( void )
public static void setUsingExceptions ( bool $using_exceptions )
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}
----------------------------------------------------------------------
RarException::isUsingExceptions
(PECL rar >= 2.0.0)
RarException::isUsingExceptions - Check whether error handling with
exceptions is in use
Description
public static bool RarException::isUsingExceptions ( void )
Checks whether the RAR functions will emit warnings and return error
values or whether they will throw exceptions in most of the circumstances
(does not include some programmatic errors such as passing the wrong type
of arguments).
Parameters
This function has no parameters.
Return Values
Returns TRUE if exceptions are being used, FALSE otherwise.
Examples
Example #1 RarException::isUsingExceptions() example
The above example will output something similar to:
bool(false)
See Also
* RarException::setUsingExceptions() - Activate and deactivate error
handling with exceptions
----------------------------------------------------------------------
----------------------------------------------------------------------
RarException::setUsingExceptions
(PECL rar >= 2.0.0)
RarException::setUsingExceptions - Activate and deactivate error handling
with exceptions
Description
public static void RarException::setUsingExceptions ( bool
$using_exceptions )
If and only if the argument is TRUE, then, instead of emitting warnings
and returning a special value indicating error when the UnRAR library
encounters an error, an exception of type RarException will be thrown.
Exceptions will also be thrown for the following errors, which occur
outside the library (their error code will be -1):
* attempting some operations on a closed RarArchive object or a RarEntry
object relative to the first;
* attempting to get an entry that does not exist with
RarArchive::getEntry().
Parameters
using_exceptions
Should be TRUE to activate exception throwing, FALSE to deactivate
(the default).
Examples
Example #1 RarException::setUsingExceptions() example
The above example will output something similar to:
bool(false)
Warning: RarArchive::open(): Failed to open does_not_exist.rar: ERAR_EOPEN (file open error) in C:\php_rar\trunk\tests\test.php on line 3
bool(false)
bool(true)
Fatal error: Uncaught exception 'RarException' with message 'unRAR internal error: Failed to open does_not_exist.rar: ERAR_EOPEN (file open error)' in C:\php_rar\trunk\tests\test.php:8
Stack trace:
#0 C:\php_rar\trunk\tests\test.php(8): RarArchive::open('does_not_exist....')
#1 {main}
thrown in C:\php_rar\trunk\tests\test.php on line 8
See Also
* RarException::isUsingExceptions() - Check whether error handling with
exceptions is in use
----------------------------------------------------------------------
Table of Contents
* RarException::isUsingExceptions - Check whether error handling with
exceptions is in use
* RarException::setUsingExceptions - Activate and deactivate error
handling with exceptions
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* Rar Functions
* rar_wrapper_cache_stats - Cache hits and misses for the URL
wrapper
* RarArchive - The RarArchive class
* RarArchive::close - Close RAR archive and free all resources
* RarArchive::getComment - Get comment text from the RAR archive
* RarArchive::getEntries - Get full list of entries from the RAR
archive
* RarArchive::getEntry - Get entry object from the RAR archive
* RarArchive::isBroken - Test whether an archive is broken
(incomplete)
* RarArchive::isSolid - Check whether the RAR archive is solid
* RarArchive::open - Open RAR archive
* RarArchive::setAllowBroken - Whether opening broken archives is
allowed
* RarArchive::__toString - Get text representation
* RarEntry - The RarEntry class
* RarEntry::extract - Extract entry from the archive
* RarEntry::getAttr - Get attributes of the entry
* RarEntry::getCrc - Get CRC of the entry
* RarEntry::getFileTime - Get entry last modification time
* RarEntry::getHostOs - Get entry host OS
* RarEntry::getMethod - Get pack method of the entry
* RarEntry::getName - Get name of the entry
* RarEntry::getPackedSize - Get packed size of the entry
* RarEntry::getStream - Get file handler for entry
* RarEntry::getUnpackedSize - Get unpacked size of the entry
* RarEntry::getVersion - Get minimum version of RAR program
required to unpack the entry
* RarEntry::isDirectory - Test whether an entry represents a
directory
* RarEntry::isEncrypted - Test whether an entry is encrypted
* RarEntry::__toString - Get text representation of entry
* RarException - The RarException class
* RarException::isUsingExceptions - Check whether error handling
with exceptions is in use
* RarException::setUsingExceptions - Activate and deactivate error
handling with exceptions
----------------------------------------------------------------------
----------------------------------------------------------------------
Zip
----------------------------------------------------------------------
Introduction
This extension enables you to transparently read or write ZIP compressed
archives and the files inside them.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
PHP 4
The bundled PHP 4 version requires >> ZZIPlib, by Guido Draheim, version
0.10.6 or later
PHP 5.2.0 or later
This extension uses the functions of >> zlib by Jean-loup Gailly and Mark
Adler.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
PHP 4
Note:
Zip support before PHP 4.1.0 is experimental.
Warning
Because the PHP 4 zip extension is unmaintained we recommend that the PECL
extension is used rather than the bundled one.
Linux systems
In order to use these functions you must compile PHP with zip support by
using the --with-zip[=DIR] configure option, where [DIR] is the prefix of
the >> ZZIPlib library install.
Windows
Windows users need to enable php_zip.dll inside of php.ini in order to use
these functions.
PHP 5.2.0 and later
Linux systems
In order to use these functions you must compile PHP with zip support by
using the --enable-zip configure option.
Windows
Windows users need to enable php_zip.dll inside of php.ini in order to use
these functions.
Installation via PECL
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here: >> http://pecl.php.net/package/zip.
A DLL for this PECL extension is currently unavailable. See also the
building on Windows section.
In PHP 4 this DLL resides in the extensions/ directory within the PHP
Windows binaries download.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
There are two resource types used in the Zip module. The first one is the
Zip directory for the Zip archive, the second Zip Entry for the archive
entries.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
ZipArchive uses class constants. There are three types of constants :
Flags (prefixed with FL_), errors (prefixed with ER_) and mode (no
prefix).
ZIPARCHIVE::CREATE (integer)
Create the archive if it does not exist.
ZIPARCHIVE::OVERWRITE (integer)
Always start a new archive, this mode will overwrite the file if
it already exists.
ZIPARCHIVE::EXCL (integer)
Error if archive already exists.
ZIPARCHIVE::CHECKCONS (integer)
Perform additional consistency checks on the archive, and error if
they fail.
ZIPARCHIVE::FL_NOCASE (integer)
Ignore case on name lookup
ZIPARCHIVE::FL_NODIR (integer)
Ignore directory component
ZIPARCHIVE::FL_COMPRESSED (integer)
Read compressed data
ZIPARCHIVE::FL_UNCHANGED (integer)
Use original data, ignoring changes.
ZIPARCHIVE::CM_DEFAULT (integer)
better of deflate or store.
ZIPARCHIVE::CM_STORE (integer)
stored (uncompressed).
ZIPARCHIVE::CM_SHRINK (integer)
shrunk
ZIPARCHIVE::CM_REDUCE_1 (integer)
reduced with factor 1
ZIPARCHIVE::CM_REDUCE_2 (integer)
reduced with factor 2
ZIPARCHIVE::CM_REDUCE_3 (integer)
reduced with factor 3
ZIPARCHIVE::CM_REDUCE_4 (integer)
reduced with factor 4
ZIPARCHIVE::CM_IMPLODE (integer)
imploded
ZIPARCHIVE::CM_DEFLATE (integer)
deflated
ZIPARCHIVE::CM_DEFLATE64 (integer)
deflate64
ZIPARCHIVE::CM_PKWARE_IMPLODE (integer)
PKWARE imploding
ZIPARCHIVE::CM_BZIP2 (integer)
BZIP2 algorithm
ZIPARCHIVE::ER_OK (integer)
No error.
ZIPARCHIVE::ER_MULTIDISK (integer)
Multi-disk zip archives not supported.
ZIPARCHIVE::ER_RENAME (integer)
Renaming temporary file failed.
ZIPARCHIVE::ER_CLOSE (integer)
Closing zip archive failed
ZIPARCHIVE::ER_SEEK (integer)
Seek error
ZIPARCHIVE::ER_READ (integer)
Read error
ZIPARCHIVE::ER_WRITE (integer)
Write error
ZIPARCHIVE::ER_CRC (integer)
CRC error
ZIPARCHIVE::ER_ZIPCLOSED (integer)
Containing zip archive was closed
ZIPARCHIVE::ER_NOENT (integer)
No such file.
ZIPARCHIVE::ER_EXISTS (integer)
File already exists
ZIPARCHIVE::ER_OPEN (integer)
Can't open file
ZIPARCHIVE::ER_TMPOPEN (integer)
Failure to create temporary file.
ZIPARCHIVE::ER_ZLIB (integer)
Zlib error
ZIPARCHIVE::ER_MEMORY (integer)
Memory allocation failure
ZIPARCHIVE::ER_CHANGED (string)
Entry has been changed
ZIPARCHIVE::ER_COMPNOTSUPP (integer)
Compression method not supported.
ZIPARCHIVE::ER_EOF (integer)
Premature EOF
ZIPARCHIVE::ER_INVAL (integer)
Invalid argument
ZIPARCHIVE::ER_NOZIP (integer)
Not a zip archive
ZIPARCHIVE::ER_INTERNAL (integer)
Internal error
ZIPARCHIVE::ER_INCONS (integer)
Zip archive inconsistent
ZIPARCHIVE::ER_REMOVE (integer)
Can't remove file
ZIPARCHIVE::ER_DELETED (integer)
Entry has been deleted
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Example #1 Create a Zip archive
open($filename, ZIPARCHIVE::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}
$zip->addFromString("testfilephp.txt" . time(), "#1 This is a test string added as testfilephp.txt.\n");
$zip->addFromString("testfilephp2.txt" . time(), "#2 This is a test string added as testfilephp2.txt.\n");
$zip->addFile($thisdir . "/too.php","/testfromfile.php");
echo "numfiles: " . $zip->numFiles . "\n";
echo "status:" . $zip->status . "\n";
$zip->close();
?>
Example #2 Dump the archive details and listing
open('test_with_comment.zip');
print_r($za);
var_dump($za);
echo "numFiles: " . $za->numFiles . "\n";
echo "status: " . $za->status . "\n";
echo "statusSys: " . $za->statusSys . "\n";
echo "filename: " . $za->filename . "\n";
echo "comment: " . $za->comment . "\n";
for ($i=0; $i<$za->numFiles;$i++) {
echo "index: $i\n";
print_r($za->statIndex($i));
}
echo "numFile:" . $za->numFiles . "\n";
?>
Example #3 Zip stream wrapper, read an OpenOffice meta info
open('zip://' . dirname(__FILE__) . '/test.odt#meta.xml');
$odt_meta = array();
while ($reader->read()) {
if ($reader->nodeType == XMLREADER::ELEMENT) {
$elm = $reader->name;
} else {
if ($reader->nodeType == XMLREADER::END_ELEMENT && $reader->name == 'office:meta') {
break;
}
if (!trim($reader->value)) {
continue;
}
$odt_meta[$elm] = $reader->value;
}
}
print_r($odt_meta);
?>
This example uses the old API (PHP 4), it opens a ZIP file archive, reads
each file in the archive and prints out its contents. The test2.zip
archive used in this example is one of the test archives in the ZZIPlib
source distribution.
Example #4 Zip Usage Example
----------------------------------------------------------------------
----------------------------------------------------------------------
The ZipArchive class
Introduction
A file archive, compressed with Zip.
Class synopsis
ZipArchive {
/* Properties */
/* Methods */
bool addEmptyDir ( string $dirname )
bool addFile ( string $filename [, string $localname = NULL [, int $start
= 0 [, int $length = 0 ]]] )
bool addFromString ( string $localname , string $contents )
bool close ( void )
bool deleteIndex ( int $index )
bool deleteName ( string $name )
bool extractTo ( string $destination [, mixed $entries ] )
string getArchiveComment ([ int $flags ] )
string getCommentIndex ( int $index [, int $flags ] )
string getCommentName ( string $name [, int $flags ] )
mixed getFromIndex ( int $index [, int $length = 0 [, int $flags ]] )
mixed getFromName ( string $name [, int $length = 0 [, int $flags ]] )
string getNameIndex ( int $index [, int $flags ] )
string getStatusString ( void )
resource getStream ( string $name )
mixed locateName ( string $name [, int $flags ] )
mixed open ( string $filename [, int $flags ] )
bool renameIndex ( int $index , string $newname )
bool renameName ( string $name , string $newname )
mixed setArchiveComment ( string $comment )
mixed setCommentIndex ( int $index , string $comment )
mixed setCommentName ( string $name , string $comment )
mixed statIndex ( int $index [, int $flags ] )
mixed statName ( name $name [, int $flags ] )
mixed unchangeAll ( void )
mixed unchangeArchive ( void )
mixed unchangeIndex ( int $index )
mixed unchangeName ( string $name )
}
Properties
status
Status of the Zip Archive
statusSys
System status of the Zip Archive
numFiles
Number of files in archive
filename
File name in the file system
comment
Comment for the archive
----------------------------------------------------------------------
ZipArchive::addEmptyDir
(PHP 5 >= 5.2.0, PECL zip >= 1.8.0)
ZipArchive::addEmptyDir - Add a new directory
Description
bool ZipArchive::addEmptyDir ( string $dirname )
Adds an empty directory in the archive.
Parameters
dirname
The directory to add.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Create a new directory in an archive
open('test.zip') === TRUE) {
if($zip->addEmptyDir('newDirectory')) {
echo 'Created a new root directory';
} else {
echo 'Could not create the directory';
}
$zip->close();
} else {
echo 'failed';
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::addFile
(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)
ZipArchive::addFile - Adds a file to a ZIP archive from the given path
Description
bool ZipArchive::addFile ( string $filename [, string $localname = NULL [,
int $start = 0 [, int $length = 0 ]]] )
Adds a file to a ZIP archive from a given path.
Parameters
filename
The path to the file to add.
localname
If supplied, this is the local name inside the ZIP archive that
will override the filename.
start
This parameter is not used but is required to extend ZipArchive.
length
This parameter is not used but is required to extend ZipArchive.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
This example opens a ZIP file archive test.zip and add the file
/path/to/index.txt. as newname.txt.
Example #1 Open and extract
open('test.zip') === TRUE) {
$zip->addFile('/path/to/index.txt', 'newname.txt');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>
Notes
Note:
When a file is set to be added to the archive, PHP will attempt to lock
the file and it is only released once the ZIP operation is done. In
short, it means you can first delete an added file after the archive is
closed.
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::addFromString
(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)
ZipArchive::addFromString - Add a file to a ZIP archive using its contents
Description
bool ZipArchive::addFromString ( string $localname , string $contents )
Add a file to a ZIP archive using its contents.
Parameters
localname
The name of the entry to create.
contents
The contents to use to create the entry. It is used in a binary
safe mode.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Add an entry to a new archive
open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('test.txt', 'file content goes here');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>
Example #2 Add file to a directory inside an archive
open('test.zip') === TRUE) {
$zip->addFromString('dir/test.txt', 'file content goes here');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::close
(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)
ZipArchive::close - Close the active archive (opened or newly created)
Description
bool ZipArchive::close ( void )
Close opened or created archive and save changes. This method is
automatically called at the end of the script.
Parameters
This function has no parameters.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::deleteIndex
(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)
ZipArchive::deleteIndex - delete an entry in the archive using its index
Description
bool ZipArchive::deleteIndex ( int $index )
Delete an entry in the archive using its index.
Parameters
index
Index of the entry to delete.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Delete file from archive using its index
open('test.zip') === TRUE) {
$zip->deleteIndex(2);
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::deleteName
(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)
ZipArchive::deleteName - delete an entry in the archive using its name
Description
bool ZipArchive::deleteName ( string $name )
Delete an entry in the archive using its name.
Parameters
name
Name of the entry to delete.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Deleting a file and directory from an archive, using names
open('test1.zip') === TRUE) {
$zip->deleteName('testfromfile.php');
$zip->deleteName('testDir/');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::extractTo
(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)
ZipArchive::extractTo - Extract the archive contents
Description
bool ZipArchive::extractTo ( string $destination [, mixed $entries ] )
Extract the complete archive or the given files to the specified
destination.
Parameters
destination
Location where to extract the files.
entries
The entries to extract. It accepts either a single entry name or
an array of names.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Extract all entries
open('test.zip') === TRUE) {
$zip->extractTo('/my/destination/dir/');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>
Example #2 Extract two entries
open('test_im.zip');
if ($res === TRUE) {
$zip->extractTo('/my/destination/dir/', array('pear_item.gif', 'testfromfile.php'));
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::getArchiveComment
(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)
ZipArchive::getArchiveComment - Returns the Zip archive comment
Description
string ZipArchive::getArchiveComment ([ int $flags ] )
Returns the Zip archive comment.
Parameters
flags
If flags is set to ZIPARCHIVE::FL_UNCHANGED, the original
unchanged comment is returned.
Return Values
Returns the Zip archive comment or FALSE on failure.
Examples
Example #1 Dump an archive comment
open('test_with_comment.zip');
if ($res === TRUE) {
var_dump($zip->getArchiveComment());
/* Or using the archive property */
var_dump($zip->comment);
} else {
echo 'failed, code:' . $res;
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::getCommentIndex
(PHP 5 >= 5.2.0, PECL zip >= 1.4.0)
ZipArchive::getCommentIndex - Returns the comment of an entry using the
entry index
Description
string ZipArchive::getCommentIndex ( int $index [, int $flags ] )
Returns the comment of an entry using the entry index.
Parameters
index
Index of the entry
flags
If flags is set to ZIPARCHIVE::FL_UNCHANGED, the original
unchanged comment is returned.
Return Values
Returns the comment on success or FALSE on failure.
Examples
Example #1 Dump an entry comment
open('test1.zip');
if ($res === TRUE) {
var_dump($zip->getCommentIndex(1));
} else {
echo 'failed, code:' . $res;
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::getCommentName
(PHP 5 >= 5.2.0, PECL zip >= 1.4.0)
ZipArchive::getCommentName - Returns the comment of an entry using the
entry name
Description
string ZipArchive::getCommentName ( string $name [, int $flags ] )
Returns the comment of an entry using the entry name.
Parameters
name
Name of the entry
flags
If flags is set to ZIPARCHIVE::FL_UNCHANGED, the original
unchanged comment is returned.
Return Values
Returns the comment on success or FALSE on failure.
Examples
Example #1 Dump an entry comment
open('test1.zip');
if ($res === TRUE) {
var_dump($zip->getCommentName('test/entry1.txt'));
} else {
echo 'failed, code:' . $res;
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::getFromIndex
(PHP 5 >= 5.2.0, PECL zip >= 1.3.0)
ZipArchive::getFromIndex - Returns the entry contents using its index
Description
mixed ZipArchive::getFromIndex ( int $index [, int $length = 0 [, int
$flags ]] )
Returns the entry contents using its index.
Parameters
index
Index of the entry
length
The length to be read from the entry. If 0, then the entire entry
is read.
flags
The flags to use to open the archive. the following values may be
ORed to it.
* ZIPARCHIVE::FL_UNCHANGED
* ZIPARCHIVE::FL_COMPRESSED
Return Values
Returns the contents of the entry on success or FALSE on failure.
Examples
Example #1 Get the file contents
open('test.zip') === TRUE) {
echo $zip->getFromIndex(2);
$zip->close();
} else {
echo 'failed';
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::getFromName
(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)
ZipArchive::getFromName - Returns the entry contents using its name
Description
mixed ZipArchive::getFromName ( string $name [, int $length = 0 [, int
$flags ]] )
Returns the entry contents using its name.
Parameters
name
Name of the entry
length
The length to be read from the entry. If 0, then the entire entry
is read.
flags
The flags to use to open the archive. the following values may be
ORed to it.
* ZIPARCHIVE::FL_UNCHANGED
* ZIPARCHIVE::FL_COMPRESSED
Return Values
Returns the contents of the entry on success or FALSE on failure.
Examples
Example #1 Get the file contents
open('test1.zip') === TRUE) {
echo $zip->getFromName('testfromfile.php');
$zip->close();
} else {
echo 'failed';
}
?>
Example #2 Convert an image from a zip entry
open(dirname(__FILE__) . '/test_im.zip')) {
$im_string = $z->getFromName("pear_item.gif");
$im = imagecreatefromstring($im_string);
imagepng($im, 'b.png');
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::getNameIndex
(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)
ZipArchive::getNameIndex - Returns the name of an entry using its index
Description
string ZipArchive::getNameIndex ( int $index [, int $flags ] )
Returns the name of an entry using its index.
Parameters
index
Index of the entry.
flags
If flags is set to ZIPARCHIVE::FL_UNCHANGED, the original
unchanged name is returned.
Return Values
Returns the name on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::getStatusString
(PHP 5 >= 5.2.7)
ZipArchive::getStatusString - Returns the status error message, system
and/or zip messages
Description
string ZipArchive::getStatusString ( void )
Returns the status error message, system and/or zip messages.
Parameters
This function has no parameters.
Return Values
Returns a string with the status message on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::getStream
(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)
ZipArchive::getStream - Get a file handler to the entry defined by its
name (read only).
Description
resource ZipArchive::getStream ( string $name )
Get a file handler to the entry defined by its name. For now it only
supports read operations.
Parameters
name
The name of the entry to use.
Return Values
Returns a file pointer (resource) on success or FALSE on failure.
Examples
Example #1 Get the entry contents with fread() and store it
open('test.zip')) {
$fp = $z->getStream('test');
if(!$fp) exit("failed\n");
while (!feof($fp)) {
$contents .= fread($fp, 2);
}
fclose($fp);
file_put_contents('t',$contents);
echo "done.\n";
}
?>
Example #2 Same as the previous example but with fopen() and the zip
stream wrapper
Example #3 Stream wrapper and image, can be used with the xml function as
well
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::locateName
(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)
ZipArchive::locateName - Returns the index of the entry in the archive
Description
mixed ZipArchive::locateName ( string $name [, int $flags ] )
Locates an entry using its name.
Parameters
name
The name of the entry to look up
flags
The flags are specified by ORing the following values, or 0 for
none of them.
* ZIPARCHIVE::FL_NOCASE
* ZIPARCHIVE::FL_NODIR
Return Values
Returns the index of the entry on success or FALSE on failure.
Examples
Example #1 Create an archive and then use it with ZipArchive::locateName()
open($file, ZIPARCHIVE::CREATE) !== TRUE) {
exit('failed');
}
$zip->addFromString('entry1.txt', 'entry #1');
$zip->addFromString('entry2.txt', 'entry #2');
$zip->addFromString('dir/entry2d.txt', 'entry #2');
if (!$zip->status == ZIPARCHIVE::ER_OK) {
echo "failed to write zip\n";
}
$zip->close();
if ($zip->open($file) !== TRUE) {
exit('failed');
}
echo $zip->locateName('entry1.txt') . "\n";
echo $zip->locateName('eNtry2.txt') . "\n";
echo $zip->locateName('eNtry2.txt', ZIPARCHIVE::FL_NOCASE) . "\n";
echo $zip->locateName('enTRy2d.txt', ZIPARCHIVE::FL_NOCASE|ZIPARCHIVE::FL_NODIR) . "\n";
$zip->close();
?>
The above example will output:
0
1
2
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::open
(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)
ZipArchive::open - Open a ZIP file archive
Description
mixed ZipArchive::open ( string $filename [, int $flags ] )
Opens a new zip archive for reading, writing or modifying.
Parameters
filename
The file name of the ZIP archive to open.
flags
The mode to use to open the archive.
* ZIPARCHIVE::OVERWRITE
* ZIPARCHIVE::CREATE
* ZIPARCHIVE::EXCL
* ZIPARCHIVE::CHECKCONS
Return Values
Error codes
Returns TRUE on success or the error code.
* ZIPARCHIVE::ER_EXISTS
* ZIPARCHIVE::ER_INCONS
* ZIPARCHIVE::ER_INVAL
* ZIPARCHIVE::ER_MEMORY
* ZIPARCHIVE::ER_NOENT
* ZIPARCHIVE::ER_NOZIP
* ZIPARCHIVE::ER_OPEN
* ZIPARCHIVE::ER_READ
* ZIPARCHIVE::ER_SEEK
Examples
Example #1 Open and extract
open('test.zip');
if ($res === TRUE) {
echo 'ok';
$zip->extractTo('test');
$zip->close();
} else {
echo 'failed, code:' . $res;
}
?>
Example #2 Create an archive
open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('test.txt', 'file content goes here');
$zip->addFile('data.txt', 'entryname.txt');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::renameIndex
(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)
ZipArchive::renameIndex - Renames an entry defined by its index
Description
bool ZipArchive::renameIndex ( int $index , string $newname )
Renames an entry defined by its index.
Parameters
index
Index of the entry to rename.
newname
New name.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Rename one entry
open('test.zip');
if ($res === TRUE) {
$zip->renameIndex(2,'newname.txt');
$zip->close();
} else {
echo 'failed, code:' . $res;
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::renameName
(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)
ZipArchive::renameName - Renames an entry defined by its name
Description
bool ZipArchive::renameName ( string $name , string $newname )
Renames an entry defined by its name.
Parameters
name
Name of the entry to rename.
newname
New name.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Rename one entry
open('test.zip');
if ($res === TRUE) {
$zip->renameName('currentname.txt','newname.txt');
$zip->close();
} else {
echo 'failed, code:' . $res;
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::setArchiveComment
(PHP 5 >= 5.2.0, PECL zip >= 1.4.0)
ZipArchive::setArchiveComment - Set the comment of a ZIP archive
Description
mixed ZipArchive::setArchiveComment ( string $comment )
Set the comment of a ZIP archive.
Parameters
comment
The contents of the comment.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Create an archive and set a comment
open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('test.txt', 'file content goes here');
$zip->setArchiveComment('new archive comment');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::setCommentIndex
(PHP 5 >= 5.2.0, PECL zip >= 1.4.0)
ZipArchive::setCommentIndex - Set the comment of an entry defined by its
index
Description
mixed ZipArchive::setCommentIndex ( int $index , string $comment )
Set the comment of an entry defined by its index.
Parameters
index
Index of the entry.
comment
The contents of the comment.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Open an archive and set a comment for an entry
open('test.zip');
if ($res === TRUE) {
$zip->setCommentIndex(2, 'new entry comment');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::setCommentName
(PHP 5 >= 5.2.0, PECL zip >= 1.4.0)
ZipArchive::setCommentName - Set the comment of an entry defined by its
name
Description
mixed ZipArchive::setCommentName ( string $name , string $comment )
Set the comment of an entry defined by its name.
Parameters
name
Name of the entry.
comment
The contents of the comment.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Open an archive and set a comment for an entry
open('test.zip');
if ($res === TRUE) {
$zip->setCommentName('entry1.txt', 'new entry comment');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::statIndex
(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)
ZipArchive::statIndex - Get the details of an entry defined by its index.
Description
mixed ZipArchive::statIndex ( int $index [, int $flags ] )
The function obtains information about the entry defined by its index.
Parameters
index
Index of the entry
flags
ZIPARCHIVE::FL_UNCHANGED may be ORed to it to request information
about the original file in the archive, ignoring any changes made.
Return Values
Returns an array containing the entry details or FALSE on failure.
Examples
Example #1 Dump the stat info of an entry
open('test.zip');
if ($res === TRUE) {
print_r($zip->statIndex(3));
$zip->close();
} else {
echo 'failed, code:' . $res;
}
?>
The above example will output something similar to:
Array
(
[name] => foobar/baz
[index] => 3
[crc] => 499465816
[size] => 27
[mtime] => 1123164748
[comp_size] => 24
[comp_method] => 8
)
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::statName
(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)
ZipArchive::statName - Get the details of an entry defined by its name.
Description
mixed ZipArchive::statName ( name $name [, int $flags ] )
The function obtains information about the entry defined by its name.
Parameters
name
Name of the entry
flags
The flags argument specifies how the name lookup should be done.
Also, ZIPARCHIVE::FL_UNCHANGED may be ORed to it to request
information about the original file in the archive, ignoring any
changes made.
* ZIPARCHIVE::FL_NOCASE
* ZIPARCHIVE::FL_NODIR
* ZIPARCHIVE::FL_UNCHANGED
Return Values
Returns an array containing the entry details or FALSE on failure.
Examples
Example #1 Dump the stat info of an entry
open('test.zip');
if ($res === TRUE) {
print_r($zip->statName('foobar/baz'));
$zip->close();
} else {
echo 'failed, code:' . $res;
}
?>
The above example will output something similar to:
Array
(
[name] => foobar/baz
[index] => 3
[crc] => 499465816
[size] => 27
[mtime] => 1123164748
[comp_size] => 24
[comp_method] => 8
)
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::unchangeAll
(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)
ZipArchive::unchangeAll - Undo all changes done in the archive
Description
mixed ZipArchive::unchangeAll ( void )
Undo all changes done in the archive.
Parameters
This function has no parameters.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::unchangeArchive
(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)
ZipArchive::unchangeArchive - Revert all global changes done in the
archive.
Description
mixed ZipArchive::unchangeArchive ( void )
Revert all global changes to the archive. For now, this only reverts
archive comment changes.
Parameters
This function has no parameters.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::unchangeIndex
(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)
ZipArchive::unchangeIndex - Revert all changes done to an entry at the
given index
Description
mixed ZipArchive::unchangeIndex ( int $index )
Revert all changes done to an entry at the given index.
Parameters
index
Index of the entry.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
ZipArchive::unchangeName
(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)
ZipArchive::unchangeName - Revert all changes done to an entry with the
given name.
Description
mixed ZipArchive::unchangeName ( string $name )
Revert all changes done to an entry.
Parameters
name
Name of the entry.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
Table of Contents
* ZipArchive::addEmptyDir - Add a new directory
* ZipArchive::addFile - Adds a file to a ZIP archive from the given path
* ZipArchive::addFromString - Add a file to a ZIP archive using its
contents
* ZipArchive::close - Close the active archive (opened or newly created)
* ZipArchive::deleteIndex - delete an entry in the archive using its
index
* ZipArchive::deleteName - delete an entry in the archive using its name
* ZipArchive::extractTo - Extract the archive contents
* ZipArchive::getArchiveComment - Returns the Zip archive comment
* ZipArchive::getCommentIndex - Returns the comment of an entry using
the entry index
* ZipArchive::getCommentName - Returns the comment of an entry using the
entry name
* ZipArchive::getFromIndex - Returns the entry contents using its index
* ZipArchive::getFromName - Returns the entry contents using its name
* ZipArchive::getNameIndex - Returns the name of an entry using its
index
* ZipArchive::getStatusString - Returns the status error message, system
and/or zip messages
* ZipArchive::getStream - Get a file handler to the entry defined by its
name (read only).
* ZipArchive::locateName - Returns the index of the entry in the archive
* ZipArchive::open - Open a ZIP file archive
* ZipArchive::renameIndex - Renames an entry defined by its index
* ZipArchive::renameName - Renames an entry defined by its name
* ZipArchive::setArchiveComment - Set the comment of a ZIP archive
* ZipArchive::setCommentIndex - Set the comment of an entry defined by
its index
* ZipArchive::setCommentName - Set the comment of an entry defined by
its name
* ZipArchive::statIndex - Get the details of an entry defined by its
index.
* ZipArchive::statName - Get the details of an entry defined by its
name.
* ZipArchive::unchangeAll - Undo all changes done in the archive
* ZipArchive::unchangeArchive - Revert all global changes done in the
archive.
* ZipArchive::unchangeIndex - Revert all changes done to an entry at the
given index
* ZipArchive::unchangeName - Revert all changes done to an entry with
the given name.
----------------------------------------------------------------------
----------------------------------------------------------------------
Zip Functions
----------------------------------------------------------------------
zip_close
(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)
zip_close - Close a ZIP file archive
Description
void zip_close ( resource $zip )
Closes the given ZIP file archive.
Parameters
zip
A ZIP file previously opened with zip_open().
Return Values
No value is returned.
See Also
* zip_open() - Open a ZIP file archive
* zip_read() - Read next entry in a ZIP file archive
----------------------------------------------------------------------
----------------------------------------------------------------------
zip_entry_close
(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)
zip_entry_close - Close a directory entry
Description
bool zip_entry_close ( resource $zip_entry )
Closes the specified directory entry.
Parameters
zip_entry
A directory entry previously opened zip_entry_open().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* zip_entry_open() - Open a directory entry for reading
* zip_entry_read() - Read from an open directory entry
----------------------------------------------------------------------
----------------------------------------------------------------------
zip_entry_compressedsize
(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)
zip_entry_compressedsize - Retrieve the compressed size of a directory
entry
Description
int zip_entry_compressedsize ( resource $zip_entry )
Returns the compressed size of the specified directory entry.
Parameters
zip_entry
A directory entry returned by zip_read().
Return Values
The compressed size.
See Also
* zip_open() - Open a ZIP file archive
* zip_read() - Read next entry in a ZIP file archive
----------------------------------------------------------------------
----------------------------------------------------------------------
zip_entry_compressionmethod
(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)
zip_entry_compressionmethod - Retrieve the compression method of a
directory entry
Description
string zip_entry_compressionmethod ( resource $zip_entry )
Returns the compression method of the directory entry specified by
zip_entry.
Parameters
zip_entry
A directory entry returned by zip_read().
Return Values
The compression method.
See Also
* zip_open() - Open a ZIP file archive
* zip_read() - Read next entry in a ZIP file archive
----------------------------------------------------------------------
----------------------------------------------------------------------
zip_entry_filesize
(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)
zip_entry_filesize - Retrieve the actual file size of a directory entry
Description
int zip_entry_filesize ( resource $zip_entry )
Returns the actual size of the specified directory entry.
Parameters
zip_entry
A directory entry returned by zip_read().
Return Values
The size of the directory entry.
See Also
* zip_open() - Open a ZIP file archive
* zip_read() - Read next entry in a ZIP file archive
----------------------------------------------------------------------
----------------------------------------------------------------------
zip_entry_name
(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)
zip_entry_name - Retrieve the name of a directory entry
Description
string zip_entry_name ( resource $zip_entry )
Returns the name of the specified directory entry.
Parameters
zip_entry
A directory entry returned by zip_read().
Return Values
The name of the directory entry.
See Also
* zip_open() - Open a ZIP file archive
* zip_read() - Read next entry in a ZIP file archive
----------------------------------------------------------------------
----------------------------------------------------------------------
zip_entry_open
(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)
zip_entry_open - Open a directory entry for reading
Description
bool zip_entry_open ( resource $zip , resource $zip_entry [, string $mode
] )
Opens a directory entry in a zip file for reading.
Parameters
zip
A valid resource handle returned by zip_open().
zip_entry
A directory entry returned by zip_read().
mode
Any of the modes specified in the documentation of fopen().
Note:
Currently, mode is ignored and is always "rb". This is due to
the fact that zip support in PHP is read only access.
Return Values
Returns TRUE on success or FALSE on failure.
Note:
Unlike fopen() and other similar functions, the return value of
zip_entry_open() only indicates the result of the operation and is not
needed for reading or closing the directory entry.
See Also
* zip_entry_close() - Close a directory entry
* zip_entry_read() - Read from an open directory entry
----------------------------------------------------------------------
----------------------------------------------------------------------
zip_entry_read
(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)
zip_entry_read - Read from an open directory entry
Description
string zip_entry_read ( resource $zip_entry [, int $length ] )
Reads from an open directory entry.
Parameters
zip_entry
A directory entry returned by zip_read().
length
The number of bytes to return. If not specified, this function
will attempt to read 1024 bytes.
Note:
This should be the uncompressed length you wish to read.
Return Values
Returns the data read, or FALSE if the end of the file is reached.
See Also
* zip_entry_open() - Open a directory entry for reading
* zip_entry_close() - Close a directory entry
* zip_entry_filesize() - Retrieve the actual file size of a directory
entry
----------------------------------------------------------------------
----------------------------------------------------------------------
zip_open
(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)
zip_open - Open a ZIP file archive
Description
mixed zip_open ( string $filename )
Opens a new zip archive for reading.
Parameters
filename
The file name of the ZIP archive to open.
Return Values
Returns a resource handle for later use with zip_read() and zip_close() or
returns the number of error if filename does not exist or in case of other
error.
See Also
* zip_read() - Read next entry in a ZIP file archive
* zip_close() - Close a ZIP file archive
----------------------------------------------------------------------
----------------------------------------------------------------------
zip_read
(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)
zip_read - Read next entry in a ZIP file archive
Description
mixed zip_read ( resource $zip )
Reads the next entry in a zip file archive.
Parameters
zip
A ZIP file previously opened with zip_open().
Return Values
Returns a directory entry resource for later use with the zip_entry_...
functions or FALSE if there's no more entries to read or number of error
in case of other error.
See Also
* zip_open() - Open a ZIP file archive
* zip_close() - Close a ZIP file archive
* zip_entry_open() - Open a directory entry for reading
* zip_entry_read() - Read from an open directory entry
----------------------------------------------------------------------
Table of Contents
* zip_close - Close a ZIP file archive
* zip_entry_close - Close a directory entry
* zip_entry_compressedsize - Retrieve the compressed size of a directory
entry
* zip_entry_compressionmethod - Retrieve the compression method of a
directory entry
* zip_entry_filesize - Retrieve the actual file size of a directory
entry
* zip_entry_name - Retrieve the name of a directory entry
* zip_entry_open - Open a directory entry for reading
* zip_entry_read - Read from an open directory entry
* zip_open - Open a ZIP file archive
* zip_read - Read next entry in a ZIP file archive
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* ZipArchive - The ZipArchive class
* ZipArchive::addEmptyDir - Add a new directory
* ZipArchive::addFile - Adds a file to a ZIP archive from the given
path
* ZipArchive::addFromString - Add a file to a ZIP archive using its
contents
* ZipArchive::close - Close the active archive (opened or newly
created)
* ZipArchive::deleteIndex - delete an entry in the archive using
its index
* ZipArchive::deleteName - delete an entry in the archive using its
name
* ZipArchive::extractTo - Extract the archive contents
* ZipArchive::getArchiveComment - Returns the Zip archive comment
* ZipArchive::getCommentIndex - Returns the comment of an entry
using the entry index
* ZipArchive::getCommentName - Returns the comment of an entry
using the entry name
* ZipArchive::getFromIndex - Returns the entry contents using its
index
* ZipArchive::getFromName - Returns the entry contents using its
name
* ZipArchive::getNameIndex - Returns the name of an entry using its
index
* ZipArchive::getStatusString - Returns the status error message,
system and/or zip messages
* ZipArchive::getStream - Get a file handler to the entry defined
by its name (read only).
* ZipArchive::locateName - Returns the index of the entry in the
archive
* ZipArchive::open - Open a ZIP file archive
* ZipArchive::renameIndex - Renames an entry defined by its index
* ZipArchive::renameName - Renames an entry defined by its name
* ZipArchive::setArchiveComment - Set the comment of a ZIP archive
* ZipArchive::setCommentIndex - Set the comment of an entry defined
by its index
* ZipArchive::setCommentName - Set the comment of an entry defined
by its name
* ZipArchive::statIndex - Get the details of an entry defined by
its index.
* ZipArchive::statName - Get the details of an entry defined by its
name.
* ZipArchive::unchangeAll - Undo all changes done in the archive
* ZipArchive::unchangeArchive - Revert all global changes done in
the archive.
* ZipArchive::unchangeIndex - Revert all changes done to an entry
at the given index
* ZipArchive::unchangeName - Revert all changes done to an entry
with the given name.
* Zip Functions
* zip_close - Close a ZIP file archive
* zip_entry_close - Close a directory entry
* zip_entry_compressedsize - Retrieve the compressed size of a
directory entry
* zip_entry_compressionmethod - Retrieve the compression method of
a directory entry
* zip_entry_filesize - Retrieve the actual file size of a directory
entry
* zip_entry_name - Retrieve the name of a directory entry
* zip_entry_open - Open a directory entry for reading
* zip_entry_read - Read from an open directory entry
* zip_open - Open a ZIP file archive
* zip_read - Read next entry in a ZIP file archive
----------------------------------------------------------------------
----------------------------------------------------------------------
Zlib Compression
----------------------------------------------------------------------
Introduction
This module enables you to transparently read and write gzip (.gz)
compressed files, through versions of most of the filesystem functions
which work with gzip-compressed files (and uncompressed files, too, but
not with sockets).
Note:
Version 4.0.4 introduced a fopen-wrapper for .gz-files, so that you can
use a special zlib: URL to access compressed files transparently using
the normal f*() file access functions if you prefix the filename or path
with zlib: when calling fopen(). This feature requires a C runtime
library that provides the fopencookie() function. Up to now the GNU libc
seems to be the only library that provides this feature.
In PHP 4.3.0, zlib: has been changed to compress.zlib:// to prevent
ambiguities with filenames containing ':' characters. The fopencookie()
function is no longer required. More information is available in the
section about zlib://.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
This module uses the functions of >> zlib by Jean-loup Gailly and Mark
Adler. You have to use a zlib version >= 1.0.9 with this module.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
Zlib support in PHP is not enabled by default. You will need to configure
PHP --with-zlib[=DIR]
The Windows version of PHP has built-in support for this extension. You do
not need to load any additional extensions in order to use these
functions.
Note: Built-in support for zlib on Windows is available with PHP 4.3.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
The zlib extension offers the option to transparently compress your pages
on-the-fly, if the requesting browser supports this. Therefore there are
three options in the configuration file php.ini.
Zlib Configuration Options
Name Default Changeable Changelog
zlib.output_compression "0" PHP_INI_ALL Available since PHP
4.0.5.
zlib.output_compression_level "-1" PHP_INI_ALL Available since PHP
4.3.0.
zlib.output_handler "" PHP_INI_ALL Available since PHP
4.3.0.
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
zlib.output_compression boolean/integer
Whether to transparently compress pages. If this option is set to
"On" in php.ini or the Apache configuration, pages are compressed
if the browser sends an "Accept-Encoding: gzip" or "deflate"
header. "Content-Encoding: gzip" (respectively "deflate") and
"Vary: Accept-Encoding" headers are added to the output. In
runtime, it can be set only before sending any output.
This option also accepts integer values instead of boolean
"On"/"Off", using this you can set the output buffer size (default
is 4KB).
Note:
output_handler must be empty if this is set 'On' ! Instead you
must use zlib.output_handler.
zlib.output_compression_level integer
Compression level used for transparent output compression. Specify
a value between 0 (no compression) to 9 (most compression). The
default value, -1, lets the server decide which level to use.
zlib.output_handler string
You cannot specify additional output handlers if
zlib.output_compression is activated here. This setting does the
same as output_handler but in a different order.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension defines a file pointer resource returned by gzopen().
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
FORCE_GZIP (integer)
FORCE_DEFLATE (integer)
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
This example opens a temporary file and writes a test string to it, then
it prints out the content of this file twice.
Example #1 Small Zlib Example
\n\n\n\n";
$s = "Only a test, test, test, test, test, test, test, test!\n";
// open file for writing with maximum compression
$zp = gzopen($filename, "w9");
// write string to file
gzwrite($zp, $s);
// close file
gzclose($zp);
// open file for reading
$zp = gzopen($filename, "r");
// read 3 char
echo gzread($zp, 3);
// output until end of the file and close it.
gzpassthru($zp);
gzclose($zp);
echo "\n";
// open file and print content (the 2nd time).
if (readgzfile($filename) != strlen($s)) {
echo "Error with zlib functions!";
}
unlink($filename);
echo " \n\n\n";
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
Zlib Functions
----------------------------------------------------------------------
gzclose
(PHP 4, PHP 5)
gzclose - Close an open gz-file pointer
Description
bool gzclose ( resource $zp )
Closes the given gz-file pointer.
Parameters
zp
The gz-file pointer. It must be valid, and must point to a file
successfully opened by gzopen().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 gzclose() example
See Also
* gzopen() - Open gz-file
----------------------------------------------------------------------
----------------------------------------------------------------------
gzcompress
(PHP 4 >= 4.0.1, PHP 5)
gzcompress - Compress a string
Description
string gzcompress ( string $data [, int $level = -1 ] )
This function compress the given string using the ZLIB data format.
For details on the ZLIB compression algorithm see the document ">> ZLIB
Compressed Data Format Specification version 3.3" (RFC 1950).
Note:
This is not the same as gzip compression, which includes some header
data. See gzencode() for gzip compression.
Parameters
data
The data to compress.
level
The level of compression. Can be given as 0 for no compression up
to 9 for maximum compression.
Return Values
The compressed string or FALSE if an error occurred.
Examples
Example #1 gzcompress() example
See Also
* gzdeflate() - Deflate a string
* gzinflate() - Inflate a deflated string
* gzuncompress() - Uncompress a compressed string
* gzencode() - Create a gzip compressed string
----------------------------------------------------------------------
----------------------------------------------------------------------
gzdecode
(No version information available, might only be in SVN)
gzdecode - Decodes a gzip compressed string
Description
string gzdecode ( string $data [, int $length ] )
This function returns a decoded version of the input data.
Parameters
data
The data to decode, encoded by gzencode().
length
The maximum length of data to decode.
Return Values
The decoded string, or FALSE if an error occurred.
See Also
* gzencode() - Create a gzip compressed string
----------------------------------------------------------------------
----------------------------------------------------------------------
gzdeflate
(PHP 4 >= 4.0.4, PHP 5)
gzdeflate - Deflate a string
Description
string gzdeflate ( string $data [, int $level = -1 ] )
This function compress the given string using the DEFLATE data format.
For details on the DEFLATE compression algorithm see the document
">> DEFLATE Compressed Data Format Specification version 1.3" (RFC 1951).
Parameters
data
The data to deflate.
level
The level of compression. Can be given as 0 for no compression up
to 9 for maximum compression. If not given, the default
compression level will be the default compression level of the
zlib library.
Return Values
The deflated string or FALSE if an error occurred.
Examples
Example #1 gzdeflate() example
See Also
* gzinflate() - Inflate a deflated string
* gzcompress() - Compress a string
* gzuncompress() - Uncompress a compressed string
* gzencode() - Create a gzip compressed string
----------------------------------------------------------------------
----------------------------------------------------------------------
gzencode
(PHP 4 >= 4.0.4, PHP 5)
gzencode - Create a gzip compressed string
Description
string gzencode ( string $data [, int $level = -1 [, int $encoding_mode =
FORCE_GZIP ]] )
This function returns a compressed version of the input data compatible
with the output of the gzip program.
For more information on the GZIP file format, see the document: >> GZIP
file format specification version 4.3 (RFC 1952).
Parameters
data
The data to encode.
level
The level of compression. Can be given as 0 for no compression up
to 9 for maximum compression. If not given, the default
compression level will be the default compression level of the
zlib library.
encoding_mode
The encoding mode. Can be FORCE_GZIP (the default) or
FORCE_DEFLATE.
If you use FORCE_DEFLATE, you get a standard zlib deflated string
(inclusive zlib headers) after the gzip file header but without
the trailing crc32 checksum.
Return Values
The encoded string, or FALSE if an error occurred.
Changelog
Version Description
4.2.0 The encoding_mode parameter was added
Examples
The resulting data contains the appropriate headers and data structure to
make a standard .gz file, e.g.:
Example #1 Creating a gzip file
See Also
* gzdecode() - Decodes a gzip compressed string
* gzdeflate() - Deflate a string
* gzinflate() - Inflate a deflated string
* gzuncompress() - Uncompress a compressed string
* gzcompress() - Compress a string
----------------------------------------------------------------------
----------------------------------------------------------------------
gzeof
(PHP 4, PHP 5)
gzeof - Test for EOF on a gz-file pointer
Description
int gzeof ( resource $zp )
Tests the given GZ file pointer for EOF.
Parameters
zp
The gz-file pointer. It must be valid, and must point to a file
successfully opened by gzopen().
Return Values
Returns TRUE if the gz-file pointer is at EOF or an error occurs;
otherwise returns FALSE.
Examples
Example #1 gzeof() example
----------------------------------------------------------------------
----------------------------------------------------------------------
gzfile
(PHP 4, PHP 5)
gzfile - Read entire gz-file into an array
Description
array gzfile ( string $filename [, int $use_include_path = 0 ] )
This function is identical to readgzfile(), except that it returns the
file in an array.
Parameters
filename
The file name.
use_include_path
You can set this optional parameter to 1, if you want to search
for the file in the include_path too.
Return Values
An array containing the file, one line per cell.
Examples
Example #1 gzfile() example
See Also
* readgzfile() - Output a gz-file
* gzopen() - Open gz-file
----------------------------------------------------------------------
----------------------------------------------------------------------
gzgetc
(PHP 4, PHP 5)
gzgetc - Get character from gz-file pointer
Description
string gzgetc ( resource $zp )
Returns a string containing a single (uncompressed) character read from
the given gz-file pointer.
Parameters
zp
The gz-file pointer. It must be valid, and must point to a file
successfully opened by gzopen().
Return Values
The uncompressed character or FALSE on EOF (unlike gzeof()).
Examples
Example #1 gzgetc() example
See Also
* gzopen() - Open gz-file
* gzgets() - Get line from file pointer
----------------------------------------------------------------------
----------------------------------------------------------------------
gzgets
(PHP 4, PHP 5)
gzgets - Get line from file pointer
Description
string gzgets ( resource $zp , int $length )
Gets a (uncompressed) string of up to length - 1 bytes read from the given
file pointer. Reading ends when length - 1 bytes have been read, on a
newline, or on EOF (whichever comes first).
Parameters
zp
The gz-file pointer. It must be valid, and must point to a file
successfully opened by gzopen().
length
The length of data to get.
Return Values
The uncompressed string, or FALSE on error.
Examples
Example #1 gzgets() example
See Also
* gzopen() - Open gz-file
* gzgetc() - Get character from gz-file pointer
* gzwrite() - Binary-safe gz-file write
----------------------------------------------------------------------
----------------------------------------------------------------------
gzgetss
(PHP 4, PHP 5)
gzgetss - Get line from gz-file pointer and strip HTML tags
Description
string gzgetss ( resource $zp , int $length [, string $allowable_tags ] )
Identical to gzgets(), except that gzgetss() attempts to strip any HTML
and PHP tags from the text it reads.
Parameters
zp
The gz-file pointer. It must be valid, and must point to a file
successfully opened by gzopen().
length
The length of data to get.
allowable_tags
You can use this optional parameter to specify tags which should
not be stripped.
Return Values
The uncompressed and striped string, or FALSE on error.
Examples
Example #1 gzgetss() example
See Also
* gzopen() - Open gz-file
* gzgets() - Get line from file pointer
* strip_tags() - Strip HTML and PHP tags from a string
----------------------------------------------------------------------
----------------------------------------------------------------------
gzinflate
(PHP 4 >= 4.0.4, PHP 5)
gzinflate - Inflate a deflated string
Description
string gzinflate ( string $data [, int $length = 0 ] )
This function inflate a deflated string.
Parameters
data
The data compressed by gzdeflate().
length
The maximum length of data to decode.
Return Values
The original uncompressed data or FALSE on error.
The function will return an error if the uncompressed data is more than
32768 times the length of the compressed input data or more than the
optional parameter length.
Examples
Example #1 gzinflate() example
See Also
* gzdeflate() - Deflate a string
* gzcompress() - Compress a string
* gzuncompress() - Uncompress a compressed string
* gzencode() - Create a gzip compressed string
----------------------------------------------------------------------
----------------------------------------------------------------------
gzopen
(PHP 4, PHP 5)
gzopen - Open gz-file
Description
resource gzopen ( string $filename , string $mode [, int $use_include_path
= 0 ] )
Opens a gzip (.gz) file for reading or writing.
gzopen() can be used to read a file which is not in gzip format; in this
case gzread() will directly read from the file without decompression.
Parameters
filename
The file name.
mode
As in fopen() (rb or wb) but can also include a compression level
(wb9) or a strategy: f for filtered data as in wb6f, h for Huffman
only compression as in wb1h. (See the description of deflateInit2
in zlib.h for more information about the strategy parameter.)
use_include_path
You can set this optional parameter to 1, if you want to search
for the file in the include_path too.
Return Values
Returns a file pointer to the file opened, after that, everything you read
from this file descriptor will be transparently decompressed and what you
write gets compressed.
If the open fails, the function returns FALSE.
Examples
Example #1 gzopen() Example
See Also
* gzclose() - Close an open gz-file pointer
----------------------------------------------------------------------
----------------------------------------------------------------------
gzpassthru
(PHP 4, PHP 5)
gzpassthru - Output all remaining data on a gz-file pointer
Description
int gzpassthru ( resource $zp )
Reads to EOF on the given gz-file pointer from the current position and
writes the (uncompressed) results to standard output.
Note:
You may need to call gzrewind() to reset the file pointer to the
beginning of the file if you have already written data to it.
Tip
If you just want to dump the contents of a file to the output buffer,
without first modifying it or seeking to a particular offset, you may want
to use the readgzfile() function, which saves you the gzopen() call.
Parameters
zp
The gz-file pointer. It must be valid, and must point to a file
successfully opened by gzopen().
Return Values
The number of uncompressed characters read from gz and passed through to
the input, or FALSE on error.
Examples
Example #1 gzpassthru() example
----------------------------------------------------------------------
----------------------------------------------------------------------
gzputs
(PHP 4, PHP 5)
gzputs - Alias of gzwrite()
Description
This function is an alias of: gzwrite().
----------------------------------------------------------------------
----------------------------------------------------------------------
gzread
(PHP 4, PHP 5)
gzread - Binary-safe gz-file read
Description
string gzread ( resource $zp , int $length )
gzread() reads up to length bytes from the given gz-file pointer. Reading
stops when length (uncompressed) bytes have been read or EOF is reached,
whichever comes first.
Parameters
zp
The gz-file pointer. It must be valid, and must point to a file
successfully opened by gzopen().
length
The number of bytes to read.
Return Values
The data that have been read.
Examples
Example #1 gzread() example
See Also
* gzwrite() - Binary-safe gz-file write
* gzopen() - Open gz-file
* gzgets() - Get line from file pointer
* gzgetss() - Get line from gz-file pointer and strip HTML tags
* gzfile() - Read entire gz-file into an array
* gzpassthru() - Output all remaining data on a gz-file pointer
----------------------------------------------------------------------
----------------------------------------------------------------------
gzrewind
(PHP 4, PHP 5)
gzrewind - Rewind the position of a gz-file pointer
Description
bool gzrewind ( resource $zp )
Sets the file position indicator of the given gz-file pointer to the
beginning of the file stream.
Parameters
zp
The gz-file pointer. It must be valid, and must point to a file
successfully opened by gzopen().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* gzseek() - Seek on a gz-file pointer
* gztell() - Tell gz-file pointer read/write position
----------------------------------------------------------------------
----------------------------------------------------------------------
gzseek
(PHP 4, PHP 5)
gzseek - Seek on a gz-file pointer
Description
int gzseek ( resource $zp , int $offset [, int $whence = SEEK_SET ] )
Sets the file position indicator for the given file pointer to the given
offset byte into the file stream. Equivalent to calling (in C) gzseek(zp,
offset, SEEK_SET).
If the file is opened for reading, this function is emulated but can be
extremely slow. If the file is opened for writing, only forward seeks are
supported; gzseek() then compresses a sequence of zeroes up to the new
starting position.
Parameters
zp
The gz-file pointer. It must be valid, and must point to a file
successfully opened by gzopen().
offset
The seeked offset.
whence
whence values are:
* SEEK_SET - Set position equal to offset bytes.
* SEEK_CUR - Set position to current location plus offset.
If whence is not specified, it is assumed to be SEEK_SET.
Return Values
Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF
is not considered an error.
Examples
Example #1 gzseek() example
See Also
* gztell() - Tell gz-file pointer read/write position
* gzrewind() - Rewind the position of a gz-file pointer
----------------------------------------------------------------------
----------------------------------------------------------------------
gztell
(PHP 4, PHP 5)
gztell - Tell gz-file pointer read/write position
Description
int gztell ( resource $zp )
Gets the position of the given file pointer; i.e., its offset into the
uncompressed file stream.
Parameters
zp
The gz-file pointer. It must be valid, and must point to a file
successfully opened by gzopen().
Return Values
The position of the file pointer or FALSE if an error occurs.
See Also
* gzopen() - Open gz-file
* gzseek() - Seek on a gz-file pointer
* gzrewind() - Rewind the position of a gz-file pointer
----------------------------------------------------------------------
----------------------------------------------------------------------
gzuncompress
(PHP 4 >= 4.0.1, PHP 5)
gzuncompress - Uncompress a compressed string
Description
string gzuncompress ( string $data [, int $length = 0 ] )
This function uncompress a compressed string.
Parameters
data
The data compressed by gzcompress().
length
The maximum length of data to decode.
Return Values
The original uncompressed data or FALSE on error.
The function will return an error if the uncompressed data is more than
32768 times the length of the compressed input data or more than the
optional parameter length.
Examples
Example #1 gzuncompress() example
See Also
* gzcompress() - Compress a string
* gzinflate() - Inflate a deflated string
* gzdeflate() - Deflate a string
* gzencode() - Create a gzip compressed string
----------------------------------------------------------------------
----------------------------------------------------------------------
gzwrite
(PHP 4, PHP 5)
gzwrite - Binary-safe gz-file write
Description
int gzwrite ( resource $zp , string $string [, int $length ] )
gzwrite() writes the contents of string to the given gz-file.
Parameters
zp
The gz-file pointer. It must be valid, and must point to a file
successfully opened by gzopen().
string
The string to write.
length
The number of uncompressed bytes to write. If supplied, writing
will stop after length (uncompressed) bytes have been written or
the end of string is reached, whichever comes first.
Note:
Note that if the length argument is given, then the
magic_quotes_runtime configuration option will be ignored and no
slashes will be stripped from string.
Return Values
Returns the number of (uncompressed) bytes written to the given gz-file
stream.
Examples
Example #1 gzwrite() example
See Also
* gzread() - Binary-safe gz-file read
* gzopen() - Open gz-file
----------------------------------------------------------------------
----------------------------------------------------------------------
readgzfile
(PHP 4, PHP 5)
readgzfile - Output a gz-file
Description
int readgzfile ( string $filename [, int $use_include_path = 0 ] )
Reads a file, decompresses it and writes it to standard output.
readgzfile() can be used to read a file which is not in gzip format; in
this case readgzfile() will directly read from the file without
decompression.
Parameters
filename
The file name. This file will be opened from the filesystem and
its contents written to standard output.
use_include_path
You can set this optional parameter to 1, if you want to search
for the file in the include_path too.
Return Values
Returns the number of (uncompressed) bytes read from the file. If an error
occurs, FALSE is returned and unless the function was called as
@readgzfile, an error message is printed.
See Also
* gzpassthru() - Output all remaining data on a gz-file pointer
* gzfile() - Read entire gz-file into an array
* gzopen() - Open gz-file
----------------------------------------------------------------------
----------------------------------------------------------------------
zlib_get_coding_type
(PHP 4 >= 4.3.2, PHP 5)
zlib_get_coding_type - Returns the coding type used for output compression
Description
string zlib_get_coding_type ( void )
Returns the coding type used for output compression.
Return Values
Possible return values are gzip, deflate, or FALSE.
See Also
* The zlib.output_compression directive
----------------------------------------------------------------------
Table of Contents
* gzclose - Close an open gz-file pointer
* gzcompress - Compress a string
* gzdecode - Decodes a gzip compressed string
* gzdeflate - Deflate a string
* gzencode - Create a gzip compressed string
* gzeof - Test for EOF on a gz-file pointer
* gzfile - Read entire gz-file into an array
* gzgetc - Get character from gz-file pointer
* gzgets - Get line from file pointer
* gzgetss - Get line from gz-file pointer and strip HTML tags
* gzinflate - Inflate a deflated string
* gzopen - Open gz-file
* gzpassthru - Output all remaining data on a gz-file pointer
* gzputs - Alias of gzwrite
* gzread - Binary-safe gz-file read
* gzrewind - Rewind the position of a gz-file pointer
* gzseek - Seek on a gz-file pointer
* gztell - Tell gz-file pointer read/write position
* gzuncompress - Uncompress a compressed string
* gzwrite - Binary-safe gz-file write
* readgzfile - Output a gz-file
* zlib_get_coding_type - Returns the coding type used for output
compression
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* Zlib Functions
* gzclose - Close an open gz-file pointer
* gzcompress - Compress a string
* gzdecode - Decodes a gzip compressed string
* gzdeflate - Deflate a string
* gzencode - Create a gzip compressed string
* gzeof - Test for EOF on a gz-file pointer
* gzfile - Read entire gz-file into an array
* gzgetc - Get character from gz-file pointer
* gzgets - Get line from file pointer
* gzgetss - Get line from gz-file pointer and strip HTML tags
* gzinflate - Inflate a deflated string
* gzopen - Open gz-file
* gzpassthru - Output all remaining data on a gz-file pointer
* gzputs - Alias of gzwrite
* gzread - Binary-safe gz-file read
* gzrewind - Rewind the position of a gz-file pointer
* gzseek - Seek on a gz-file pointer
* gztell - Tell gz-file pointer read/write position
* gzuncompress - Uncompress a compressed string
* gzwrite - Binary-safe gz-file write
* readgzfile - Output a gz-file
* zlib_get_coding_type - Returns the coding type used for output
compression
----------------------------------------------------------------------
* Bzip2
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* Bzip2 Functions
* LZF
* Introduction
* Installing/Configuring
* Predefined Constants
* LZF Functions
* Phar
* Introduction
* Installing/Configuring
* Predefined Constants
* Using Phar Archives
* Creating Phar Archives
* What makes a phar a phar and not a tar or a zip?
* Phar - The Phar class
* PharData - The PharData class
* PharFileInfo - The PharFileInfo class
* PharException - The PharException class
* Rar - Rar Archiving
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* Rar Functions
* RarArchive - The RarArchive class
* RarEntry - The RarEntry class
* RarException - The RarException class
* Zip
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* ZipArchive - The ZipArchive class
* Zip Functions
* Zlib - Zlib Compression
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* Zlib Functions
----------------------------------------------------------------------
----------------------------------------------------------------------
Credit Card Processing
----------------------------------------------------------------------
MCVE (Monetra) Payment
----------------------------------------------------------------------
Introduction
These functions interface the MCVE (Monetra) API (libmonetra, formerly
known as libmcve), allowing you to work directly with MCVE/Monetra from
your PHP scripts. MCVE/Monetra is Main Street Softworks' solution to
direct credit/debit/gift card processing for Linux/Unix/MacOSX/Windows (
>> http://www.mainstreetsoftworks.com/ ). It lets you directly address the
credit card clearing houses via your *nix box, modem and/or internet
connection (bypassing the need for an additional service such as
Authorize.Net or Pay Flow Pro). Using the MCVE/Monetra module for PHP, you
can process credit cards directly through MCVE/Monetra via your PHP
scripts. The following references will outline the process.
Note:
MCVE/Monetra is the replacement for RedHat's CCVS. They contracted with
RedHat in late 2001 to migrate all existing clientele to the MCVE
platform.
Note:
This extension has been moved to the >> PECL repository and is no longer
bundled with PHP as of PHP 5.1.0.
Note: This extension is not available on Windows platforms.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
The LibMonetra (formerly libmcve) library.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
This >> PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here: >> http://pecl.php.net/package/mcve.
A DLL for this PECL extension is currently unavailable. See also the
building on Windows section.
If installing without specifying the libmonetra path, PHP will attempt to
look in the default LibMonetra Install location (/usr/local). If Monetra
(MCVE) is in a non-standard location, run configure with:
--with-mcve=$mcve_path , where $mcve_path is the path to your MCVE/Monetra
installation. Please note that MCVE/Monetra support requires that
$mcve_path/lib and $mcve_path/include exist, and include mcve.h or
monetra.h under the include directory and libmcve.so and/or libmcve.a
and/or libmonetra.so and/or libmonetra.a under the lib directory.
Since MCVE/Monetra has true server/client separation, there are no
additional requirements for running PHP with MCVE support. To test your
MCVE/Monetra extension in PHP, you may connect to testbox.monetra.com on
port 8333 for IP, or port 8444 for SSL using the MCVE/Monetra PHP API. Use
'vitale' for your username, and 'test' for your password. Additional
information about test facilities are available at
>> http://www.mainstreetsoftworks.com/.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension defines a MCVE_CONN resource returned by m_initconn().
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
M_PENDING (integer)
M_DONE (integer)
M_ERROR (integer)
M_FAIL (integer)
M_SUCCESS (integer)
----------------------------------------------------------------------
----------------------------------------------------------------------
MCVE Functions
See Also
Additional documentation about MCVE/Monetra's PHP API can be found at
>> http://www.mainstreetsoftworks.com/documentation.html. Main Street's
documentation is complete and should be the primary reference for
functions.
----------------------------------------------------------------------
m_checkstatus
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_checkstatus - Check to see if a transaction has completed
Description
int m_checkstatus ( resource $conn , int $identifier )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
identifier
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_completeauthorizations
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_completeauthorizations - Number of complete authorizations in queue,
returning an array of their identifiers
Description
int m_completeauthorizations ( resource $conn , int &$array )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
array
Its description
Return Values
What the function returns, first on success, then on failure. See also the
&return.success; entity
----------------------------------------------------------------------
----------------------------------------------------------------------
m_connect
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_connect - Establish the connection to MCVE
Description
int m_connect ( resource $conn )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_connectionerror
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_connectionerror - Get a textual representation of why a connection
failed
Description
string m_connectionerror ( resource $conn )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_deletetrans
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_deletetrans - Delete specified transaction from MCVE_CONN structure
Description
bool m_deletetrans ( resource $conn , int $identifier )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
identifier
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_destroyconn
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_destroyconn - Destroy the connection and MCVE_CONN structure
Description
bool m_destroyconn ( resource $conn )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
Return Values
Returns TRUE.
See Also
* m_initconn() - Create and initialize an MCVE_CONN structure
----------------------------------------------------------------------
----------------------------------------------------------------------
m_destroyengine
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_destroyengine - Free memory associated with IP/SSL connectivity
Description
void m_destroyengine ( void )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
m_getcell
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_getcell - Get a specific cell from a comma delimited response by column
name
Description
string m_getcell ( resource $conn , int $identifier , string $column , int
$row )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
identifier
column
row
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_getcellbynum
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_getcellbynum - Get a specific cell from a comma delimited response by
column number
Description
string m_getcellbynum ( resource $conn , int $identifier , int $column ,
int $row )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
identifier
column
row
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_getcommadelimited
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_getcommadelimited - Get the RAW comma delimited data returned from MCVE
Description
string m_getcommadelimited ( resource $conn , int $identifier )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
identifier
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_getheader
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_getheader - Get the name of the column in a comma-delimited response
Description
string m_getheader ( resource $conn , int $identifier , int $column_num )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
identifier
column_num
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_initconn
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_initconn - Create and initialize an MCVE_CONN structure
Description
resource m_initconn ( void )
Warning
This function is currently not documented; only its argument list is
available.
Return Values
Returns an MCVE_CONN resource.
See Also
* m_destroyconn() - Destroy the connection and MCVE_CONN structure
----------------------------------------------------------------------
----------------------------------------------------------------------
m_initengine
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_initengine - Ready the client for IP/SSL Communication
Description
int m_initengine ( string $location )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
location
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_iscommadelimited
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_iscommadelimited - Checks to see if response is comma delimited
Description
int m_iscommadelimited ( resource $conn , int $identifier )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
identifier
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_maxconntimeout
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_maxconntimeout - The maximum amount of time the API will attempt a
connection to MCVE
Description
bool m_maxconntimeout ( resource $conn , int $secs )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
secs
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_monitor
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_monitor - Perform communication with MCVE (send/receive data)
Non-blocking
Description
int m_monitor ( resource $conn )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_numcolumns
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_numcolumns - Number of columns returned in a comma delimited response
Description
int m_numcolumns ( resource $conn , int $identifier )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
identifier
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_numrows
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_numrows - Number of rows returned in a comma delimited response
Description
int m_numrows ( resource $conn , int $identifier )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
identifier
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_parsecommadelimited
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_parsecommadelimited - Parse the comma delimited response so m_getcell,
etc will work
Description
int m_parsecommadelimited ( resource $conn , int $identifier )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
identifier
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_responsekeys
(PHP 5 >= 5.0.5, PECL mcve >= 1.0.0)
m_responsekeys - Returns array of strings which represents the keys that
can be used for response parameters on this transaction
Description
array m_responsekeys ( resource $conn , int $identifier )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
identifier
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_responseparam
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_responseparam - Get a custom response parameter
Description
string m_responseparam ( resource $conn , int $identifier , string $key )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
identifier
key
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_returnstatus
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_returnstatus - Check to see if the transaction was successful
Description
int m_returnstatus ( resource $conn , int $identifier )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
identifier
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_setblocking
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_setblocking - Set blocking/non-blocking mode for connection
Description
int m_setblocking ( resource $conn , int $tf )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
tf
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_setdropfile
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_setdropfile - Set the connection method to Drop-File
Description
int m_setdropfile ( resource $conn , string $directory )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
directory
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_setip
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_setip - Set the connection method to IP
Description
int m_setip ( resource $conn , string $host , int $port )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
host
port
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_setssl_cafile
(PHP 5 >= 5.0.5, PECL mcve >= 1.0.0)
m_setssl_cafile - Set SSL CA (Certificate Authority) file for verification
of server certificate
Description
int m_setssl_cafile ( resource $conn , string $cafile )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
cafile
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_setssl_files
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_setssl_files - Set certificate key files and certificates if server
requires client certificate verification
Description
int m_setssl_files ( resource $conn , string $sslkeyfile , string
$sslcertfile )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
sslkeyfile
sslcertfile
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_setssl
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_setssl - Set the connection method to SSL
Description
int m_setssl ( resource $conn , string $host , int $port )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
host
port
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_settimeout
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_settimeout - Set maximum transaction time (per trans)
Description
int m_settimeout ( resource $conn , int $seconds )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
seconds
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_sslcert_gen_hash
(PECL mcve >= 5.2.0)
m_sslcert_gen_hash - Generate hash for SSL client certificate verification
Description
string m_sslcert_gen_hash ( string $filename )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
filename
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_transactionssent
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_transactionssent - Check to see if outgoing buffer is clear
Description
int m_transactionssent ( resource $conn )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_transinqueue
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_transinqueue - Number of transactions in client-queue
Description
int m_transinqueue ( resource $conn )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_transkeyval
(PHP 5 >= 5.0.5, PECL mcve >= 1.0.0)
m_transkeyval - Add key/value pair to a transaction. Replaces deprecated
transparam()
Description
int m_transkeyval ( resource $conn , int $identifier , string $key ,
string $value )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
identifier
key
value
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_transnew
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_transnew - Start a new transaction
Description
int m_transnew ( resource $conn )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_transsend
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_transsend - Finalize and send the transaction
Description
int m_transsend ( resource $conn , int $identifier )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
identifier
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_uwait
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_uwait - Wait x microsecs
Description
int m_uwait ( int $microsecs )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
microsecs
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_validateidentifier
(PHP 5 >= 5.0.5, PECL mcve >= 1.0.0)
m_validateidentifier - Whether or not to validate the passed identifier on
any transaction it is passed to
Description
int m_validateidentifier ( resource $conn , int $tf )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
tf
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_verifyconnection
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_verifyconnection - Set whether or not to PING upon connect to verify
connection
Description
bool m_verifyconnection ( resource $conn , int $tf )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
tf
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
m_verifysslcert
(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)
m_verifysslcert - Set whether or not to verify the server ssl certificate
Description
bool m_verifysslcert ( resource $conn , int $tf )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
conn
An MCVE_CONN resource returned by m_initengine().
tf
Return Values
----------------------------------------------------------------------
Table of Contents
* m_checkstatus - Check to see if a transaction has completed
* m_completeauthorizations - Number of complete authorizations in queue,
returning an array of their identifiers
* m_connect - Establish the connection to MCVE
* m_connectionerror - Get a textual representation of why a connection
failed
* m_deletetrans - Delete specified transaction from MCVE_CONN structure
* m_destroyconn - Destroy the connection and MCVE_CONN structure
* m_destroyengine - Free memory associated with IP/SSL connectivity
* m_getcell - Get a specific cell from a comma delimited response by
column name
* m_getcellbynum - Get a specific cell from a comma delimited response
by column number
* m_getcommadelimited - Get the RAW comma delimited data returned from
MCVE
* m_getheader - Get the name of the column in a comma-delimited response
* m_initconn - Create and initialize an MCVE_CONN structure
* m_initengine - Ready the client for IP/SSL Communication
* m_iscommadelimited - Checks to see if response is comma delimited
* m_maxconntimeout - The maximum amount of time the API will attempt a
connection to MCVE
* m_monitor - Perform communication with MCVE (send/receive data)
Non-blocking
* m_numcolumns - Number of columns returned in a comma delimited
response
* m_numrows - Number of rows returned in a comma delimited response
* m_parsecommadelimited - Parse the comma delimited response so
m_getcell, etc will work
* m_responsekeys - Returns array of strings which represents the keys
that can be used for response parameters on this transaction
* m_responseparam - Get a custom response parameter
* m_returnstatus - Check to see if the transaction was successful
* m_setblocking - Set blocking/non-blocking mode for connection
* m_setdropfile - Set the connection method to Drop-File
* m_setip - Set the connection method to IP
* m_setssl_cafile - Set SSL CA (Certificate Authority) file for
verification of server certificate
* m_setssl_files - Set certificate key files and certificates if server
requires client certificate verification
* m_setssl - Set the connection method to SSL
* m_settimeout - Set maximum transaction time (per trans)
* m_sslcert_gen_hash - Generate hash for SSL client certificate
verification
* m_transactionssent - Check to see if outgoing buffer is clear
* m_transinqueue - Number of transactions in client-queue
* m_transkeyval - Add key/value pair to a transaction. Replaces
deprecated transparam()
* m_transnew - Start a new transaction
* m_transsend - Finalize and send the transaction
* m_uwait - Wait x microsecs
* m_validateidentifier - Whether or not to validate the passed
identifier on any transaction it is passed to
* m_verifyconnection - Set whether or not to PING upon connect to verify
connection
* m_verifysslcert - Set whether or not to verify the server ssl
certificate
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* MCVE Functions
* m_checkstatus - Check to see if a transaction has completed
* m_completeauthorizations - Number of complete authorizations in
queue, returning an array of their identifiers
* m_connect - Establish the connection to MCVE
* m_connectionerror - Get a textual representation of why a
connection failed
* m_deletetrans - Delete specified transaction from MCVE_CONN
structure
* m_destroyconn - Destroy the connection and MCVE_CONN structure
* m_destroyengine - Free memory associated with IP/SSL connectivity
* m_getcell - Get a specific cell from a comma delimited response
by column name
* m_getcellbynum - Get a specific cell from a comma delimited
response by column number
* m_getcommadelimited - Get the RAW comma delimited data returned
from MCVE
* m_getheader - Get the name of the column in a comma-delimited
response
* m_initconn - Create and initialize an MCVE_CONN structure
* m_initengine - Ready the client for IP/SSL Communication
* m_iscommadelimited - Checks to see if response is comma delimited
* m_maxconntimeout - The maximum amount of time the API will
attempt a connection to MCVE
* m_monitor - Perform communication with MCVE (send/receive data)
Non-blocking
* m_numcolumns - Number of columns returned in a comma delimited
response
* m_numrows - Number of rows returned in a comma delimited response
* m_parsecommadelimited - Parse the comma delimited response so
m_getcell, etc will work
* m_responsekeys - Returns array of strings which represents the
keys that can be used for response parameters on this transaction
* m_responseparam - Get a custom response parameter
* m_returnstatus - Check to see if the transaction was successful
* m_setblocking - Set blocking/non-blocking mode for connection
* m_setdropfile - Set the connection method to Drop-File
* m_setip - Set the connection method to IP
* m_setssl_cafile - Set SSL CA (Certificate Authority) file for
verification of server certificate
* m_setssl_files - Set certificate key files and certificates if
server requires client certificate verification
* m_setssl - Set the connection method to SSL
* m_settimeout - Set maximum transaction time (per trans)
* m_sslcert_gen_hash - Generate hash for SSL client certificate
verification
* m_transactionssent - Check to see if outgoing buffer is clear
* m_transinqueue - Number of transactions in client-queue
* m_transkeyval - Add key/value pair to a transaction. Replaces
deprecated transparam()
* m_transnew - Start a new transaction
* m_transsend - Finalize and send the transaction
* m_uwait - Wait x microsecs
* m_validateidentifier - Whether or not to validate the passed
identifier on any transaction it is passed to
* m_verifyconnection - Set whether or not to PING upon connect to
verify connection
* m_verifysslcert - Set whether or not to verify the server ssl
certificate
----------------------------------------------------------------------
----------------------------------------------------------------------
SPPLUS Payment System
----------------------------------------------------------------------
Introduction
This extension gives you the possibility to use the >> SPPLUS Payment
System of the Caisse d'Epargne (a French Bank).
Note: This extension is not available on Windows platforms.
Refer to the README files in kit_php's source distribution for
configuration details.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
Note: You need at least PHP 4.1.0 and SPPLUS v.3
Note: You will need to get the new kit_php for spplus. Feel free to
contact the maintainer if you can't get it.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here: >> http://pecl.php.net/package/spplus.
A DLL for this PECL extension is currently unavailable. See also the
building on Windows section.
Note:
PHP 4.3.0 or greater is required for the compression to work.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
This extension has no constants defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
SPPLUS Functions
----------------------------------------------------------------------
calcul_hmac
(PECL spplus >= 1.0.0)
calcul_hmac - Obtain a hmac key (needs 8 arguments)
Description
string calcul_hmac ( string $clent , string $siretcode , string $price ,
string $reference , string $validity , string $taxation , string $devise ,
string $language )
Warning
This function is currently not documented; only its argument list is
available.
Return Values
Returns TRUE on success or FALSE on failure.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
calculhmac
(PECL spplus >= 1.0.0)
calculhmac - Obtain a hmac key (needs 2 arguments)
Description
string calculhmac ( string $clent , string $data )
Warning
This function is currently not documented; only its argument list is
available.
Return Values
Returns TRUE on success or FALSE on failure.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
nthmac
(PECL spplus >= 1.0.0)
nthmac - Obtain a nthmac key (needs 2 arguments)
Description
string nthmac ( string $clent , string $data )
Warning
This function is currently not documented; only its argument list is
available.
Return Values
Returns TRUE on success or FALSE on failure.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
signeurlpaiement
(PECL spplus >= 1.0.0)
signeurlpaiement - Obtain the payment url (needs 2 arguments)
Description
string nthmac ( string $clent , string $data )
Warning
This function is currently not documented; only its argument list is
available.
Return Values
Returns TRUE on success or FALSE on failure.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
Table of Contents
* calcul_hmac - Obtain a hmac key (needs 8 arguments)
* calculhmac - Obtain a hmac key (needs 2 arguments)
* nthmac - Obtain a nthmac key (needs 2 arguments)
* signeurlpaiement - Obtain the payment url (needs 2 arguments)
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* SPPLUS Functions
* calcul_hmac - Obtain a hmac key (needs 8 arguments)
* calculhmac - Obtain a hmac key (needs 2 arguments)
* nthmac - Obtain a nthmac key (needs 2 arguments)
* signeurlpaiement - Obtain the payment url (needs 2 arguments)
----------------------------------------------------------------------
* MCVE - MCVE (Monetra) Payment
* Introduction
* Installing/Configuring
* Predefined Constants
* MCVE Functions
* SPPLUS - SPPLUS Payment System
* Introduction
* Installing/Configuring
* Predefined Constants
* SPPLUS Functions
----------------------------------------------------------------------
----------------------------------------------------------------------
Cryptography Extensions
----------------------------------------------------------------------
Cracklib
----------------------------------------------------------------------
Introduction
These functions allow you to use the CrackLib library to test the
'strength' of a password. The 'strength' of a password is tested by that
checks length, use of upper and lower case and checked against the
specified CrackLib dictionary. CrackLib will also give helpful diagnostic
messages that will help 'strengthen' the password.
Note:
This extension has been moved to the >> PECL repository and is no longer
bundled with PHP as of PHP 5.0.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
More information regarding CrackLib along with the library can be found at
>> http://sourceforge.net/projects/cracklib.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
This >> PECL extension is not bundled with PHP. Information for installing
this PECL extension may be found in the manual chapter titled Installation
of PECL extensions. Additional information such as new releases,
downloads, source files, maintainer information, and a CHANGELOG, can be
located here: >> http://pecl.php.net/package/crack.
In PHP 4 this PECL extensions source can be found in the ext/ directory
within the PHP source or at the PECL link above. In order to use these
functions you must compile PHP with Crack support by using the
--with-crack[=DIR] configuration option.
Windows users will enable php_crack.dll inside of php.ini in order to use
these functions. In PHP 4 this DLL resides in the extensions/ directory
within the PHP Windows binaries download. A DLL for this PECL extension is
currently unavailable. See also the building on Windows section.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Crack configuration options
Name Default Changeable Changelog
PHP_INI_SYSTEM in crack <=
crack.default_dictionary NULL PHP_INI_PERDIR 0.2. Available since PHP
4.0.5. Removed in PHP
5.0.0.
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
The CrackLib extension defines a dictionary resource identifier returned
by crack_opendict().
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
This extension has no constants defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
This example shows how to open a CrackLib dictionary, test a given
password, retrieve any diagnostic messages, and close the dictionary.
Example #1 CrackLib example
Note:
If crack_check() returns TRUE, crack_getlastmessage() will return
'strong password'.
----------------------------------------------------------------------
----------------------------------------------------------------------
Crack Functions
----------------------------------------------------------------------
crack_check
(PECL crack >= 0.1)
crack_check - Performs an obscure check with the given password
Description
bool crack_check ( resource $dictionary , string $password )
bool crack_check ( string $password )
Performs an obscure check with the given password on the specified
dictionary.
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Parameters
dictionary
The crack lib dictionary. If not specified, the last opened
dictionary is used.
password
The tested password.
Return Values
Returns TRUE if password is strong, or FALSE otherwise.
----------------------------------------------------------------------
----------------------------------------------------------------------
crack_closedict
(PECL crack >= 0.1)
crack_closedict - Closes an open CrackLib dictionary
Description
bool crack_closedict ([ resource $dictionary ] )
crack_closedict() closes the specified dictionary identifier.
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Parameters
dictionary
The dictionary to close. If not specified, the current dictionary
is closed.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* crack_opendict() - Opens a new CrackLib dictionary
----------------------------------------------------------------------
----------------------------------------------------------------------
crack_getlastmessage
(PECL crack >= 0.1)
crack_getlastmessage - Returns the message from the last obscure check
Description
string crack_getlastmessage ( void )
crack_getlastmessage() returns the message from the last obscure check.
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Return Values
The message from the last obscure check or FALSE if there was no obscure
checks made so far.
The returned message is one of:
* it's WAY too short
* it is too short
* it does not contain enough DIFFERENT characters
* it is all whitespace
* it is too simplistic/systematic
* it looks like a National Insurance number.
* it is based on a dictionary word
* it is based on a (reversed) dictionary word
* strong password
See Also
* crack_check() - Performs an obscure check with the given password
----------------------------------------------------------------------
----------------------------------------------------------------------
crack_opendict
(PECL crack >= 0.1)
crack_opendict - Opens a new CrackLib dictionary
Description
resource crack_opendict ( string $dictionary )
crack_opendict() opens the specified CrackLib dictionary for use with
crack_check().
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Note:
Only one dictionary may be open at a time.
Parameters
dictionary
The path to the Cracklib dictionary.
Return Values
Returns a dictionary resource identifier on success or FALSE on failure.
See Also
* crack_check() - Performs an obscure check with the given password
* crack_closedict() - Closes an open CrackLib dictionary
----------------------------------------------------------------------
Table of Contents
* crack_check - Performs an obscure check with the given password
* crack_closedict - Closes an open CrackLib dictionary
* crack_getlastmessage - Returns the message from the last obscure check
* crack_opendict - Opens a new CrackLib dictionary
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* Crack Functions
* crack_check - Performs an obscure check with the given password
* crack_closedict - Closes an open CrackLib dictionary
* crack_getlastmessage - Returns the message from the last obscure
check
* crack_opendict - Opens a new CrackLib dictionary
----------------------------------------------------------------------
----------------------------------------------------------------------
HASH Message Digest Framework
----------------------------------------------------------------------
Introduction
Message Digest (hash) engine. Allows direct or incremental processing of
arbitrary length messages using a variety of hashing algorithms.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
The Hash extension requires no external libraries and is enabled by
default as of PHP 5.1.2. It may be explicitly disabled by using the
--disable-hash switch to configure. Earlier versions of PHP may
incorporate the Hash extension by installing the >> PECL module.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
There is no installation needed to use these functions; they are part of
the PHP core.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension defines a Hashing Context resource returned by hash_init().
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
HASH_HMAC (integer)
Optional flag for hash_init(). Indicates that the HMAC
digest-keying algorithm should be applied to the current hashing
context.
----------------------------------------------------------------------
----------------------------------------------------------------------
Hash Functions
----------------------------------------------------------------------
hash_algos
(PHP 5 >= 5.1.2, PECL hash >= 1.1)
hash_algos - Return a list of registered hashing algorithms
Description
array hash_algos ( void )
Return Values
Returns a numerically indexed array containing the list of supported
hashing algorithms.
Changelog
Version Description
5.4.0 Support for joaat, fnv132 and fnv164 was added
5.3.0 Support for md2, ripemd256, ripemd320, salsa10, salsa20, snefru256
and sha224 was added
Examples
Example #1 hash_algos() example
As of PHP 5.3.0, hash_algos() will return the following list of algorithm
names.
The above example will output:
Array
(
[0] => md2
[1] => md4
[2] => md5
[3] => sha1
[4] => sha224
[5] => sha256
[6] => sha384
[7] => sha512
[8] => ripemd128
[9] => ripemd160
[10] => ripemd256
[11] => ripemd320
[12] => whirlpool
[13] => tiger128,3
[14] => tiger160,3
[15] => tiger192,3
[16] => tiger128,4
[17] => tiger160,4
[18] => tiger192,4
[19] => snefru
[20] => snefru256
[21] => gost
[22] => adler32
[23] => crc32
[24] => crc32b
[25] => salsa10
[26] => salsa20
[27] => haval128,3
[28] => haval160,3
[29] => haval192,3
[30] => haval224,3
[31] => haval256,3
[32] => haval128,4
[33] => haval160,4
[34] => haval192,4
[35] => haval224,4
[36] => haval256,4
[37] => haval128,5
[38] => haval160,5
[39] => haval192,5
[40] => haval224,5
[41] => haval256,5
)
----------------------------------------------------------------------
----------------------------------------------------------------------
hash_copy
(PHP 5 >= 5.3.0)
hash_copy - Copy hashing context
Description
resource hash_copy ( resource $context )
Parameters
context
Hashing context returned by hash_init().
Return Values
Returns a copy of Hashing Context resource.
Examples
Example #1 hash_copy() example
The above example will output:
8d777f385d3dfec8815d20f7496026dc
511ae0b1c13f95e5f08f1a0dd3da3d93
----------------------------------------------------------------------
----------------------------------------------------------------------
hash_file
(PHP 5 >= 5.1.2, PECL hash >= 1.1)
hash_file - Generate a hash value using the contents of a given file
Description
string hash_file ( string $algo , string $filename [, bool $raw_output =
false ] )
Parameters
algo
Name of selected hashing algorithm (i.e. "md5", "sha256",
"haval160,4", etc..)
filename
URL describing location of file to be hashed; Supports fopen
wrappers.
raw_output
When set to TRUE, outputs raw binary data. FALSE outputs lowercase
hexits.
Return Values
Returns a string containing the calculated message digest as lowercase
hexits unless raw_output is set to true in which case the raw binary
representation of the message digest is returned.
Examples
Example #1 Using hash_file()
The above example will output:
5c6ffbdd40d9556b73a21e63c3e0e904
See Also
* hash() - Generate a hash value (message digest)
* hash_hmac_file() - Generate a keyed hash value using the HMAC method
and the contents of a given file
* hash_update_file() - Pump data into an active hashing context from a
file
* md5_file() - Calculates the md5 hash of a given file
* sha1_file() - Calculate the sha1 hash of a file
----------------------------------------------------------------------
----------------------------------------------------------------------
hash_final
(PHP 5 >= 5.1.2, PECL hash >= 1.1)
hash_final - Finalize an incremental hash and return resulting digest
Description
string hash_final ( resource $context [, bool $raw_output = false ] )
Parameters
context
Hashing context returned by hash_init().
raw_output
When set to TRUE, outputs raw binary data. FALSE outputs lowercase
hexits.
Return Values
Returns a string containing the calculated message digest as lowercase
hexits unless raw_output is set to true in which case the raw binary
representation of the message digest is returned.
Examples
Example #1 hash_final() example
The above example will output:
c0854fb9fb03c41cce3802cb0d220529e6eef94e
See Also
* hash_init() - Initialize an incremental hashing context
* hash_update() - Pump data into an active hashing context
* hash_update_stream() - Pump data into an active hashing context from
an open stream
* hash_update_file() - Pump data into an active hashing context from a
file
----------------------------------------------------------------------
----------------------------------------------------------------------
hash_hmac_file
(PHP 5 >= 5.1.2, PECL hash >= 1.1)
hash_hmac_file - Generate a keyed hash value using the HMAC method and the
contents of a given file
Description
string hash_hmac_file ( string $algo , string $filename , string $key [,
bool $raw_output = false ] )
Parameters
algo
Name of selected hashing algorithm (i.e. "md5", "sha256",
"haval160,4", etc..) See hash_algos() for a list of supported
algorithms.
filename
URL describing location of file to be hashed; Supports fopen
wrappers.
key
Shared secret key used for generating the HMAC variant of the
message digest.
raw_output
When set to TRUE, outputs raw binary data. FALSE outputs lowercase
hexits.
Return Values
Returns a string containing the calculated message digest as lowercase
hexits unless raw_output is set to true in which case the raw binary
representation of the message digest is returned.
Examples
Example #1 hash_hmac_file() example
The above example will output:
7eb2b5c37443418fc77c136dd20e859c
See Also
* hash_algos() - Return a list of registered hashing algorithms
* hash_hmac() - Generate a keyed hash value using the HMAC method
* hash_file() - Generate a hash value using the contents of a given file
----------------------------------------------------------------------
----------------------------------------------------------------------
hash_hmac
(PHP 5 >= 5.1.2, PECL hash >= 1.1)
hash_hmac - Generate a keyed hash value using the HMAC method
Description
string hash_hmac ( string $algo , string $data , string $key [, bool
$raw_output = false ] )
Parameters
algo
Name of selected hashing algorithm (i.e. "md5", "sha256",
"haval160,4", etc..) See hash_algos() for a list of supported
algorithms.
data
Message to be hashed.
key
Shared secret key used for generating the HMAC variant of the
message digest.
raw_output
When set to TRUE, outputs raw binary data. FALSE outputs lowercase
hexits.
Return Values
Returns a string containing the calculated message digest as lowercase
hexits unless raw_output is set to true in which case the raw binary
representation of the message digest is returned.
Examples
Example #1 hash_hmac() example
The above example will output:
b8e7ae12510bdfb1812e463a7f086122cf37e4f7
See Also
* hash() - Generate a hash value (message digest)
* hash_algos() - Return a list of registered hashing algorithms
* hash_init() - Initialize an incremental hashing context
* hash_hmac_file() - Generate a keyed hash value using the HMAC method
and the contents of a given file
----------------------------------------------------------------------
----------------------------------------------------------------------
hash_init
(PHP 5 >= 5.1.2, PECL hash >= 1.1)
hash_init - Initialize an incremental hashing context
Description
resource hash_init ( string $algo [, int $options = 0 [, string $key =
NULL ]] )
Parameters
algo
Name of selected hashing algorithm (i.e. "md5", "sha256",
"haval160,4", etc..)
options
Optional settings for hash generation, currently supports only one
option: HASH_HMAC. When specified, the key must be specified.
key
When HASH_HMAC is specified for options, a shared secret key to be
used with the HMAC hashing method must be supplied in this
parameter.
Return Values
Returns a Hashing Context resource for use with hash_update(),
hash_update_stream(), hash_update_file(), and hash_final().
Examples
Example #1 Incremental hashing example
The above example will output:
5c6ffbdd40d9556b73a21e63c3e0e904
See Also
* hash() - Generate a hash value (message digest)
* hash_file() - Generate a hash value using the contents of a given file
* hash_hmac() - Generate a keyed hash value using the HMAC method
* hash_hmac_file() - Generate a keyed hash value using the HMAC method
and the contents of a given file
----------------------------------------------------------------------
----------------------------------------------------------------------
hash_update_file
(PHP 5 >= 5.1.2, PECL hash >= 1.1)
hash_update_file - Pump data into an active hashing context from a file
Description
bool hash_update_file ( resource $context , string $filename [, resource
$context = NULL ] )
Parameters
context
Hashing context returned by hash_init().
filename
URL describing location of file to be hashed; Supports fopen
wrappers.
context
Stream context as returned by stream_context_create().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* hash_init() - Initialize an incremental hashing context
* hash_update() - Pump data into an active hashing context
* hash_update_stream() - Pump data into an active hashing context from
an open stream
* hash_final() - Finalize an incremental hash and return resulting
digest
* hash() - Generate a hash value (message digest)
* hash_file() - Generate a hash value using the contents of a given file
----------------------------------------------------------------------
----------------------------------------------------------------------
hash_update_stream
(PHP 5 >= 5.1.2, PECL hash >= 1.1)
hash_update_stream - Pump data into an active hashing context from an open
stream
Description
int hash_update_stream ( resource $context , resource $handle [, int
$length = -1 ] )
Parameters
context
Hashing context returned by hash_init().
handle
Open file handle as returned by any stream creation function.
length
Maximum number of characters to copy from handle into the hashing
context.
Return Values
Actual number of bytes added to the hashing context from handle.
Examples
Example #1 hash_update_stream() example
The above example will output:
5c6ffbdd40d9556b73a21e63c3e0e904
See Also
* hash_init() - Initialize an incremental hashing context
* hash_update() - Pump data into an active hashing context
* hash_final() - Finalize an incremental hash and return resulting
digest
* hash() - Generate a hash value (message digest)
* hash_file() - Generate a hash value using the contents of a given file
----------------------------------------------------------------------
----------------------------------------------------------------------
hash_update
(PHP 5 >= 5.1.2, PECL hash >= 1.1)
hash_update - Pump data into an active hashing context
Description
bool hash_update ( resource $context , string $data )
Parameters
context
Hashing context returned by hash_init().
data
Message to be included in the hash digest.
Return Values
Returns TRUE.
See Also
* hash_init() - Initialize an incremental hashing context
* hash_update_file() - Pump data into an active hashing context from a
file
* hash_update_stream() - Pump data into an active hashing context from
an open stream
* hash_final() - Finalize an incremental hash and return resulting
digest
----------------------------------------------------------------------
----------------------------------------------------------------------
hash
(PHP 5 >= 5.1.2, PECL hash >= 1.1)
hash - Generate a hash value (message digest)
Description
string hash ( string $algo , string $data [, bool $raw_output = false ] )
Parameters
algo
Name of selected hashing algorithm (i.e. "md5", "sha256",
"haval160,4", etc..)
data
Message to be hashed.
raw_output
When set to TRUE, outputs raw binary data. FALSE outputs lowercase
hexits.
Return Values
Returns a string containing the calculated message digest as lowercase
hexits unless raw_output is set to true in which case the raw binary
representation of the message digest is returned.
Examples
Example #1 A hash() example
The above example will output:
ec457d0a974c48d5685a7efa03d137dc8bbde7e3
See Also
* hash_file() - Generate a hash value using the contents of a given file
* hash_hmac() - Generate a keyed hash value using the HMAC method
* hash_init() - Initialize an incremental hashing context
* md5() - Calculate the md5 hash of a string
* sha1() - Calculate the sha1 hash of a string
----------------------------------------------------------------------
Table of Contents
* hash_algos - Return a list of registered hashing algorithms
* hash_copy - Copy hashing context
* hash_file - Generate a hash value using the contents of a given file
* hash_final - Finalize an incremental hash and return resulting digest
* hash_hmac_file - Generate a keyed hash value using the HMAC method and
the contents of a given file
* hash_hmac - Generate a keyed hash value using the HMAC method
* hash_init - Initialize an incremental hashing context
* hash_update_file - Pump data into an active hashing context from a
file
* hash_update_stream - Pump data into an active hashing context from an
open stream
* hash_update - Pump data into an active hashing context
* hash - Generate a hash value (message digest)
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Hash Functions
* hash_algos - Return a list of registered hashing algorithms
* hash_copy - Copy hashing context
* hash_file - Generate a hash value using the contents of a given
file
* hash_final - Finalize an incremental hash and return resulting
digest
* hash_hmac_file - Generate a keyed hash value using the HMAC
method and the contents of a given file
* hash_hmac - Generate a keyed hash value using the HMAC method
* hash_init - Initialize an incremental hashing context
* hash_update_file - Pump data into an active hashing context from
a file
* hash_update_stream - Pump data into an active hashing context
from an open stream
* hash_update - Pump data into an active hashing context
* hash - Generate a hash value (message digest)
----------------------------------------------------------------------
----------------------------------------------------------------------
Mcrypt
----------------------------------------------------------------------
Introduction
This is an interface to the mcrypt library, which supports a wide variety
of block algorithms such as DES, TripleDES, Blowfish (default), 3-WAY,
SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST in CBC, OFB, CFB and
ECB cipher modes. Additionally, it supports RC6 and IDEA which are
considered "non-free". CFB/OFB are 8bit by default.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
These functions work using >> mcrypt. To use it, download
libmcrypt-x.x.tar.gz from >> http://mcrypt.sourceforge.net/ and follow the
included installation instructions.
As of PHP 5.0.0 you will need libmcrypt Version 2.5.6 or greater.
Windows users will find the library is the PHP 5.2 Windows binaries
release. PHP 5.3 Windows binaries uses the static version of the MCrypt
library, no DLL are needed.
If you linked against libmcrypt 2.4.x or higher, the following additional
block algorithms are supported: CAST, LOKI97, RIJNDAEL, SAFERPLUS, SERPENT
and the following stream ciphers: ENIGMA (crypt), PANAMA, RC4 and WAKE.
With libmcrypt 2.4.x or higher another cipher mode is also available;
nOFB.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
You need to compile PHP with the --with-mcrypt[=DIR] parameter to enable
this extension. DIR is the mcrypt install directory. Make sure you compile
libmcrypt with the option --disable-posix-threads .
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Mcrypt configuration options
Name Default Changeable Changelog
mcrypt.algorithms_dir NULL PHP_INI_ALL
mcrypt.modes_dir NULL PHP_INI_ALL
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
mcrypt.algorithms_dir string
The directory that contains the algorithms. Defaults to the
directories compiled within libmcrypt, which is typically
/usr/local/lib/libmcrypt. See mcrypt_list_algorithms() for
additional details.
mcrypt.modes_dir string
The directory that contains the modes. Defaults to the directories
compiled within libmcrypt, which is typically
/usr/local/lib/libmcrypt. See mcrypt_list_modes() for additional
details.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
mcrypt_module_open() returns an encryption descriptor.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
Mcrypt can operate in four block cipher modes (CBC, OFB, CFB, and ECB). If
linked against libmcrypt-2.4.x or higher the functions can also operate in
the block cipher mode nOFB and in STREAM mode. Below you find a list with
all supported encryption modes together with the constants that are
defines for the encryption mode. For a more complete reference and
discussion see Applied Cryptography by Schneier (ISBN 0-471-11709-9).
* MCRYPT_MODE_ECB (electronic codebook) is suitable for random data,
such as encrypting other keys. Since data there is short and random,
the disadvantages of ECB have a favorable negative effect.
* MCRYPT_MODE_CBC (cipher block chaining) is especially suitable for
encrypting files where the security is increased over ECB
significantly.
* MCRYPT_MODE_CFB (cipher feedback) is the best mode for encrypting byte
streams where single bytes must be encrypted.
* MCRYPT_MODE_OFB (output feedback, in 8bit) is comparable to CFB, but
can be used in applications where error propagation cannot be
tolerated. It's insecure (because it operates in 8bit mode) so it is
not recommended to use it.
* MCRYPT_MODE_NOFB (output feedback, in nbit) is comparable to OFB, but
more secure because it operates on the block size of the algorithm.
* MCRYPT_MODE_STREAM is an extra mode to include some stream algorithms
like "WAKE" or "RC4".
Some other mode and random device constants:
MCRYPT_ENCRYPT (integer)
MCRYPT_DECRYPT (integer)
MCRYPT_DEV_RANDOM (integer)
MCRYPT_DEV_URANDOM (integer)
MCRYPT_RAND (integer)
----------------------------------------------------------------------
----------------------------------------------------------------------
Mcrypt ciphers
Here is a list of ciphers which are currently supported by the mcrypt
extension. For a complete list of supported ciphers, see the defines at
the end of mcrypt.h. The general rule with the mcrypt-2.2.x API is that
you can access the cipher from PHP with MCRYPT_ciphername. With the
libmcrypt-2.4.x and libmcrypt-2.5.x API these constants also work, but it
is possible to specify the name of the cipher as a string with a call to
mcrypt_module_open().
* MCRYPT_3DES
* MCRYPT_ARCFOUR_IV (libmcrypt > 2.4.x only)
* MCRYPT_ARCFOUR (libmcrypt > 2.4.x only)
* MCRYPT_BLOWFISH
* MCRYPT_CAST_128
* MCRYPT_CAST_256
* MCRYPT_CRYPT
* MCRYPT_DES
* MCRYPT_DES_COMPAT (libmcrypt 2.2.x only)
* MCRYPT_ENIGMA (libmcrypt > 2.4.x only, alias for MCRYPT_CRYPT)
* MCRYPT_GOST
* MCRYPT_IDEA (non-free)
* MCRYPT_LOKI97 (libmcrypt > 2.4.x only)
* MCRYPT_MARS (libmcrypt > 2.4.x only, non-free)
* MCRYPT_PANAMA (libmcrypt > 2.4.x only)
* MCRYPT_RIJNDAEL_128 (libmcrypt > 2.4.x only)
* MCRYPT_RIJNDAEL_192 (libmcrypt > 2.4.x only)
* MCRYPT_RIJNDAEL_256 (libmcrypt > 2.4.x only)
* MCRYPT_RC2
* MCRYPT_RC4 (libmcrypt 2.2.x only)
* MCRYPT_RC6 (libmcrypt > 2.4.x only)
* MCRYPT_RC6_128 (libmcrypt 2.2.x only)
* MCRYPT_RC6_192 (libmcrypt 2.2.x only)
* MCRYPT_RC6_256 (libmcrypt 2.2.x only)
* MCRYPT_SAFER64
* MCRYPT_SAFER128
* MCRYPT_SAFERPLUS (libmcrypt > 2.4.x only)
* MCRYPT_SERPENT(libmcrypt > 2.4.x only)
* MCRYPT_SERPENT_128 (libmcrypt 2.2.x only)
* MCRYPT_SERPENT_192 (libmcrypt 2.2.x only)
* MCRYPT_SERPENT_256 (libmcrypt 2.2.x only)
* MCRYPT_SKIPJACK (libmcrypt > 2.4.x only)
* MCRYPT_TEAN (libmcrypt 2.2.x only)
* MCRYPT_THREEWAY
* MCRYPT_TRIPLEDES (libmcrypt > 2.4.x only)
* MCRYPT_TWOFISH (for older mcrypt 2.x versions, or mcrypt > 2.4.x )
* MCRYPT_TWOFISH128 (TWOFISHxxx are available in newer 2.x versions, but
not in the 2.4.x versions)
* MCRYPT_TWOFISH192
* MCRYPT_TWOFISH256
* MCRYPT_WAKE (libmcrypt > 2.4.x only)
* MCRYPT_XTEA (libmcrypt > 2.4.x only)
You must (in CFB and OFB mode) or can (in CBC mode) supply an
initialization vector (IV) to the respective cipher function. The IV must
be unique and must be the same when decrypting/encrypting. With data which
is stored encrypted, you can take the output of a function of the index
under which the data is stored (e.g. the MD5 key of the filename).
Alternatively, you can transmit the IV together with the encrypted data
(see chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9)
for a discussion of this topic).
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Mcrypt can be used to encrypt and decrypt using the above mentioned
ciphers. If you linked against libmcrypt-2.2.x, the four important mcrypt
commands (mcrypt_cfb(), mcrypt_cbc(), mcrypt_ecb(), and mcrypt_ofb()) can
operate in both modes which are named MCRYPT_ENCRYPT and MCRYPT_DECRYPT,
respectively.
Example #1 Encrypt an input value with TripleDES under 2.2.x in ECB mode
This example will give you the encrypted data as a string in
$encrypted_data.
If you linked against libmcrypt 2.4.x or 2.5.x, these functions are still
available, but it is recommended that you use the advanced functions.
Example #2 Encrypt an input value with TripleDES under 2.4.x and higher in
ECB mode
This example will give you the encrypted data as a string in
$encrypted_data. For a full example see mcrypt_module_open().
----------------------------------------------------------------------
----------------------------------------------------------------------
Mcrypt Functions
----------------------------------------------------------------------
mcrypt_cbc
(PHP 4, PHP 5)
mcrypt_cbc - Encrypts/decrypts data in CBC mode
Description
string mcrypt_cbc ( int $cipher , string $key , string $data , int $mode
[, string $iv ] )
string mcrypt_cbc ( string $cipher , string $key , string $data , int
$mode [, string $iv ] )
The first prototype is when linked against libmcrypt 2.2.x, the second
when linked against libmcrypt 2.4.x or higher. The mode should be either
MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
This function should not be used anymore, see mcrypt_generic() and
mdecrypt_generic() for replacements.
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_cfb
(PHP 4, PHP 5)
mcrypt_cfb - Encrypts/decrypts data in CFB mode
Description
string mcrypt_cfb ( int $cipher , string $key , string $data , int $mode ,
string $iv )
string mcrypt_cfb ( string $cipher , string $key , string $data , int
$mode [, string $iv ] )
The first prototype is when linked against libmcrypt 2.2.x, the second
when linked against libmcrypt 2.4.x or higher. The mode should be either
MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
This function should not be used anymore, see mcrypt_generic() and
mdecrypt_generic() for replacements.
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_create_iv
(PHP 4, PHP 5)
mcrypt_create_iv - Creates an initialization vector (IV) from a random
source
Description
string mcrypt_create_iv ( int $size [, int $source = MCRYPT_DEV_RANDOM ] )
Creates an initialization vector (IV) from a random source.
The IV is only meant to give an alternative seed to the encryption
routines. This IV does not need to be secret at all, though it can be
desirable. You even can send it along with your ciphertext without losing
security.
Parameters
size
The size of the IV.
source
The source of the IV. The source can be MCRYPT_RAND (system random
number generator), MCRYPT_DEV_RANDOM (read data from /dev/random)
and MCRYPT_DEV_URANDOM (read data from /dev/urandom). Prior to
5.3.0, MCRYPT_RAND was the only one supported on Windows.
Return Values
Returns the initialization vector, or FALSE on error.
Changelog
Version Description
5.3.0 MCRYPT_DEV_RANDOM and MCRYPT_DEV_URANDOM became available on
Windows platforms.
5.3.0 It is no longer required to call srand() first. This is now done
automatically.
Examples
Example #1 mcrypt_create_iv() Example
See Also
* >> http://www.ciphersbyritter.com/GLOSSARY.HTM#IV
* >> http://www.quadibloc.com/crypto/co0409.htm
* Chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9)
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_decrypt
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_decrypt - Decrypts crypttext with given parameters
Description
string mcrypt_decrypt ( string $cipher , string $key , string $data ,
string $mode [, string $iv ] )
Decrypts the data and returns the unencrypted data.
Parameters
cipher
One of the MCRYPT_ciphername constants, or the name of the
algorithm as string.
key
The key with which the data was encrypted. If it's smaller than
the required keysize, it is padded with '\0'.
data
The data that will be decrypted with the given cipher and mode. If
the size of the data is not n * blocksize, the data will be padded
with '\0'.
mode
One of the MCRYPT_MODE_modename constants, or one of the following
strings: "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".
iv
The iv parameter is used for the initialization in CBC, CFB, OFB
modes, and in some algorithms in STREAM mode. If you do not supply
an IV, while it is needed for an algorithm, the function issues a
warning and uses an IV with all its bytes set to '\0'.
Return Values
Returns the decrypted data as a string.
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_ecb
(PHP 4, PHP 5)
mcrypt_ecb - Deprecated: Encrypts/decrypts data in ECB mode
Description
string mcrypt_ecb ( int $cipher , string $key , string $data , int $mode )
string mcrypt_ecb ( string $cipher , string $key , string $data , int
$mode [, string $iv ] )
The first prototype is when linked against libmcrypt 2.2.x, the second
when linked against libmcrypt 2.4.x or higher. The mode should be either
MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
This function is deprecated and should not be used anymore, see
mcrypt_generic() and mdecrypt_generic() for replacements.
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_enc_get_algorithms_name
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_enc_get_algorithms_name - Returns the name of the opened algorithm
Description
string mcrypt_enc_get_algorithms_name ( resource $td )
This function returns the name of the algorithm.
Parameters
td
The encryption descriptor.
Return Values
Returns the name of the opened algorithm as a string.
Examples
Example #1 mcrypt_enc_get_algorithms_name() example
The above example will output:
CAST-256
CAST-256
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_enc_get_block_size
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_enc_get_block_size - Returns the blocksize of the opened algorithm
Description
int mcrypt_enc_get_block_size ( resource $td )
Gets the blocksize of the opened algorithm.
Parameters
td
The encryption descriptor.
Return Values
Returns the block size of the specified algorithm in bytes.
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_enc_get_iv_size
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_enc_get_iv_size - Returns the size of the IV of the opened
algorithm
Description
int mcrypt_enc_get_iv_size ( resource $td )
This function returns the size of the IV of the algorithm specified by the
encryption descriptor in bytes. An IV is used in cbc, cfb and ofb modes,
and in some algorithms in stream mode.
Parameters
td
The encryption descriptor.
Return Values
Returns the size of the IV, or 0 if the IV is ignored by the algorithm.
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_enc_get_key_size
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_enc_get_key_size - Returns the maximum supported keysize of the
opened mode
Description
int mcrypt_enc_get_key_size ( resource $td )
Gets the maximum supported key size of the algorithm in bytes.
Parameters
td
The encryption descriptor.
Return Values
Returns the maximum supported key size of the algorithm in bytes.
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_enc_get_modes_name
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_enc_get_modes_name - Returns the name of the opened mode
Description
string mcrypt_enc_get_modes_name ( resource $td )
This function returns the name of the mode.
Parameters
td
The encryption descriptor.
Return Values
Returns the name as a string.
Examples
Example #1 mcrypt_enc_get_modes_name() example
The above example will output:
CFB
ECB
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_enc_get_supported_key_sizes
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_enc_get_supported_key_sizes - Returns an array with the supported
keysizes of the opened algorithm
Description
array mcrypt_enc_get_supported_key_sizes ( resource $td )
Gets the supported key sizes of the opened algorithm.
Parameters
td
The encryption descriptor.
Return Values
Returns an array with the key sizes supported by the algorithm specified
by the encryption descriptor. If it returns an empty array then all key
sizes between 1 and mcrypt_enc_get_key_size() are supported by the
algorithm.
Examples
Example #1 mcrypt_enc_get_supported_key_sizes() example
The above example will output:
array(3) {
[0]=>
int(16)
[1]=>
int(24)
[2]=>
int(32)
}
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_enc_is_block_algorithm_mode
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_enc_is_block_algorithm_mode - Checks whether the encryption of the
opened mode works on blocks
Description
bool mcrypt_enc_is_block_algorithm_mode ( resource $td )
Tells whether the algorithm of the opened mode works on blocks (e.g. FALSE
for stream, and TRUE for cbc, cfb, ofb)..
Parameters
td
The encryption descriptor.
Return Values
Returns TRUE if the mode is for use with block algorithms, otherwise it
returns FALSE.
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_enc_is_block_algorithm
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_enc_is_block_algorithm - Checks whether the algorithm of the opened
mode is a block algorithm
Description
bool mcrypt_enc_is_block_algorithm ( resource $td )
Tells whether the algorithm of the opened mode is a block algorithm.
Parameters
td
The encryption descriptor.
Return Values
Returns TRUE if the algorithm is a block algorithm or FALSE if it is a
stream one.
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_enc_is_block_mode
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_enc_is_block_mode - Checks whether the opened mode outputs blocks
Description
bool mcrypt_enc_is_block_mode ( resource $td )
Tells whether the opened mode outputs blocks (e.g. TRUE for cbc and ecb,
and FALSE for cfb and stream).
Parameters
td
The encryption descriptor.
Return Values
Returns TRUE if the mode outputs blocks of bytes, or FALSE if it outputs
just bytes.
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_enc_self_test
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_enc_self_test - Runs a self test on the opened module
Description
int mcrypt_enc_self_test ( resource $td )
This function runs the self test on the algorithm specified by the
descriptor td.
Parameters
td
The encryption descriptor.
Return Values
If the self test succeeds it returns FALSE. In case of an error, it
returns TRUE.
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_encrypt
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_encrypt - Encrypts plaintext with given parameters
Description
string mcrypt_encrypt ( string $cipher , string $key , string $data ,
string $mode [, string $iv ] )
Encrypts the data and returns it.
Parameters
cipher
One of the MCRYPT_ciphername constants, or the name of the
algorithm as string.
key
The key with which the data will be encrypted. If it's smaller
than the required keysize, it is padded with '\0'. It is better
not to use ASCII strings for keys.
It is recommended to use the mhash functions to create a key from
a string.
data
The data that will be encrypted with the given cipher and mode. If
the size of the data is not n * blocksize, the data will be padded
with '\0'.
The returned crypttext can be larger than the size of the data
that was given by data.
mode
One of the MCRYPT_MODE_modename constants, or one of the following
strings: "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".
iv
Used for the initialization in CBC, CFB, OFB modes, and in some
algorithms in STREAM mode. If you do not supply an IV, while it is
needed for an algorithm, the function issues a warning and uses an
IV with all its bytes set to '\0'.
Return Values
Returns the encrypted data, as a string.
Examples
Example #1 mcrypt_encrypt() Example
The above example will output:
42
64
See also mcrypt_module_open() for a more advanced API and an example.
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_generic_deinit
(PHP 4 >= 4.0.7, PHP 5)
mcrypt_generic_deinit - This function deinitializes an encryption module
Description
bool mcrypt_generic_deinit ( resource $td )
This function terminates encryption specified by the encryption descriptor
(td). It clears all buffers, but does not close the module. You need to
call mcrypt_module_close() yourself. (But PHP does this for you at the end
of the script.)
Parameters
td
The encryption descriptor.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* mcrypt_module_open() - Opens the module of the algorithm and the mode
to be used
* mcrypt_generic_init() - This function initializes all buffers needed
for encryption
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_generic_end
(PHP 4 >= 4.0.2, PHP 5 <= 5.1.6)
mcrypt_generic_end - This function terminates encryption
Description
bool mcrypt_generic_end ( resource $td )
Warning
This function is deprecated, use mcrypt_generic_deinit() instead. It can
cause crashes when used with mcrypt_module_close() due to multiple buffer
frees.
This function terminates encryption specified by the encryption descriptor
(td). Actually it clears all buffers, and closes all the modules used.
Returns FALSE on error, or TRUE on success.
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_generic_init
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_generic_init - This function initializes all buffers needed for
encryption
Description
int mcrypt_generic_init ( resource $td , string $key , string $iv )
You need to call this function before every call to mcrypt_generic() or
mdecrypt_generic().
Parameters
td
The encryption descriptor.
key
The maximum length of the key should be the one obtained by
calling mcrypt_enc_get_key_size() and every value smaller than
this is legal.
iv
The IV should normally have the size of the algorithms block size,
but you must obtain the size by calling mcrypt_enc_get_iv_size().
IV is ignored in ECB. IV MUST exist in CFB, CBC, STREAM, nOFB and
OFB modes. It needs to be random and unique (but not secret). The
same IV must be used for encryption/decryption. If you do not want
to use it you should set it to zeros, but this is not recommended.
Return Values
The function returns a negative value on error: -3 when the key length was
incorrect, -4 when there was a memory allocation problem and any other
return value is an unknown error. If an error occurs a warning will be
displayed accordingly. FALSE is returned if incorrect parameters were
passed.
See Also
* mcrypt_module_open() - Opens the module of the algorithm and the mode
to be used
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_generic
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_generic - This function encrypts data
Description
string mcrypt_generic ( resource $td , string $data )
This function encrypts data. The data is padded with "\0" to make sure the
length of the data is n * blocksize. This function returns the encrypted
data. Note that the length of the returned string can in fact be longer
than the input, due to the padding of the data.
If you want to store the encrypted data in a database make sure to store
the entire string as returned by mcrypt_generic, or the string will not
entirely decrypt properly. If your original string is 10 characters long
and the block size is 8 (use mcrypt_enc_get_block_size() to determine the
blocksize), you would need at least 16 characters in your database field.
Note the string returned by mdecrypt_generic() will be 16 characters as
well...use rtrim($str, "\0") to remove the padding.
If you are for example storing the data in a MySQL database remember that
varchar fields automatically have trailing spaces removed during
insertion. As encrypted data can end in a space (ASCII 32), the data will
be damaged by this removal. Store data in a tinyblob/tinytext (or larger)
field instead.
Parameters
td
The encryption descriptor.
The encryption handle should always be initialized with
mcrypt_generic_init() with a key and an IV before calling this
function. Where the encryption is done, you should free the
encryption buffers by calling mcrypt_generic_deinit(). See
mcrypt_module_open() for an example.
data
The data to encrypt.
Return Values
Returns the encrypted data.
See Also
* mdecrypt_generic() - Decrypts data
* mcrypt_generic_init() - This function initializes all buffers needed
for encryption
* mcrypt_generic_deinit() - This function deinitializes an encryption
module
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_get_block_size
(PHP 4, PHP 5)
mcrypt_get_block_size - Gets the block size of the specified cipher
Description
int mcrypt_get_block_size ( int $cipher )
int mcrypt_get_block_size ( string $cipher , string $module )
The first prototype is when linked against libmcrypt 2.2.x, the second
when linked against libmcrypt 2.4.x or 2.5.x.
mcrypt_get_block_size() is used to get the size of a block of the
specified cipher (in combination with an encryption mode).
It is more useful to use the mcrypt_enc_get_block_size() function as this
uses the resource returned by mcrypt_module_open().
Parameters
cipher
One of the MCRYPT_ciphername constants or the name of the
algorithm as string.
module
The module.
Return Values
Gets the block size, as an integer.
Examples
Example #1 mcrypt_get_block_size() example
This example shows how to use this function when linked against libmcrypt
2.4.x and 2.5.x.
See Also
* mcrypt_get_key_size() - Gets the key size of the specified cipher
* mcrypt_enc_get_block_size() - Returns the blocksize of the opened
algorithm
* mcrypt_encrypt() - Encrypts plaintext with given parameters
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_get_cipher_name
(PHP 4, PHP 5)
mcrypt_get_cipher_name - Gets the name of the specified cipher
Description
string mcrypt_get_cipher_name ( int $cipher )
string mcrypt_get_cipher_name ( string $cipher )
mcrypt_get_cipher_name() is used to get the name of the specified cipher.
mcrypt_get_cipher_name() takes the cipher number as an argument (libmcrypt
2.2.x) or takes the cipher name as an argument (libmcrypt 2.4.x or higher)
and returns the name of the cipher or FALSE, if the cipher does not exist.
Parameters
cipher
One of the MCRYPT_ciphername constants or the name of the
algorithm as string.
Return Values
This function returns the name of the cipher or FALSE, if the cipher does
not exist.
Examples
Example #1 mcrypt_get_cipher_name() Example
The above example will output:
3DES
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_get_iv_size
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_get_iv_size - Returns the size of the IV belonging to a specific
cipher/mode combination
Description
int mcrypt_get_iv_size ( string $cipher , string $mode )
Gets the size of the IV belonging to a specific cipher/mode combination.
It is more useful to use the mcrypt_enc_get_iv_size() function as this
uses the resource returned by mcrypt_module_open().
Parameters
cipher
One of the MCRYPT_ciphername constants, or the name of the
algorithm as string.
mode
One of the MCRYPT_MODE_modename constants, or one of the following
strings: "ecb", "cbc", "cfb", "ofb", "nofb" or "stream". The IV is
ignored in ECB mode as this mode does not require it. You will
need to have the same IV (think: starting point) both at
encryption and decryption stages, otherwise your encryption will
fail.
Return Values
Returns the size of the Initialization Vector (IV) in bytes. On error the
function returns FALSE. If the IV is ignored in the specified cipher/mode
combination zero is returned.
Examples
Example #1 mcrypt_get_iv_size() Example
See Also
* mcrypt_get_block_size() - Gets the block size of the specified cipher
* mcrypt_enc_get_iv_size() - Returns the size of the IV of the opened
algorithm
* mcrypt_create_iv() - Creates an initialization vector (IV) from a
random source
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_get_key_size
(PHP 4, PHP 5)
mcrypt_get_key_size - Gets the key size of the specified cipher
Description
int mcrypt_get_key_size ( int $cipher )
int mcrypt_get_key_size ( string $cipher , string $module )
The first prototype is when linked against libmcrypt 2.2.x, the second
when linked against libmcrypt 2.4.x or 2.5.x.
mcrypt_get_key_size() is used to get the size of a key of the specified
cipher (in combination with an encryption mode).
It is more useful to use the mcrypt_enc_get_key_size() function as this
uses the resource returned by mcrypt_module_open().
Examples
Example #1 mcrypt_get_key_size() Example
The example above shows how to use this function when linked against
libmcrypt 2.4.x or 2.5.x.
The above example will output:
24
See Also
* mcrypt_get_block_size() - Gets the block size of the specified cipher
* mcrypt_enc_get_key_size() - Returns the maximum supported keysize of
the opened mode
* mcrypt_encrypt() - Encrypts plaintext with given parameters
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_list_algorithms
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_list_algorithms - Gets an array of all supported ciphers
Description
array mcrypt_list_algorithms ([ string $lib_dir =
ini_get("mcrypt.algorithms_dir") ] )
Gets the list of all supported algorithms in the lib_dir parameter.
Parameters
lib_dir
Specifies the directory where all algorithms are located. If not
specified, the value of the mcrypt.algorithms_dir php.ini
directive is used.
Return Values
Returns an array with all the supported algorithms.
Examples
Example #1 mcrypt_list_algorithms() Example
\n";
}
?>
The example above will produce a list with all supported algorithms in the
"/usr/local/lib/libmcrypt" directory.
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_list_modes
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_list_modes - Gets an array of all supported modes
Description
array mcrypt_list_modes ([ string $lib_dir = ini_get("mcrypt.modes_dir") ]
)
Gets the list of all supported modes in the lib_dir parameter.
Parameters
lib_dir
Specifies the directory where all modes are located. If not
specified, the value of the mcrypt.modes_dir php.ini directive is
used.
Return Values
Returns an array with all the supported modes.
Examples
Example #1 mcrypt_list_modes() Example
\n";
}
?>
The example above will produce a list with all supported algorithms in the
default mode directory. If it is not set with the mcrypt.modes_dir php.ini
directive, the default directory of mcrypt is used (which is
/usr/local/lib/libmcrypt).
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_module_close
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_close - Closes the mcrypt module
Description
bool mcrypt_module_close ( resource $td )
Closes the specified encryption handle.
Parameters
td
The encryption descriptor.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* mcrypt_module_open() - Opens the module of the algorithm and the mode
to be used
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_module_get_algo_block_size
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_get_algo_block_size - Returns the blocksize of the specified
algorithm
Description
int mcrypt_module_get_algo_block_size ( string $algorithm [, string
$lib_dir ] )
Gets the blocksize of the specified algorithm.
Parameters
algorithm
The algorithm name.
lib_dir
This optional parameter can contain the location where the mode
module is on the system.
Return Values
Returns the block size of the algorithm specified in bytes.
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_module_get_algo_key_size
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_get_algo_key_size - Returns the maximum supported keysize of
the opened mode
Description
int mcrypt_module_get_algo_key_size ( string $algorithm [, string $lib_dir
] )
Gets the maximum supported keysize of the opened mode.
Parameters
algorithm
The algorithm name.
lib_dir
This optional parameter can contain the location where the mode
module is on the system.
Return Values
This function returns the maximum supported key size of the algorithm
specified in bytes.
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_module_get_supported_key_sizes
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_get_supported_key_sizes - Returns an array with the
supported keysizes of the opened algorithm
Description
array mcrypt_module_get_supported_key_sizes ( string $algorithm [, string
$lib_dir ] )
Returns an array with the key sizes supported by the specified algorithm.
If it returns an empty array then all key sizes between 1 and
mcrypt_module_get_algo_key_size() are supported by the algorithm.
Parameters
algorithm
The algorithm to be used.
lib_dir
The optional lib_dir parameter can contain the location where the
algorithm module is on the system.
Return Values
Returns an array with the key sizes supported by the specified algorithm.
If it returns an empty array then all key sizes between 1 and
mcrypt_module_get_algo_key_size() are supported by the algorithm.
See Also
* mcrypt_enc_get_supported_key_sizes() - Returns an array with the
supported keysizes of the opened algorithm
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_module_is_block_algorithm_mode
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_is_block_algorithm_mode - Returns if the specified module is
a block algorithm or not
Description
bool mcrypt_module_is_block_algorithm_mode ( string $mode [, string
$lib_dir ] )
This function returns TRUE if the mode is for use with block algorithms,
otherwise it returns FALSE. (e.g. FALSE for stream, and TRUE for cbc, cfb,
ofb).
Parameters
mode
The mode to check.
lib_dir
The optional lib_dir parameter can contain the location where the
algorithm module is on the system.
Return Values
This function returns TRUE if the mode is for use with block algorithms,
otherwise it returns FALSE. (e.g. FALSE for stream, and TRUE for cbc, cfb,
ofb).
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_module_is_block_algorithm
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_is_block_algorithm - This function checks whether the
specified algorithm is a block algorithm
Description
bool mcrypt_module_is_block_algorithm ( string $algorithm [, string
$lib_dir ] )
This function returns TRUE if the specified algorithm is a block
algorithm, or FALSE if it is a stream one.
Parameters
algorithm
The algorithm to check.
lib_dir
The optional lib_dir parameter can contain the location where the
algorithm module is on the system.
Return Values
This function returns TRUE if the specified algorithm is a block
algorithm, or FALSE if it is a stream one.
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_module_is_block_mode
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_is_block_mode - Returns if the specified mode outputs blocks
or not
Description
bool mcrypt_module_is_block_mode ( string $mode [, string $lib_dir ] )
This function returns TRUE if the mode outputs blocks of bytes or FALSE if
it outputs just bytes. (e.g. TRUE for cbc and ecb, and FALSE for cfb and
stream).
Parameters
mode
The mode to check.
lib_dir
The optional lib_dir parameter can contain the location where the
algorithm module is on the system.
Return Values
This function returns TRUE if the mode outputs blocks of bytes or FALSE if
it outputs just bytes. (e.g. TRUE for cbc and ecb, and FALSE for cfb and
stream).
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_module_open
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_open - Opens the module of the algorithm and the mode to be
used
Description
resource mcrypt_module_open ( string $algorithm , string
$algorithm_directory , string $mode , string $mode_directory )
This function opens the module of the algorithm and the mode to be used.
The name of the algorithm is specified in algorithm, e.g. "twofish" or is
one of the MCRYPT_ciphername constants. The module is closed by calling
mcrypt_module_close().
Parameters
algorithm
The algorithm to be used.
algorithm_directory
The algorithm_directory parameter is used to locate the encryption
module. When you supply a directory name, it is used. When you set
it to an empty string (""), the value set by the
mcrypt.algorithms_dir php.ini directive is used. When it is not
set, the default directory that is used is the one that was
compiled into libmcrypt (usually /usr/local/lib/libmcrypt).
mode
The mode to be used.
mode_directory
The mode_directory parameter is used to locate the encryption
module. When you supply a directory name, it is used. When you set
it to an empty string (""), the value set by the mcrypt.modes_dir
php.ini directive is used. When it is not set, the default
directory that is used is the one that was compiled-in into
libmcrypt (usually /usr/local/lib/libmcrypt).
Return Values
Normally it returns an encryption descriptor, or FALSE on error.
Examples
Example #1 mcrypt_module_open() Examples
The first line in the example above will try to open the DES cipher from
the default directory and the EBC mode from the directory
/usr/lib/mcrypt-modes. The second example uses strings as name for the
cipher and mode, this only works when the extension is linked against
libmcrypt 2.4.x or 2.5.x.
Example #2 Using mcrypt_module_open() in encryption
See Also
* mcrypt_module_close() - Closes the mcrypt module
* mcrypt_generic() - This function encrypts data
* mdecrypt_generic() - Decrypts data
* mcrypt_generic_init() - This function initializes all buffers needed
for encryption
* mcrypt_generic_deinit() - This function deinitializes an encryption
module
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_module_self_test
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_self_test - This function runs a self test on the specified
module
Description
bool mcrypt_module_self_test ( string $algorithm [, string $lib_dir ] )
This function runs the self test on the algorithm specified.
Parameters
algorithm
The algorithm to test.
lib_dir
The optional lib_dir parameter can contain the location where the
algorithm module is on the system.
Return Values
The function returns TRUE if the self test succeeds, or FALSE when it
fails.
Examples
Example #1 mcrypt_module_self_test() example
The above example will output:
bool(true)
bool(false)
----------------------------------------------------------------------
----------------------------------------------------------------------
mcrypt_ofb
(PHP 4, PHP 5)
mcrypt_ofb - Encrypts/decrypts data in OFB mode
Description
string mcrypt_ofb ( int $cipher , string $key , string $data , int $mode ,
string $iv )
string mcrypt_ofb ( string $cipher , string $key , string $data , int
$mode [, string $iv ] )
The first prototype is when linked against libmcrypt 2.2.x, the second
when linked against libmcrypt 2.4.x or higher. The mode should be either
MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
This function should not be used anymore, see mcrypt_generic() and
mdecrypt_generic() for replacements.
----------------------------------------------------------------------
----------------------------------------------------------------------
mdecrypt_generic
(PHP 4 >= 4.0.2, PHP 5)
mdecrypt_generic - Decrypts data
Description
string mdecrypt_generic ( resource $td , string $data )
This function decrypts data. Note that the length of the returned string
can in fact be longer than the unencrypted string, due to the padding of
the data.
Parameters
td
An encryption descriptor returned by mcrypt_module_open()
data
Encrypted data.
Examples
Example #1 mdecrypt_generic() Example
The example above shows how to check if the data before the encryption is
the same as the data after the decryption. It is very important to
reinitialize the encryption buffer with mcrypt_generic_init() before you
try to decrypt the data.
The decryption handle should always be initialized with
mcrypt_generic_init() with a key and an IV before calling this function.
Where the encryption is done, you should free the encryption buffers by
calling mcrypt_generic_deinit(). See mcrypt_module_open() for an example.
See Also
* mcrypt_generic() - This function encrypts data
* mcrypt_generic_init() - This function initializes all buffers needed
for encryption
* mcrypt_generic_deinit() - This function deinitializes an encryption
module
----------------------------------------------------------------------
Table of Contents
* mcrypt_cbc - Encrypts/decrypts data in CBC mode
* mcrypt_cfb - Encrypts/decrypts data in CFB mode
* mcrypt_create_iv - Creates an initialization vector (IV) from a random
source
* mcrypt_decrypt - Decrypts crypttext with given parameters
* mcrypt_ecb - Deprecated: Encrypts/decrypts data in ECB mode
* mcrypt_enc_get_algorithms_name - Returns the name of the opened
algorithm
* mcrypt_enc_get_block_size - Returns the blocksize of the opened
algorithm
* mcrypt_enc_get_iv_size - Returns the size of the IV of the opened
algorithm
* mcrypt_enc_get_key_size - Returns the maximum supported keysize of the
opened mode
* mcrypt_enc_get_modes_name - Returns the name of the opened mode
* mcrypt_enc_get_supported_key_sizes - Returns an array with the
supported keysizes of the opened algorithm
* mcrypt_enc_is_block_algorithm_mode - Checks whether the encryption of
the opened mode works on blocks
* mcrypt_enc_is_block_algorithm - Checks whether the algorithm of the
opened mode is a block algorithm
* mcrypt_enc_is_block_mode - Checks whether the opened mode outputs
blocks
* mcrypt_enc_self_test - Runs a self test on the opened module
* mcrypt_encrypt - Encrypts plaintext with given parameters
* mcrypt_generic_deinit - This function deinitializes an encryption
module
* mcrypt_generic_end - This function terminates encryption
* mcrypt_generic_init - This function initializes all buffers needed for
encryption
* mcrypt_generic - This function encrypts data
* mcrypt_get_block_size - Gets the block size of the specified cipher
* mcrypt_get_cipher_name - Gets the name of the specified cipher
* mcrypt_get_iv_size - Returns the size of the IV belonging to a
specific cipher/mode combination
* mcrypt_get_key_size - Gets the key size of the specified cipher
* mcrypt_list_algorithms - Gets an array of all supported ciphers
* mcrypt_list_modes - Gets an array of all supported modes
* mcrypt_module_close - Closes the mcrypt module
* mcrypt_module_get_algo_block_size - Returns the blocksize of the
specified algorithm
* mcrypt_module_get_algo_key_size - Returns the maximum supported
keysize of the opened mode
* mcrypt_module_get_supported_key_sizes - Returns an array with the
supported keysizes of the opened algorithm
* mcrypt_module_is_block_algorithm_mode - Returns if the specified
module is a block algorithm or not
* mcrypt_module_is_block_algorithm - This function checks whether the
specified algorithm is a block algorithm
* mcrypt_module_is_block_mode - Returns if the specified mode outputs
blocks or not
* mcrypt_module_open - Opens the module of the algorithm and the mode to
be used
* mcrypt_module_self_test - This function runs a self test on the
specified module
* mcrypt_ofb - Encrypts/decrypts data in OFB mode
* mdecrypt_generic - Decrypts data
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Mcrypt ciphers
* Examples
* Mcrypt Functions
* mcrypt_cbc - Encrypts/decrypts data in CBC mode
* mcrypt_cfb - Encrypts/decrypts data in CFB mode
* mcrypt_create_iv - Creates an initialization vector (IV) from a
random source
* mcrypt_decrypt - Decrypts crypttext with given parameters
* mcrypt_ecb - Deprecated: Encrypts/decrypts data in ECB mode
* mcrypt_enc_get_algorithms_name - Returns the name of the opened
algorithm
* mcrypt_enc_get_block_size - Returns the blocksize of the opened
algorithm
* mcrypt_enc_get_iv_size - Returns the size of the IV of the opened
algorithm
* mcrypt_enc_get_key_size - Returns the maximum supported keysize
of the opened mode
* mcrypt_enc_get_modes_name - Returns the name of the opened mode
* mcrypt_enc_get_supported_key_sizes - Returns an array with the
supported keysizes of the opened algorithm
* mcrypt_enc_is_block_algorithm_mode - Checks whether the
encryption of the opened mode works on blocks
* mcrypt_enc_is_block_algorithm - Checks whether the algorithm of
the opened mode is a block algorithm
* mcrypt_enc_is_block_mode - Checks whether the opened mode outputs
blocks
* mcrypt_enc_self_test - Runs a self test on the opened module
* mcrypt_encrypt - Encrypts plaintext with given parameters
* mcrypt_generic_deinit - This function deinitializes an encryption
module
* mcrypt_generic_end - This function terminates encryption
* mcrypt_generic_init - This function initializes all buffers
needed for encryption
* mcrypt_generic - This function encrypts data
* mcrypt_get_block_size - Gets the block size of the specified
cipher
* mcrypt_get_cipher_name - Gets the name of the specified cipher
* mcrypt_get_iv_size - Returns the size of the IV belonging to a
specific cipher/mode combination
* mcrypt_get_key_size - Gets the key size of the specified cipher
* mcrypt_list_algorithms - Gets an array of all supported ciphers
* mcrypt_list_modes - Gets an array of all supported modes
* mcrypt_module_close - Closes the mcrypt module
* mcrypt_module_get_algo_block_size - Returns the blocksize of the
specified algorithm
* mcrypt_module_get_algo_key_size - Returns the maximum supported
keysize of the opened mode
* mcrypt_module_get_supported_key_sizes - Returns an array with the
supported keysizes of the opened algorithm
* mcrypt_module_is_block_algorithm_mode - Returns if the specified
module is a block algorithm or not
* mcrypt_module_is_block_algorithm - This function checks whether
the specified algorithm is a block algorithm
* mcrypt_module_is_block_mode - Returns if the specified mode
outputs blocks or not
* mcrypt_module_open - Opens the module of the algorithm and the
mode to be used
* mcrypt_module_self_test - This function runs a self test on the
specified module
* mcrypt_ofb - Encrypts/decrypts data in OFB mode
* mdecrypt_generic - Decrypts data
----------------------------------------------------------------------
----------------------------------------------------------------------
Mhash
----------------------------------------------------------------------
Introduction
These functions are intended to work with >> mhash. Mhash can be used to
create checksums, message digests, message authentication codes, and more.
This is an interface to the mhash library. Mhash supports a wide variety
of hash algorithms such as MD5, SHA1, GOST, and many others. For a
complete list of supported hashes, refer to the constants page. The
general rule is that you can access the hash algorithm from PHP with
MHASH_hashname. For example, to access TIGER you use the PHP constant
MHASH_TIGER.
Note:
This extension is obsoleted by Hash.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
To use it, download the mhash distribution from >> its web site and follow
the included installation instructions.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
You need to compile PHP with the --with-mhash[=DIR] parameter to enable
this extension. DIR is the mhash installation directory.
As of PHP 5.3.0, the mhash extension is emulated thru the Hash extension.
This makes the mhash installation directory have no effect, and requires
the hash extension enabled to make the mhash support available.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
Here is a list of hashes which are currently supported by mhash. If a hash
is not listed here, but it is listed in the mhash documentation as
supported, you can safely assume that this documentation is outdated.
* MHASH_ADLER32
* MHASH_CRC32
* MHASH_CRC32B
* MHASH_GOST
* MHASH_HAVAL128
* MHASH_HAVAL160
* MHASH_HAVAL192
* MHASH_HAVAL224
* MHASH_HAVAL256
* MHASH_MD2
* MHASH_MD4
* MHASH_MD5
* MHASH_RIPEMD128
* MHASH_RIPEMD256
* MHASH_RIPEMD320
* MHASH_SHA1
* MHASH_SHA192
* MHASH_SHA224
* MHASH_SHA256
* MHASH_SHA384
* MHASH_SHA512
* MHASH_SNEFRU128
* MHASH_SNEFRU256
* MHASH_TIGER
* MHASH_TIGER128
* MHASH_TIGER160
* MHASH_WHIRLPOOL
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Example #1 Computes the MD5 digest and hmac and print it out as hex
\n";
$hash = mhash(MHASH_MD5, $input, "Jefe");
echo "The hmac is " . bin2hex($hash) . " \n";
?>
The above example will output:
The hash is d03cb659cbf9192dcd066272249f8412
The hmac is 750c783e6ab0b503eaa86e310a5db738
----------------------------------------------------------------------
----------------------------------------------------------------------
Mhash Functions
----------------------------------------------------------------------
mhash_count
(PHP 4, PHP 5)
mhash_count - Gets the highest available hash ID
Description
int mhash_count ( void )
Gets the highest available hash ID.
Return Values
Returns the highest available hash ID. Hashes are numbered from 0 to this
hash ID.
Examples
Example #1 Traversing all hashes
----------------------------------------------------------------------
----------------------------------------------------------------------
mhash_get_block_size
(PHP 4, PHP 5)
mhash_get_block_size - Gets the block size of the specified hash
Description
int mhash_get_block_size ( int $hash )
Gets the size of a block of the specified hash.
Parameters
hash
The hash ID. One of the MHASH_hashname constants.
Return Values
Returns the size in bytes or FALSE, if the hash does not exist.
Examples
Example #1 mhash_get_block_size() Example
----------------------------------------------------------------------
----------------------------------------------------------------------
mhash_get_hash_name
(PHP 4, PHP 5)
mhash_get_hash_name - Gets the name of the specified hash
Description
string mhash_get_hash_name ( int $hash )
Gets the name of the specified hash.
Parameters
hash
The hash ID. One of the MHASH_hashname constants.
Return Values
Returns the name of the hash or FALSE, if the hash does not exist.
Examples
Example #1 mhash_get_hash_name() Example
----------------------------------------------------------------------
----------------------------------------------------------------------
mhash_keygen_s2k
(PHP 4 >= 4.0.4, PHP 5)
mhash_keygen_s2k - Generates a key
Description
string mhash_keygen_s2k ( int $hash , string $password , string $salt ,
int $bytes )
Generates a key according to the given hash, using an user provided
password.
This is the Salted S2K algorithm as specified in the OpenPGP document
(>> RFC 2440).
Keep in mind that user supplied passwords are not really suitable to be
used as keys in cryptographic algorithms, since users normally choose keys
they can write on keyboard. These passwords use only 6 to 7 bits per
character (or less). It is highly recommended to use some kind of
transformation (like this function) to the user supplied key.
Parameters
hash
The hash ID used to create the key. One of the MHASH_hashname
constants.
password
An user supplied password.
salt
Must be different and random enough for every key you generate in
order to create different keys. Because salt must be known when
you check the keys, it is a good idea to append the key to it.
Salt has a fixed length of 8 bytes and will be padded with zeros
if you supply less bytes.
bytes
The key length, in bytes.
Return Values
Returns the generated key as a string, or FALSE on error.
----------------------------------------------------------------------
----------------------------------------------------------------------
mhash
(PHP 4, PHP 5)
mhash - Computes hash
Description
string mhash ( int $hash , string $data [, string $key ] )
mhash() applies a hash function specified by hash to the data.
Parameters
hash
The hash ID. One of the MHASH_hashname constants.
data
The user input, as a string.
key
If specified, the function will return the resulting HMAC instead.
HMAC is keyed hashing for message authentication, or simply a
message digest that depends on the specified key. Not all
algorithms supported in mhash can be used in HMAC mode.
Return Values
Returns the resulting hash (also called digest) or HMAC as a string, or
FALSE on error.
----------------------------------------------------------------------
Table of Contents
* mhash_count - Gets the highest available hash ID
* mhash_get_block_size - Gets the block size of the specified hash
* mhash_get_hash_name - Gets the name of the specified hash
* mhash_keygen_s2k - Generates a key
* mhash - Computes hash
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* Mhash Functions
* mhash_count - Gets the highest available hash ID
* mhash_get_block_size - Gets the block size of the specified hash
* mhash_get_hash_name - Gets the name of the specified hash
* mhash_keygen_s2k - Generates a key
* mhash - Computes hash
----------------------------------------------------------------------
----------------------------------------------------------------------
OpenSSL
----------------------------------------------------------------------
Introduction
This module uses the functions of >> OpenSSL for generation and
verification of signatures and for sealing (encrypting) and opening
(decrypting) data. OpenSSL offers many features that this module currently
doesn't support. Some of these may be added in the future.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
In order to use the OpenSSL functions you need to install the >> OpenSSL
package. PHP between versions 4.0.5 and 4.3.1 will work with OpenSSL >=
0.9.5. Other versions (PHP <=4.0.4 and >= 4.3.2) require OpenSSL >= 0.9.6.
Warning
You are strongly encouraged to use the most recent OpenSSL version,
otherwise your web server could be vulnerable to attack.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
To use PHP's OpenSSL support you must also compile PHP
--with-openssl[=DIR] .
The OpenSSL library also has additional requirements for normal operation
at run-time. Most notably, OpenSSL requires access to a random or
pseudo-random number generator; on most Unix and Unix-like platforms
(including Linux), this means that it must have access to a /dev/urandom
or /dev/random device.
Note: Note to Win32 Users
In order for this extension to work, there are DLL files that must be
available to the Windows system PATH. For information on how to do this,
see the FAQ entitled "How do I add my PHP directory to the PATH on
Windows". Although copying DLL files from the PHP folder into the
Windows system directory also works (because the system directory is by
default in the system's PATH), this is not recommended. This extension
requires the following files to be in the PATH: libeay32.dll
Additionally, if you are planning to use the key generation and
certificate signing functions, you will need to install a valid
openssl.cnf file on your system. As of PHP 4.3.0, we include a sample
configuration file in our win32 binary distributions. PHP 4.3.x and
4.4.x has the file in the openssl directory. PHP 5.x and 6.x has the
file in the extras/openssl directory. If you are either using PHP 4.2.x
or missing the file, you can obtain it from >> the OpenSSL binaries page
or by downloading a recent PHP release. Be aware that Windows Explorer
hides the .cnf extension by default and says the file Type is SpeedDial.
PHP will search for the openssl.cnf using the following logic:
* the OPENSSL_CONF environmental variable, if set, will be used as the
path (including filename) of the configuration file.
* the SSLEAY_CONF environmental variable, if set, will be used as the
path (including filename) of the configuration file.
* The file openssl.cnf will be assumed to be found in the default
certificate area, as configured at the time that the openssl DLL was
compiled. This is usually means that the default filename is
c:\usr\local\ssl\openssl.cnf.
In your installation, you need to decide whether to install the
configuration file at c:\usr\local\ssl\openssl.cnf or whether to install
it someplace else and use environmental variables (possibly on a
per-virtual-host basis) to locate the configuration file. Note that it
is possible to override the default path from the script using the
configargs of the functions that require a configuration file.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
Table of Contents
* Purpose checking flags
* Padding flags
* Key types
* PKCS7 Flags/Constants
* Signature Algorithms
* Ciphers
* Version constants
* Server Name Indication constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
----------------------------------------------------------------------
Purpose checking flags
X509_PURPOSE_SSL_CLIENT (integer)
X509_PURPOSE_SSL_SERVER (integer)
X509_PURPOSE_NS_SSL_SERVER (integer)
X509_PURPOSE_SMIME_SIGN (integer)
X509_PURPOSE_SMIME_ENCRYPT (integer)
X509_PURPOSE_CRL_SIGN (integer)
X509_PURPOSE_ANY (integer)
----------------------------------------------------------------------
----------------------------------------------------------------------
Padding flags
OPENSSL_PKCS1_PADDING (integer)
OPENSSL_SSLV23_PADDING (integer)
OPENSSL_NO_PADDING (integer)
OPENSSL_PKCS1_OAEP_PADDING (integer)
----------------------------------------------------------------------
----------------------------------------------------------------------
Key types
OPENSSL_KEYTYPE_RSA (integer)
OPENSSL_KEYTYPE_DSA (integer)
OPENSSL_KEYTYPE_DH (integer)
----------------------------------------------------------------------
----------------------------------------------------------------------
PKCS7 Flags/Constants
The S/MIME functions make use of flags which are specified using a
bitfield which can include one or more of the following values:
PKCS7 CONSTANTS
Constant Description
Adds text/plain content type headers to encrypted/signed
message. If decrypting or verifying, it strips those
PKCS7_TEXT headers from the output - if the decrypted or verified
message is not of MIME type text/plain then an error will
occur.
Normally the input message is converted to "canonical"
format which is effectively using CR and LF as end of line:
PKCS7_BINARY as required by the S/MIME specification. When this option
is present, no translation occurs. This is useful when
handling binary data which may not be in MIME format.
When verifying a message, certificates (if any) included in
the message are normally searched for the signing
PKCS7_NOINTERN certificate. With this option only the certificates
specified in the extracerts parameter of
openssl_pkcs7_verify() are used. The supplied certificates
can still be used as untrusted CAs however.
PKCS7_NOVERIFY Do not verify the signers certificate of a signed message.
Do not chain verification of signers certificates: that is
PKCS7_NOCHAIN don't use the certificates in the signed message as
untrusted CAs.
When signing a message the signer's certificate is normally
included - with this option it is excluded. This will
PKCS7_NOCERTS reduce the size of the signed message but the verifier must
have a copy of the signers certificate available locally
(passed using the extracerts to openssl_pkcs7_verify() for
example).
Normally when a message is signed, a set of attributes are
PKCS7_NOATTR included which include the signing time and the supported
symmetric algorithms. With this option they are not
included.
When signing a message, use cleartext signing with the MIME
type "multipart/signed". This is the default if you do not
specify any flags to openssl_pkcs7_sign(). If you turn this
PKCS7_DETACHED option off, the message will be signed using opaque
signing, which is more resistant to translation by mail
relays but cannot be read by mail agents that do not
support S/MIME.
PKCS7_NOSIGS Don't try and verify the signatures on a message
Note:
These constants were added in 4.0.6.
----------------------------------------------------------------------
----------------------------------------------------------------------
Signature Algorithms
OPENSSL_ALGO_DSS1 (integer)
OPENSSL_ALGO_SHA1 (integer)
Used as default algorithm by openssl_sign() and openssl_verify().
OPENSSL_ALGO_MD5 (integer)
OPENSSL_ALGO_MD4 (integer)
OPENSSL_ALGO_MD2 (integer)
Note:
These constants were added in 5.0.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
Ciphers
OPENSSL_CIPHER_RC2_40 (integer)
OPENSSL_CIPHER_RC2_128 (integer)
OPENSSL_CIPHER_RC2_64 (integer)
OPENSSL_CIPHER_DES (integer)
OPENSSL_CIPHER_3DES (integer)
Note:
These constants were added in 4.3.0.
OPENSSL_CIPHER_AES_128_CBC (integer)
OPENSSL_CIPHER_AES_192_CBC (integer)
OPENSSL_CIPHER_AES_256_CBC (integer)
Note:
These constants were added in 5.4.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
Version constants
OPENSSL_VERSION_TEXT (string)
OPENSSL_VERSION_NUMBER (integer)
Note:
These constants were added in 5.2.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
Server Name Indication constants
OPENSSL_TLSEXT_SERVER_NAME (string)
Whether SNI support is available or not.
Note:
This constant were added in 5.3.2 and requires PHP to be built with
OpenSSL 0.9.8j or greater.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Key/Certificate parameters
Quite a few of the openssl functions require a key or a certificate
parameter. PHP 4.0.5 and earlier have to use a key or certificate resource
returned by one of the openssl_get_xxx() functions. Later versions may use
one of the following methods:
* Certificates
1. An X.509 resource returned from openssl_x509_read()
2. A string having the format file://path/to/cert.pem; the named
file must contain a PEM encoded certificate
3. A string containing the content of a certificate, PEM encoded
* Public/Private Keys
1. A key resource returned from openssl_get_publickey() or
openssl_get_privatekey()
2. For public keys only: an X.509 resource
3. A string having the format file://path/to/file.pem - the named
file must contain a PEM encoded certificate/private key (it may
contain both)
4. A string containing the content of a certificate/key, PEM encoded
5. For private keys, you may also use the syntax array($key,
$passphrase) where $key represents a key specified using the
file:// or textual content notation above, and $passphrase
represents a string containing the passphrase for that private
key
----------------------------------------------------------------------
----------------------------------------------------------------------
Certificate Verification
When calling a function that will verify a signature/certificate, the
cainfo parameter is an array containing file and directory names that
specify the locations of trusted CA files. If a directory is specified,
then it must be a correctly formed hashed directory as the openssl command
would use.
----------------------------------------------------------------------
----------------------------------------------------------------------
OpenSSL Functions
----------------------------------------------------------------------
openssl_cipher_iv_length
(PHP 5 >= PHP 5.3.3)
openssl_cipher_iv_length - Gets the cipher iv length
Description
integer openssl_cipher_iv_length ( string $method )
Gets the cipher iv length.
Parameters
method
The method.
Return Values
Returns the cipher length on success, or FALSE on failure.
Errors/Exceptions
Emits an E_WARNING level error when the cipher algorithm is unknown.
Examples
Example #1 openssl_cipher_iv_length() example
The above example will output something similar to:
16
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_csr_export_to_file
(PHP 4 >= 4.2.0, PHP 5)
openssl_csr_export_to_file - Exports a CSR to a file
Description
bool openssl_csr_export_to_file ( resource $csr , string $outfilename [,
bool $notext = true ] )
openssl_csr_export_to_file() takes the Certificate Signing Request
represented by csr and saves it as ascii-armoured text into the file named
by outfilename.
Parameters
csr
outfilename
Path to the output file.
notext
The optional parameter notext affects the verbosity of the output;
if it is FALSE, then additional human-readable information is
included in the output. The default value of notext is TRUE.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* openssl_csr_export() - Exports a CSR as a string
* openssl_csr_new() - Generates a CSR
* openssl_csr_sign() - Sign a CSR with another certificate (or itself)
and generate a certificate
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_csr_export
(PHP 4 >= 4.2.0, PHP 5)
openssl_csr_export - Exports a CSR as a string
Description
bool openssl_csr_export ( resource $csr , string &$out [, bool $notext =
true ] )
openssl_csr_export() takes the Certificate Signing Request represented by
csr and stores it as ascii-armoured text into out, which is passed by
reference.
Parameters
csr
out
notext
The optional parameter notext affects the verbosity of the output;
if it is FALSE, then additional human-readable information is
included in the output. The default value of notext is TRUE.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* openssl_csr_export_to_file() - Exports a CSR to a file
* openssl_csr_new() - Generates a CSR
* openssl_csr_sign() - Sign a CSR with another certificate (or itself)
and generate a certificate
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_csr_get_public_key
(PHP 5 >= 5.2.0)
openssl_csr_get_public_key - Returns the public key of a CERT
Description
resource openssl_csr_get_public_key ( mixed $csr [, bool $use_shortnames =
true ] )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_csr_get_subject
(PHP 5 >= 5.2.0)
openssl_csr_get_subject - Returns the subject of a CERT
Description
array openssl_csr_get_subject ( mixed $csr [, bool $use_shortnames = true
] )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_csr_new
(PHP 4 >= 4.2.0, PHP 5)
openssl_csr_new - Generates a CSR
Description
mixed openssl_csr_new ( array $dn , resource &$privkey [, array
$configargs [, array $extraattribs ]] )
openssl_csr_new() generates a new CSR (Certificate Signing Request) based
on the information provided by dn, which represents the Distinguished Name
to be used in the certificate.
Note: You need to have a valid openssl.cnf installed for this function
to operate correctly. See the notes under the installation section for
more information.
Parameters
dn
The Distinguished Name to be used in the certificate.
privkey
privkey should be set to a private key that was previously
generated by openssl_pkey_new() (or otherwise obtained from the
other openssl_pkey family of functions). The corresponding public
portion of the key will be used to sign the CSR.
configargs
By default, the information in your system openssl.conf is used to
initialize the request; you can specify a configuration file
section by setting the config_section_section key of configargs.
You can also specify an alternative openssl configuration file by
setting the value of the config key to the path of the file you
want to use. The following keys, if present in configargs behave
as their equivalents in the openssl.conf, as listed in the table
below.
Configuration overrides
configargs key type openssl.conf description
equivalent
digest_alg string default_md Selects which digest
method to use
Selects which
x509_extensions string x509_extensions extensions should be
used when creating an
x509 certificate
Selects which
req_extensions string req_extensions extensions should be
used when creating a
CSR
Specifies how many bits
private_key_bits integer default_bits should be used to
generate a private key
Specifies the type of
private key to create.
This can be one of
OPENSSL_KEYTYPE_DSA,
OPENSSL_KEYTYPE_DH or
private_key_type integer none OPENSSL_KEYTYPE_RSA.
The default value is
OPENSSL_KEYTYPE_RSA
which is currently the
only supported key
type.
Should an exported key
encrypt_key boolean encrypt_key (with passphrase) be
encrypted?
encrypt_key_cipher integer none One of cipher
constants.
extraattribs
extraattribs is used to specify additional configuration options
for the CSR. Both dn and extraattribs are associative arrays whose
keys are converted to OIDs and applied to the relevant part of the
request.
Return Values
Returns the CSR.
Examples
Example #1 Creating a self-signed-certificate
"UK",
"stateOrProvinceName" => "Somerset",
"localityName" => "Glastonbury",
"organizationName" => "The Brain Room Limited",
"organizationalUnitName" => "PHP Documentation Team",
"commonName" => "Wez Furlong",
"emailAddress" => "wez@example.com"
);
// Generate a new private (and public) key pair
$privkey = openssl_pkey_new();
// Generate a certificate signing request
$csr = openssl_csr_new($dn, $privkey);
// You will usually want to create a self-signed certificate at this
// point until your CA fulfills your request.
// This creates a self-signed cert that is valid for 365 days
$sscert = openssl_csr_sign($csr, null, $privkey, 365);
// Now you will want to preserve your private key, CSR and self-signed
// cert so that they can be installed into your web server, mail server
// or mail client (depending on the intended use of the certificate).
// This example shows how to get those things into variables, but you
// can also store them directly into files.
// Typically, you will send the CSR on to your CA who will then issue
// you with the "real" certificate.
openssl_csr_export($csr, $csrout) and var_dump($csrout);
openssl_x509_export($sscert, $certout) and var_dump($certout);
openssl_pkey_export($privkey, $pkeyout, "mypassword") and var_dump($pkeyout);
// Show any errors that occurred here
while (($e = openssl_error_string()) !== false) {
echo $e . "\n";
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_csr_sign
(PHP 4 >= 4.2.0, PHP 5)
openssl_csr_sign - Sign a CSR with another certificate (or itself) and
generate a certificate
Description
resource openssl_csr_sign ( mixed $csr , mixed $cacert , mixed $priv_key ,
int $days [, array $configargs [, int $serial = 0 ]] )
openssl_csr_sign() generates an x509 certificate resource from the given
CSR.
Note: You need to have a valid openssl.cnf installed for this function
to operate correctly. See the notes under the installation section for
more information.
Parameters
csr
A CSR previously generated by openssl_csr_new(). It can also be
the path to a PEM encoded CSR when specified as file://path/to/csr
or an exported string generated by openssl_csr_export().
cacert
The generated certificate will be signed by cacert. If cacert is
NULL, the generated certificate will be a self-signed certificate.
priv_key
priv_key is the private key that corresponds to cacert.
days
days specifies the length of time for which the generated
certificate will be valid, in days.
configargs
You can finetune the CSR signing by configargs. See
openssl_csr_new() for more information about configargs.
serial
An optional the serial number of issued certificate. If not
specified it will default to 0.
Return Values
Returns an x509 certificate resource on success, FALSE on failure.
Changelog
Version Description
4.3.3 The serial parameter was added.
Examples
Example #1 openssl_csr_sign() example - signing a CSR (how to implement
your own CA)
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_decrypt
(PHP 5 >= 5.3.0)
openssl_decrypt - Decrypts data
Description
string openssl_decrypt ( string $data , string $method , string $password
[, bool $raw_input = false [, string $iv = "" ]] )
Takes a raw or base64 encoded string and decrypts it using a given method
and key.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
data
The data.
method
The cipher method.
password
The password.
raw_input
Setting to TRUE will take a raw encoded string, otherwise a base64
string is assumed for the data parameter.
iv
A non-NULL Initialization Vector.
Return Values
The decrypted string on success or FALSE on failure.
Errors/Exceptions
Emits an E_WARNING level error if an unknown cipher algorithm is passed
via the method parameter.
Emits an E_WARNING level error if an empty value is passed in via the iv
parameter.
Changelog
Version Description
5.3.3 The iv parameter was added.
See Also
* openssl_encrypt() - Encrypts data
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_dh_compute_key
(No version information available, might only be in SVN)
openssl_dh_compute_key - Computes shared secret for public value of remote
DH key and local DH key
Description
string openssl_dh_compute_key ( string $pub_key , resource $dh_key )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
pub_key
Public key
dh_key
DH key
Return Values
Returns computed key on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_digest
(PHP 5 >= 5.3.0)
openssl_digest - Computes a digest
Description
string openssl_digest ( string $data , string $method [, bool $raw_output
= false ] )
Computes a digest hash value for the given data using a given method, and
returns a raw or binhex encoded string.
Warning
This function is currently not documented; only its argument list is
available.
Parameters
data
The data.
method
The digest method.
raw_output
Setting to TRUE will return as raw output data, otherwise the
return value is binhex encoded.
Return Values
Returns the digested hash value on success or FALSE on failure.
Errors/Exceptions
Emits an E_WARNING level error if an unknown signature algorithm is passed
via the method parameter.
See Also
* openssl_get_cipher_methods() - Gets available cipher methods
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_encrypt
(PHP 5 >= 5.3.0)
openssl_encrypt - Encrypts data
Description
string openssl_encrypt ( string $data , string $method , string $password
[, bool $raw_output = false [, string $iv = "" ]] )
Encrypts given data with given method and key, returns a raw or base64
encoded string
Warning
This function is currently not documented; only its argument list is
available.
Parameters
data
The data.
method
The cipher method.
password
The password.
raw_output
Setting to TRUE will return as raw output data, otherwise the
return value is base64 encoded.
iv
A non-NULL Initialization Vector.
Return Values
Returns the encrypted string on success or FALSE on failure.
Errors/Exceptions
Emits an E_WARNING level error if an unknown cipher algorithm is passed in
via the method parameter.
Emits an E_WARNING level error if an empty value is passed in via the iv
parameter.
Changelog
Version Description
5.3.3 The iv parameter was added.
See Also
* openssl_decrypt() - Decrypts data
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_error_string
(PHP 4 >= 4.0.6, PHP 5)
openssl_error_string - Return openSSL error message
Description
string openssl_error_string ( void )
openssl_error_string() returns the last error from the openSSL library.
Error messages are stacked, so this function should be called multiple
times to collect all of the information.
Return Values
Returns an error message string, or FALSE if there are no more error
messages to return.
Examples
Example #1 openssl_error_string() example
\n";
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_free_key
(PHP 4 >= 4.0.4, PHP 5)
openssl_free_key - Free key resource
Description
void openssl_free_key ( resource $key_identifier )
openssl_free_key() frees the key associated with the specified
key_identifier from memory.
Parameters
key_identifier
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_get_cipher_methods
(PHP 5 >= 5.3.0)
openssl_get_cipher_methods - Gets available cipher methods
Description
array openssl_get_cipher_methods ([ bool $aliases = false ] )
Gets a list of available cipher methods.
Parameters
aliases
Set to TRUE if cipher aliases should be included within the
returned array.
Return Values
An array of available cipher methods.
Examples
Example #1 openssl_get_cipher_methods() example
Shows how the available ciphers might look, and also which aliases might
be available.
The above example will output something similar to:
Array
(
[0] => AES-128-CBC
[1] => AES-128-CFB
[2] => AES-128-CFB1
[3] => AES-128-CFB8
[4] => AES-128-ECB
[5] => AES-128-OFB
[6] => AES-192-CBC
[7] => AES-192-CFB
[8] => AES-192-CFB1
[9] => AES-192-CFB8
[10] => AES-192-ECB
[11] => AES-192-OFB
[12] => AES-256-CBC
[13] => AES-256-CFB
[14] => AES-256-CFB1
[15] => AES-256-CFB8
[16] => AES-256-ECB
[17] => AES-256-OFB
[18] => BF-CBC
[19] => BF-CFB
[20] => BF-ECB
[21] => BF-OFB
[22] => CAST5-CBC
[23] => CAST5-CFB
[24] => CAST5-ECB
[25] => CAST5-OFB
[26] => DES-CBC
[27] => DES-CFB
[28] => DES-CFB1
[29] => DES-CFB8
[30] => DES-ECB
[31] => DES-EDE
[32] => DES-EDE-CBC
[33] => DES-EDE-CFB
[34] => DES-EDE-OFB
[35] => DES-EDE3
[36] => DES-EDE3-CBC
[37] => DES-EDE3-CFB
[38] => DES-EDE3-OFB
[39] => DES-OFB
[40] => DESX-CBC
[41] => IDEA-CBC
[42] => IDEA-CFB
[43] => IDEA-ECB
[44] => IDEA-OFB
[45] => RC2-40-CBC
[46] => RC2-64-CBC
[47] => RC2-CBC
[48] => RC2-CFB
[49] => RC2-ECB
[50] => RC2-OFB
[51] => RC4
[52] => RC4-40
[53] => aes-128-cbc
[54] => aes-128-cfb
[55] => aes-128-cfb1
[56] => aes-128-cfb8
[57] => aes-128-ecb
[58] => aes-128-ofb
[59] => aes-192-cbc
[60] => aes-192-cfb
[61] => aes-192-cfb1
[62] => aes-192-cfb8
[63] => aes-192-ecb
[64] => aes-192-ofb
[65] => aes-256-cbc
[66] => aes-256-cfb
[67] => aes-256-cfb1
[68] => aes-256-cfb8
[69] => aes-256-ecb
[70] => aes-256-ofb
[71] => bf-cbc
[72] => bf-cfb
[73] => bf-ecb
[74] => bf-ofb
[75] => cast5-cbc
[76] => cast5-cfb
[77] => cast5-ecb
[78] => cast5-ofb
[79] => des-cbc
[80] => des-cfb
[81] => des-cfb1
[82] => des-cfb8
[83] => des-ecb
[84] => des-ede
[85] => des-ede-cbc
[86] => des-ede-cfb
[87] => des-ede-ofb
[88] => des-ede3
[89] => des-ede3-cbc
[90] => des-ede3-cfb
[91] => des-ede3-ofb
[92] => des-ofb
[93] => desx-cbc
[94] => idea-cbc
[95] => idea-cfb
[96] => idea-ecb
[97] => idea-ofb
[98] => rc2-40-cbc
[99] => rc2-64-cbc
[100] => rc2-cbc
[101] => rc2-cfb
[102] => rc2-ecb
[103] => rc2-ofb
[104] => rc4
[105] => rc4-40
)
Array
(
[18] => AES128
[19] => AES192
[20] => AES256
[21] => BF
[26] => CAST
[27] => CAST-cbc
[32] => DES
[47] => DES3
[48] => DESX
[50] => IDEA
[55] => RC2
[82] => aes128
[83] => aes192
[84] => aes256
[85] => bf
[90] => blowfish
[91] => cast
[92] => cast-cbc
[97] => des
[112] => des3
[113] => desx
[115] => idea
[120] => rc2
)
See Also
* openssl_get_md_methods() - Gets available digest methods
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_get_md_methods
(PHP 5 >= 5.3.0)
openssl_get_md_methods - Gets available digest methods
Description
array openssl_get_md_methods ([ bool $aliases = false ] )
Gets a list of available digest methods.
Parameters
aliases
Set to TRUE if digest aliases should be included within the
returned array.
Return Values
An array of available digest methods.
Examples
Example #1 openssl_get_md_methods() example
Shows how the available digests might look, and also which aliases might
be available.
The above example will output something similar to:
Array
(
[0] => DSA
[1] => DSA-SHA
[2] => MD2
[3] => MD4
[4] => MD5
[5] => RIPEMD160
[6] => SHA
[7] => SHA1
[8] => SHA224
[9] => SHA256
[10] => SHA384
[11] => SHA512
[12] => dsaEncryption
[13] => dsaWithSHA
[14] => ecdsa-with-SHA1
[15] => md2
[16] => md4
[17] => md5
[18] => ripemd160
[19] => sha
[20] => sha1
[21] => sha224
[22] => sha256
[23] => sha384
[24] => sha512
)
Array
(
[2] => DSA-SHA1
[3] => DSA-SHA1-old
[4] => DSS1
[9] => RSA-MD2
[10] => RSA-MD4
[11] => RSA-MD5
[12] => RSA-RIPEMD160
[13] => RSA-SHA
[14] => RSA-SHA1
[15] => RSA-SHA1-2
[16] => RSA-SHA224
[17] => RSA-SHA256
[18] => RSA-SHA384
[19] => RSA-SHA512
[28] => dsaWithSHA1
[29] => dss1
[32] => md2WithRSAEncryption
[34] => md4WithRSAEncryption
[36] => md5WithRSAEncryption
[37] => ripemd
[39] => ripemd160WithRSA
[40] => rmd160
[43] => sha1WithRSAEncryption
[45] => sha224WithRSAEncryption
[47] => sha256WithRSAEncryption
[49] => sha384WithRSAEncryption
[51] => sha512WithRSAEncryption
[52] => shaWithRSAEncryption
[53] => ssl2-md5
[54] => ssl3-md5
[55] => ssl3-sha1
)
See Also
* openssl_digest() - Computes a digest
* openssl_get_cipher_methods() - Gets available cipher methods
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_get_privatekey
(PHP 4 >= 4.0.4, PHP 5)
openssl_get_privatekey - Alias of openssl_pkey_get_private()
Description
This function is an alias of: openssl_pkey_get_private().
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_get_publickey
(PHP 4 >= 4.0.4, PHP 5)
openssl_get_publickey - Alias of openssl_pkey_get_public()
Description
This function is an alias of: openssl_pkey_get_public().
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_open
(PHP 4 >= 4.0.4, PHP 5)
openssl_open - Open sealed data
Description
bool openssl_open ( string $sealed_data , string &$open_data , string
$env_key , mixed $priv_key_id [, string $method ] )
openssl_open() opens (decrypts) sealed_data using the private key
associated with the key identifier priv_key_id and the envelope key
env_key, and fills open_data with the decrypted data. The envelope key is
generated when the data are sealed and can only be used by one specific
private key. See openssl_seal() for more information.
Parameters
sealed_data
open_data
If the call is successful the opened data is returned in this
parameter.
env_key
priv_key_id
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 openssl_open() example
See Also
* openssl_seal() - Seal (encrypt) data
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_pkcs12_export_to_file
(PHP 5 >= 5.2.2)
openssl_pkcs12_export_to_file - Exports a PKCS#12 Compatible Certificate
Store File
Description
bool openssl_pkcs12_export_to_file ( mixed $x509 , string $filename ,
mixed $priv_key , string $pass [, array $args ] )
openssl_pkcs12_export_to_file() stores x509 into a file named by filename
in a PKCS#12 file format.
Parameters
x509
See Key/Certificate parameters for a list of valid values.
filename
Path to the output file.
priv_key
Private key component of PKCS#12 file.
pass
Encryption password for unlocking the PKCS#12 file.
args
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_pkcs12_export
(PHP 5 >= 5.2.2)
openssl_pkcs12_export - Exports a PKCS#12 Compatible Certificate Store
File to variable.
Description
bool openssl_pkcs12_export ( mixed $x509 , string &$out , mixed $priv_key
, string $pass [, array $args ] )
openssl_pkcs12_export() stores x509 into a string named by out in a
PKCS#12 file format.
Parameters
x509
See Key/Certificate parameters for a list of valid values.
out
On success, this will hold the PKCS#12.
priv_key
Private key component of PKCS#12 file.
pass
Encryption password for unlocking the PKCS#12 file.
args
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_pkcs12_read
(PHP 5 >= 5.2.2)
openssl_pkcs12_read - Parse a PKCS#12 Certificate Store into an array
Description
bool openssl_pkcs12_read ( string $pkcs12 , array &$certs , string $pass )
openssl_pkcs12_read() parses the PKCS#12 certificate store supplied by
pkcs12 into a array named certs.
Parameters
pkcs12
certs
On success, this will hold the Certificate Store Data.
pass
Encryption password for unlocking the PKCS#12 file.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_pkcs7_decrypt
(PHP 4 >= 4.0.6, PHP 5)
openssl_pkcs7_decrypt - Decrypts an S/MIME encrypted message
Description
bool openssl_pkcs7_decrypt ( string $infilename , string $outfilename ,
mixed $recipcert [, mixed $recipkey ] )
Decrypts the S/MIME encrypted message contained in the file specified by
infilename using the certificate and its associated private key specified
by recipcert and recipkey.
Parameters
infilename
outfilename
The decrypted message is written to the file specified by
outfilename.
recipcert
recipkey
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 openssl_pkcs7_decrypt() example
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_pkcs7_encrypt
(PHP 4 >= 4.0.6, PHP 5)
openssl_pkcs7_encrypt - Encrypt an S/MIME message
Description
bool openssl_pkcs7_encrypt ( string $infile , string $outfile , mixed
$recipcerts , array $headers [, int $flags = 0 [, int $cipherid =
OPENSSL_CIPHER_RC2_40 ]] )
openssl_pkcs7_encrypt() takes the contents of the file named infile and
encrypts them using an RC2 40-bit cipher so that they can only be read by
the intended recipients specified by recipcerts.
Parameters
infile
outfile
recipcerts
Either a lone X.509 certificate, or an array of X.509
certificates.
headers
headers is an array of headers that will be prepended to the data
after it has been encrypted.
headers can be either an associative array keyed by header name,
or an indexed array, where each element contains a single header
line.
flags
flags can be used to specify options that affect the encoding
process - see PKCS7 constants.
cipherid
One of cipher constants.
Return Values
Returns TRUE on success or FALSE on failure.
Changelog
Version Description
5.0.0 The cipherid parameter was added.
Examples
Example #1 openssl_pkcs7_encrypt() example
"nighthawk@example.com", // keyed syntax
"From: HQ ", // indexed syntax
"Subject" => "Eyes only"))) {
// message encrypted - send it!
exec(ini_get("sendmail_path") . " < enc.txt");
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_pkcs7_sign
(PHP 4 >= 4.0.6, PHP 5)
openssl_pkcs7_sign - Sign an S/MIME message
Description
bool openssl_pkcs7_sign ( string $infilename , string $outfilename , mixed
$signcert , mixed $privkey , array $headers [, int $flags = PKCS7_DETACHED
[, string $extracerts ]] )
openssl_pkcs7_sign() takes the contents of the file named infilename and
signs them using the certificate and its matching private key specified by
signcert and privkey parameters.
Parameters
infilename
outfilename
signcert
privkey
headers
headers is an array of headers that will be prepended to the data
after it has been signed (see openssl_pkcs7_encrypt() for more
information about the format of this parameter).
flags
flags can be used to alter the output - see PKCS7 constants.
extracerts
extracerts specifies the name of a file containing a bunch of
extra certificates to include in the signature which can for
example be used to help the recipient to verify the certificate
that you used.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 openssl_pkcs7_sign() example
"joes@example.com", // keyed syntax
"From: HQ ", // indexed syntax
"Subject" => "Eyes only")
)) {
// message signed - send it!
exec(ini_get("sendmail_path") . " < signed.txt");
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_pkcs7_verify
(PHP 4 >= 4.0.6, PHP 5)
openssl_pkcs7_verify - Verifies the signature of an S/MIME signed message
Description
mixed openssl_pkcs7_verify ( string $filename , int $flags [, string
$outfilename [, array $cainfo [, string $extracerts [, string $content
]]]] )
openssl_pkcs7_verify() reads the S/MIME message contained in the given
file and examines the digital signature.
Parameters
filename
Path to the message.
flags
flags can be used to affect how the signature is verified - see
PKCS7 constants for more information.
outfilename
If the outfilename is specified, it should be a string holding the
name of a file into which the certificates of the persons that
signed the messages will be stored in PEM format.
cainfo
If the cainfo is specified, it should hold information about the
trusted CA certificates to use in the verification process - see
certificate verification for more information about this
parameter.
extracerts
If the extracerts is specified, it is the filename of a file
containing a bunch of certificates to use as untrusted CAs.
content
You can specify a filename with content that will be filled with
the verified data, but with the signature information stripped.
Return Values
Returns TRUE if the signature is verified, FALSE if it is not correct (the
message has been tampered with, or the signing certificate is invalid), or
-1 on error.
Changelog
Version Description
5.1.0 The content parameter was added.
Notes
Note: As specified in RFC 2045, lines may not be longer than 76
characters in the filename parameter.
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_pkey_export_to_file
(PHP 4 >= 4.2.0, PHP 5)
openssl_pkey_export_to_file - Gets an exportable representation of a key
into a file
Description
bool openssl_pkey_export_to_file ( mixed $key , string $outfilename [,
string $passphrase [, array $configargs ]] )
openssl_pkey_export_to_file() saves an ascii-armoured (PEM encoded)
rendition of key into the file named by outfilename.
Note: You need to have a valid openssl.cnf installed for this function
to operate correctly. See the notes under the installation section for
more information.
Parameters
key
outfilename
Path to the output file.
passphrase
The key can be optionally protected by a passphrase.
configargs
configargs can be used to fine-tune the export process by
specifying and/or overriding options for the openssl configuration
file. See openssl_csr_new() for more information about configargs.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_pkey_export
(PHP 4 >= 4.2.0, PHP 5)
openssl_pkey_export - Gets an exportable representation of a key into a
string
Description
bool openssl_pkey_export ( mixed $key , string &$out [, string $passphrase
[, array $configargs ]] )
openssl_pkey_export() exports key as a PEM encoded string and stores it
into out (which is passed by reference).
Note: You need to have a valid openssl.cnf installed for this function
to operate correctly. See the notes under the installation section for
more information.
Parameters
key
out
passphrase
The key is optionally protected by passphrase.
configargs
configargs can be used to fine-tune the export process by
specifying and/or overriding options for the openssl configuration
file. See openssl_csr_new() for more information about configargs.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_pkey_free
(PHP 4 >= 4.2.0, PHP 5)
openssl_pkey_free - Frees a private key
Description
void openssl_pkey_free ( resource $key )
This function frees a private key created by openssl_pkey_new().
Parameters
key
Resource holding the key.
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_pkey_get_details
(PHP 5 >= 5.2.0)
openssl_pkey_get_details - Returns an array with the key details
Description
array openssl_pkey_get_details ( resource $key )
This function returns the key details (bits, key, type).
Parameters
key
Resource holding the key.
Return Values
Returns an array with the key details in success or FALSE in failure.
Returned array has indexes bits (number of bits), key (string
representation of the public key) and type (type of the key which is one
of OPENSSL_KEYTYPE_RSA, OPENSSL_KEYTYPE_DSA, OPENSSL_KEYTYPE_DH,
OPENSSL_KEYTYPE_EC or -1 meaning unknown).
Depending on the key type used, additional details may be returned. Note
that some elements may not always be available.
* OPENSSL_KEYTYPE_RSA, an additional array key named "rsa", containing
the key data is returned.
Key Description
"n"
"e"
"d"
"p"
"q"
"dmp1"
"dmq1"
"iqmp"
* OPENSSL_KEYTYPE_DSA, an additional array key named "dsa", containing
the key data is returned.
Key Description
"p"
"q"
"g"
"priv_key"
"pub_key"
* OPENSSL_KEYTYPE_DH, an additional array key named "dh", containing the
key data is returned.
Key Description
"p"
"g"
"priv_key"
"pub_key"
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_pkey_get_private
(PHP 4 >= 4.2.0, PHP 5)
openssl_pkey_get_private - Get a private key
Description
resource openssl_pkey_get_private ( mixed $key [, string $passphrase = ""
] )
openssl_get_privatekey() parses key and prepares it for use by other
functions.
Parameters
key
key can be one of the following:
1. a string having the format file://path/to/file.pem. The named
file must contain a PEM encoded certificate/private key (it
may contain both).
2. A PEM formatted private key.
passphrase
The optional parameter passphrase must be used if the specified
key is encrypted (protected by a passphrase).
Return Values
Returns a positive key resource identifier on success, or FALSE on error.
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_pkey_get_public
(PHP 4 >= 4.2.0, PHP 5)
openssl_pkey_get_public - Extract public key from certificate and prepare
it for use
Description
resource openssl_pkey_get_public ( mixed $certificate )
openssl_get_publickey() extracts the public key from certificate and
prepares it for use by other functions.
Parameters
certificate
certificate can be one of the following:
1. an X.509 certificate resource
2. a string having the format file://path/to/file.pem. The named
file must contain a PEM encoded certificate/private key (it
may contain both).
3. A PEM formatted private key.
Return Values
Returns a positive key resource identifier on success, or FALSE on error.
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_pkey_new
(PHP 4 >= 4.2.0, PHP 5)
openssl_pkey_new - Generates a new private key
Description
resource openssl_pkey_new ([ array $configargs ] )
openssl_pkey_new() generates a new private and public key pair. The public
component of the key can be obtained using openssl_pkey_get_public().
Note: You need to have a valid openssl.cnf installed for this function
to operate correctly. See the notes under the installation section for
more information.
Parameters
configargs
You can finetune the key generation (such as specifying the number
of bits) using configargs. See openssl_csr_new() for more
information about configargs.
Return Values
Returns a resource identifier for the pkey on success, or FALSE on error.
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_private_decrypt
(PHP 4 >= 4.0.6, PHP 5)
openssl_private_decrypt - Decrypts data with private key
Description
bool openssl_private_decrypt ( string $data , string &$decrypted , mixed
$key [, int $padding = OPENSSL_PKCS1_PADDING ] )
openssl_private_decrypt() decrypts data that was previous encrypted via
openssl_public_encrypt() and stores the result into decrypted.
You can use this function e.g. to decrypt data which were supposed only to
you.
Parameters
data
decrypted
key
key must be the private key corresponding that was used to encrypt
the data.
padding
padding can be one of OPENSSL_PKCS1_PADDING,
OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING,
OPENSSL_NO_PADDING.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* openssl_public_encrypt() - Encrypts data with public key
* openssl_public_decrypt() - Decrypts data with public key
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_private_encrypt
(PHP 4 >= 4.0.6, PHP 5)
openssl_private_encrypt - Encrypts data with private key
Description
bool openssl_private_encrypt ( string $data , string &$crypted , mixed
$key [, int $padding = OPENSSL_PKCS1_PADDING ] )
openssl_private_encrypt() encrypts data with private key and stores the
result into crypted. Encrypted data can be decrypted via
openssl_public_decrypt().
This function can be used e.g. to sign data (or its hash) to prove that it
is not written by someone else.
Parameters
data
crypted
key
padding
padding can be one of OPENSSL_PKCS1_PADDING, OPENSSL_NO_PADDING.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* openssl_public_encrypt() - Encrypts data with public key
* openssl_public_decrypt() - Decrypts data with public key
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_public_decrypt
(PHP 4 >= 4.0.6, PHP 5)
openssl_public_decrypt - Decrypts data with public key
Description
bool openssl_public_decrypt ( string $data , string &$decrypted , mixed
$key [, int $padding = OPENSSL_PKCS1_PADDING ] )
openssl_public_decrypt() decrypts data that was previous encrypted via
openssl_private_encrypt() and stores the result into decrypted.
You can use this function e.g. to check if the message was written by the
owner of the private key.
Parameters
data
decrypted
key
key must be the public key corresponding that was used to encrypt
the data.
padding
padding can be one of OPENSSL_PKCS1_PADDING, OPENSSL_NO_PADDING.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* openssl_private_encrypt() - Encrypts data with private key
* openssl_private_decrypt() - Decrypts data with private key
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_public_encrypt
(PHP 4 >= 4.0.6, PHP 5)
openssl_public_encrypt - Encrypts data with public key
Description
bool openssl_public_encrypt ( string $data , string &$crypted , mixed $key
[, int $padding = OPENSSL_PKCS1_PADDING ] )
openssl_public_encrypt() encrypts data with public key and stores the
result into crypted. Encrypted data can be decrypted via
openssl_private_decrypt().
This function can be used e.g. to encrypt message which can be then read
only by owner of the private key. It can be also used to store secure data
in database.
Parameters
data
crypted
This will hold the result of the encryption.
key
The public key.
padding
padding can be one of OPENSSL_PKCS1_PADDING,
OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING,
OPENSSL_NO_PADDING.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* openssl_private_encrypt() - Encrypts data with private key
* openssl_private_decrypt() - Decrypts data with private key
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_random_pseudo_bytes
(PHP 5 >= 5.3.0)
openssl_random_pseudo_bytes - Generate a pseudo-random string of bytes
Description
string openssl_random_pseudo_bytes ( int $length [, bool &$crypto_strong ]
)
Generates a string of pseudo-random bytes, with the number of bytes
determined by the length parameter.
It also indicates if a cryptographically strong algorithm was used to
produce the pseudo-random bytes, and does this via the optional
crypto_strong parameter. It's rare for this to be FALSE, but some systems
may be broken or old.
Parameters
length
The length of the desired string of bytes. Must be a positive
integer. PHP will try to cast this parameter to a non-null integer
to use it.
crypto_strong
If passed into the function, this will hold a boolean value that
determines if the algorithm used was "cryptographically strong",
e.g., safe for usage with GPG, passwords, etc. TRUE if it did,
otherwise FALSE
Return Values
Returns the generated string of bytes on success, or FALSE on failure.
Examples
Example #1 openssl_random_pseudo_bytes() example
The above example will output something similar to:
Lengths: Bytes: -1 and Hex: 0
string(0) ""
NULL
Lengths: Bytes: 0 and Hex: 0
string(0) ""
NULL
Lengths: Bytes: 1 and Hex: 2
string(2) "42"
bool(true)
Lengths: Bytes: 2 and Hex: 4
string(4) "dc6e"
bool(true)
Lengths: Bytes: 3 and Hex: 6
string(6) "288591"
bool(true)
Lengths: Bytes: 4 and Hex: 8
string(8) "ab86d144"
bool(true)
See Also
* bin2hex() - Convert binary data into hexadecimal representation
* crypt() - One-way string hashing
* mt_rand() - Generate a better random value
* uniqid() - Generate a unique ID
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_seal
(PHP 4 >= 4.0.4, PHP 5)
openssl_seal - Seal (encrypt) data
Description
int openssl_seal ( string $data , string &$sealed_data , array &$env_keys
, array $pub_key_ids [, string $method ] )
openssl_seal() seals (encrypts) data by using RC4 with a randomly
generated secret key. The key is encrypted with each of the public keys
associated with the identifiers in pub_key_ids and each encrypted key is
returned in env_keys. This means that one can send sealed data to multiple
recipients (provided one has obtained their public keys). Each recipient
must receive both the sealed data and the envelope key that was encrypted
with the recipient's public key.
Parameters
data
sealed_data
env_keys
pub_key_ids
Return Values
Returns the length of the sealed data on success, or FALSE on error. If
successful the sealed data is returned in sealed_data, and the envelope
keys in env_keys.
Examples
Example #1 openssl_seal() example
See Also
* openssl_open() - Open sealed data
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_sign
(PHP 4 >= 4.0.4, PHP 5)
openssl_sign - Generate signature
Description
bool openssl_sign ( string $data , string &$signature , mixed $priv_key_id
[, int $signature_alg = OPENSSL_ALGO_SHA1 ] )
openssl_sign() computes a signature for the specified data by using SHA1
for hashing followed by encryption using the private key associated with
priv_key_id. Note that the data itself is not encrypted.
Parameters
data
signature
If the call was successful the signature is returned in signature.
priv_key_id
signature_alg
For more information see the list of Signature Algorithms.
Return Values
Returns TRUE on success or FALSE on failure.
Changelog
Version Description
5.0.0 The signature_alg parameter was added.
Examples
Example #1 openssl_sign() example
See Also
* openssl_verify() - Verify signature
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_verify
(PHP 4 >= 4.0.4, PHP 5)
openssl_verify - Verify signature
Description
int openssl_verify ( string $data , string $signature , mixed $pub_key_id
[, int $signature_alg = OPENSSL_ALGO_SHA1 ] )
openssl_verify() verifies that the signature is correct for the specified
data using the public key associated with pub_key_id. This must be the
public key corresponding to the private key used for signing.
Parameters
data
signature
pub_key_id
signature_alg
For more information see the list of Signature Algorithms.
Return Values
Returns 1 if the signature is correct, 0 if it is incorrect, and -1 on
error.
Changelog
Version Description
5.2.0 The signature_alg parameter was added.
Examples
Example #1 openssl_verify() example
See Also
* openssl_sign() - Generate signature
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_x509_check_private_key
(PHP 4 >= 4.2.0, PHP 5)
openssl_x509_check_private_key - Checks if a private key corresponds to a
certificate
Description
bool openssl_x509_check_private_key ( mixed $cert , mixed $key )
Checks whether the given key is the private key that corresponds to cert.
Parameters
cert
The certificate.
key
The private key.
Return Values
Returns TRUE if key is the private key that corresponds to cert, or FALSE
otherwise.
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_x509_checkpurpose
(PHP 4 >= 4.0.6, PHP 5)
openssl_x509_checkpurpose - Verifies if a certificate can be used for a
particular purpose
Description
int openssl_x509_checkpurpose ( mixed $x509cert , int $purpose [, array
$cainfo = array() [, string $untrustedfile ]] )
openssl_x509_checkpurpose() examines a certificate to see if it can be
used for the specified purpose.
Parameters
x509cert
The examined certificate.
purpose
openssl_x509_checkpurpose() purposes
Constant Description
X509_PURPOSE_SSL_CLIENT Can the certificate be used for the
client side of an SSL connection?
X509_PURPOSE_SSL_SERVER Can the certificate be used for the
server side of an SSL connection?
X509_PURPOSE_NS_SSL_SERVER Can the cert be used for Netscape SSL
server?
X509_PURPOSE_SMIME_SIGN Can the cert be used to sign S/MIME
email?
X509_PURPOSE_SMIME_ENCRYPT Can the cert be used to encrypt S/MIME
email?
X509_PURPOSE_CRL_SIGN Can the cert be used to sign a
certificate revocation list (CRL)?
X509_PURPOSE_ANY Can the cert be used for Any/All
purposes?
These options are not bitfields - you may specify one only!
cainfo
cainfo should be an array of trusted CA files/dirs as described in
Certificate Verification.
untrustedfile
If specified, this should be the name of a PEM encoded file
holding certificates that can be used to help verify the
certificate, although no trust is placed in the certificates that
come from that file.
Return Values
Returns TRUE if the certificate can be used for the intended purpose,
FALSE if it cannot, or -1 on error.
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_x509_export_to_file
(PHP 4 >= 4.2.0, PHP 5)
openssl_x509_export_to_file - Exports a certificate to file
Description
bool openssl_x509_export_to_file ( mixed $x509 , string $outfilename [,
bool $notext = TRUE ] )
openssl_x509_export_to_file() stores x509 into a file named by outfilename
in a PEM encoded format.
Parameters
x509
See Key/Certificate parameters for a list of valid values.
outfilename
Path to the output file.
notext
The optional parameter notext affects the verbosity of the output;
if it is FALSE, then additional human-readable information is
included in the output. The default value of notext is TRUE.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_x509_export
(PHP 4 >= 4.2.0, PHP 5)
openssl_x509_export - Exports a certificate as a string
Description
bool openssl_x509_export ( mixed $x509 , string &$output [, bool $notext =
TRUE ] )
openssl_x509_export() stores x509 into a string named by output in a PEM
encoded format.
Parameters
x509
See Key/Certificate parameters for a list of valid values.
output
On success, this will hold the PEM.
notext
The optional parameter notext affects the verbosity of the output;
if it is FALSE, then additional human-readable information is
included in the output. The default value of notext is TRUE.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_x509_free
(PHP 4 >= 4.0.6, PHP 5)
openssl_x509_free - Free certificate resource
Description
void openssl_x509_free ( resource $x509cert )
openssl_x509_free() frees the certificate associated with the specified
x509cert resource from memory.
Parameters
x509cert
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_x509_parse
(PHP 4 >= 4.0.6, PHP 5)
openssl_x509_parse - Parse an X509 certificate and return the information
as an array
Description
array openssl_x509_parse ( mixed $x509cert [, bool $shortnames = true ] )
openssl_x509_parse() returns information about the supplied x509cert,
including fields such as subject name, issuer name, purposes, valid from
and valid to dates etc.
Parameters
x509cert
shortnames
shortnames controls how the data is indexed in the array - if
shortnames is TRUE (the default) then fields will be indexed with
the short name form, otherwise, the long name form will be used -
e.g.: CN is the shortname form of commonName.
Return Values
The structure of the returned data is (deliberately) not yet documented,
as it is still subject to change.
----------------------------------------------------------------------
----------------------------------------------------------------------
openssl_x509_read
(PHP 4 >= 4.0.6, PHP 5)
openssl_x509_read - Parse an X.509 certificate and return a resource
identifier for it
Description
resource openssl_x509_read ( mixed $x509certdata )
openssl_x509_read() parses the certificate supplied by x509certdata and
returns a resource identifier for it.
Parameters
x509certdata
Return Values
Returns a resource identifier on success or FALSE on failure.
----------------------------------------------------------------------
Table of Contents
* openssl_cipher_iv_length - Gets the cipher iv length
* openssl_csr_export_to_file - Exports a CSR to a file
* openssl_csr_export - Exports a CSR as a string
* openssl_csr_get_public_key - Returns the public key of a CERT
* openssl_csr_get_subject - Returns the subject of a CERT
* openssl_csr_new - Generates a CSR
* openssl_csr_sign - Sign a CSR with another certificate (or itself) and
generate a certificate
* openssl_decrypt - Decrypts data
* openssl_dh_compute_key - Computes shared secret for public value of
remote DH key and local DH key
* openssl_digest - Computes a digest
* openssl_encrypt - Encrypts data
* openssl_error_string - Return openSSL error message
* openssl_free_key - Free key resource
* openssl_get_cipher_methods - Gets available cipher methods
* openssl_get_md_methods - Gets available digest methods
* openssl_get_privatekey - Alias of openssl_pkey_get_private
* openssl_get_publickey - Alias of openssl_pkey_get_public
* openssl_open - Open sealed data
* openssl_pkcs12_export_to_file - Exports a PKCS#12 Compatible
Certificate Store File
* openssl_pkcs12_export - Exports a PKCS#12 Compatible Certificate Store
File to variable.
* openssl_pkcs12_read - Parse a PKCS#12 Certificate Store into an array
* openssl_pkcs7_decrypt - Decrypts an S/MIME encrypted message
* openssl_pkcs7_encrypt - Encrypt an S/MIME message
* openssl_pkcs7_sign - Sign an S/MIME message
* openssl_pkcs7_verify - Verifies the signature of an S/MIME signed
message
* openssl_pkey_export_to_file - Gets an exportable representation of a
key into a file
* openssl_pkey_export - Gets an exportable representation of a key into
a string
* openssl_pkey_free - Frees a private key
* openssl_pkey_get_details - Returns an array with the key details
* openssl_pkey_get_private - Get a private key
* openssl_pkey_get_public - Extract public key from certificate and
prepare it for use
* openssl_pkey_new - Generates a new private key
* openssl_private_decrypt - Decrypts data with private key
* openssl_private_encrypt - Encrypts data with private key
* openssl_public_decrypt - Decrypts data with public key
* openssl_public_encrypt - Encrypts data with public key
* openssl_random_pseudo_bytes - Generate a pseudo-random string of bytes
* openssl_seal - Seal (encrypt) data
* openssl_sign - Generate signature
* openssl_verify - Verify signature
* openssl_x509_check_private_key - Checks if a private key corresponds
to a certificate
* openssl_x509_checkpurpose - Verifies if a certificate can be used for
a particular purpose
* openssl_x509_export_to_file - Exports a certificate to file
* openssl_x509_export - Exports a certificate as a string
* openssl_x509_free - Free certificate resource
* openssl_x509_parse - Parse an X509 certificate and return the
information as an array
* openssl_x509_read - Parse an X.509 certificate and return a resource
identifier for it
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Purpose checking flags
* Padding flags
* Key types
* PKCS7 Flags/Constants
* Signature Algorithms
* Ciphers
* Version constants
* Server Name Indication constants
* Key/Certificate parameters
* Certificate Verification
* OpenSSL Functions
* openssl_cipher_iv_length - Gets the cipher iv length
* openssl_csr_export_to_file - Exports a CSR to a file
* openssl_csr_export - Exports a CSR as a string
* openssl_csr_get_public_key - Returns the public key of a CERT
* openssl_csr_get_subject - Returns the subject of a CERT
* openssl_csr_new - Generates a CSR
* openssl_csr_sign - Sign a CSR with another certificate (or
itself) and generate a certificate
* openssl_decrypt - Decrypts data
* openssl_dh_compute_key - Computes shared secret for public value
of remote DH key and local DH key
* openssl_digest - Computes a digest
* openssl_encrypt - Encrypts data
* openssl_error_string - Return openSSL error message
* openssl_free_key - Free key resource
* openssl_get_cipher_methods - Gets available cipher methods
* openssl_get_md_methods - Gets available digest methods
* openssl_get_privatekey - Alias of openssl_pkey_get_private
* openssl_get_publickey - Alias of openssl_pkey_get_public
* openssl_open - Open sealed data
* openssl_pkcs12_export_to_file - Exports a PKCS#12 Compatible
Certificate Store File
* openssl_pkcs12_export - Exports a PKCS#12 Compatible Certificate
Store File to variable.
* openssl_pkcs12_read - Parse a PKCS#12 Certificate Store into an
array
* openssl_pkcs7_decrypt - Decrypts an S/MIME encrypted message
* openssl_pkcs7_encrypt - Encrypt an S/MIME message
* openssl_pkcs7_sign - Sign an S/MIME message
* openssl_pkcs7_verify - Verifies the signature of an S/MIME signed
message
* openssl_pkey_export_to_file - Gets an exportable representation
of a key into a file
* openssl_pkey_export - Gets an exportable representation of a key
into a string
* openssl_pkey_free - Frees a private key
* openssl_pkey_get_details - Returns an array with the key details
* openssl_pkey_get_private - Get a private key
* openssl_pkey_get_public - Extract public key from certificate and
prepare it for use
* openssl_pkey_new - Generates a new private key
* openssl_private_decrypt - Decrypts data with private key
* openssl_private_encrypt - Encrypts data with private key
* openssl_public_decrypt - Decrypts data with public key
* openssl_public_encrypt - Encrypts data with public key
* openssl_random_pseudo_bytes - Generate a pseudo-random string of
bytes
* openssl_seal - Seal (encrypt) data
* openssl_sign - Generate signature
* openssl_verify - Verify signature
* openssl_x509_check_private_key - Checks if a private key
corresponds to a certificate
* openssl_x509_checkpurpose - Verifies if a certificate can be used
for a particular purpose
* openssl_x509_export_to_file - Exports a certificate to file
* openssl_x509_export - Exports a certificate as a string
* openssl_x509_free - Free certificate resource
* openssl_x509_parse - Parse an X509 certificate and return the
information as an array
* openssl_x509_read - Parse an X.509 certificate and return a
resource identifier for it
----------------------------------------------------------------------
* Crack - Cracklib
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* Crack Functions
* Hash - HASH Message Digest Framework
* Introduction
* Installing/Configuring
* Predefined Constants
* Hash Functions
* Mcrypt
* Introduction
* Installing/Configuring
* Predefined Constants
* Mcrypt ciphers
* Examples
* Mcrypt Functions
* Mhash
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* Mhash Functions
* OpenSSL
* Introduction
* Installing/Configuring
* Predefined Constants
* Key/Certificate parameters
* Certificate Verification
* OpenSSL Functions
----------------------------------------------------------------------
----------------------------------------------------------------------
Database Extensions
----------------------------------------------------------------------
Abstraction Layers
----------------------------------------------------------------------
Database (dbm-style) Abstraction Layer
----------------------------------------------------------------------
Introduction
These functions build the foundation for accessing Berkeley DB style
databases.
This is a general abstraction layer for several file-based databases. As
such, functionality is limited to a common subset of features supported by
modern databases such as >> Oracle Berkeley DB.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
The behaviour of various aspects depends on the implementation of the
underlying database. Functions such as dba_optimize() and dba_sync() will
do what they promise for one database and will do nothing for others. You
have to download and install supported dba-Handlers.
List of DBA handlers
Handler Notes
Dbm is the oldest (original) type of Berkeley DB style databases.
You should avoid it, if possible. We do not support the
dbm compatibility functions built into DB2 and gdbm, because they are
only compatible on the source code level, but cannot handle the
original dbm format.
ndbm Ndbm is a newer type and more flexible than dbm. It still has
most of the arbitrary limits of dbm (therefore it is deprecated).
gdbm Gdbm is the >> GNU database manager.
DB2 is for >> Oracle Berkeley DB 2. It is described as "a
db2 programmatic toolkit that provides high-performance built-in
database support for both standalone and client/server
applications.
db3 DB3 is for >> Oracle Berkeley DB 3.
db4 DB4 is for >> Oracle Berkeley DB 4 or 5. This option is available
from PHP 4.3.2. It can be used with BDB 5 from PHP 5.3.3.
Cdb is "a fast, reliable, lightweight package for creating and
reading constant databases." It is from the author of qmail and
cdb can be found at >> http://cr.yp.to/cdb.html. Since it is
constant, we support only reading operations. And since PHP 4.3.0
we support writing (not updating) through the internal cdb
library.
cdb_make Since PHP 4.3.0 we support creation (not updating) of cdb files
when the bundled cdb library is used.
This is available since PHP 4.3.0 for compatibility with the
flatfile deprecated dbm extension only and should be avoided. However you
may use this where files were created in this format. That
happens when configure could not find any external library.
This is available since PHP 4.3.3 to be able to modify php.ini
files from within PHP scripts. When working with ini files you
can pass arrays of the form array(0=>group,1=>value_name) or
inifile strings of the form "[group]value_name" where group is optional.
As the functions dba_firstkey() and dba_nextkey() return string
representations of the key there is a new function
dba_key_split() available since PHP 5 which allows to convert the
string keys into array keys without loosing FALSE.
qdbm This is available since PHP 5.0.0. The qdbm library can be loaded
from >> http://fallabs.com/qdbm/index.html.
When invoking the dba_open() or dba_popen() functions, one of the handler
names must be supplied as an argument. The actually available list of
handlers is displayed by invoking phpinfo() or dba_handlers().
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
By using the --enable-dba=shared configuration option you can build a
dynamic loadable module to enable PHP for basic support of dbm-style
databases. You also have to add support for at least one of the following
handlers by specifying the --with-XXXX configure switch to your PHP
configure line.
Warning
After configuring and compiling PHP you must execute the following test
from commandline: php run-tests.php ext/dba. This shows whether your
combination of handlers works. Most problematic are dbm and ndbm which
conflict with many installations. The reason for this is that on several
systems these libraries are part of more than one other library. The
configuration test only prevents you from configuring malfunctioning
single handlers but not combinations.
Supported DBA handlers
Handler Configure Switch
To enable support for dbm add --with-dbm[=DIR] .
Note:
dbm
dbm normally is a wrapper which often results in failures. This
means you should only use dbm if you are sure it works and if
you really need this format.
To enable support for ndbm add --with-ndbm[=DIR] .
Note:
ndbm
ndbm normally is a wrapper which often results in failures.
This means you should only use ndbm if you are sure it works
and if you really need this format.
gdbm To enable support for gdbm add --with-gdbm[=DIR] .
To enable support for Oracle Berkeley DB 2 add --with-db2[=DIR] .
db2 Note:
db2 conflicts with db3 and db4.
To enable support for Oracle Berkeley DB 3 add --with-db3[=DIR] .
db3 Note:
db3 conflicts with db2 and db4.
To enable support for Oracle Berkeley DB 4 or 5 add
--with-db4[=DIR] .
Note:
db4 conflicts with db2 and db3.
Note:
db4
The db4 option was added in PHP 4.3.2. In earlier versions of
PHP you need to use --with-db3=DIR with DIR being the path to
db4 library. It is not possible to use db versions starting
from 4.1 with PHP prior to version 4.3.0. Also, the db
libraries with versions 4.1 through 4.1.24 cannot be used in
any PHP version.
Support for BDB 5 was added in PHP 5.3.3.
To enable support for cdb add --with-cdb[=DIR] .
Note:
cdb
Since PHP 4.3.0 you can omit DIR to use the bundled cdb library
that adds the cdb_make handler which allows creation of cdb
files and allows to access cdb files on the network using PHP's
streams.
To enable support for flatfile add --with-flatfile .
Note:
flatfile
This was added in PHP 4.3.0 to add compatibility with
deprecated dbm extension. Use this handler only when you cannot
install one of the libraries required by the other handlers and
when you cannot use bundled cdb handler.
To enable support for inifile add --with-inifile .
inifile Note:
This was added in PHP 5.0.0 and allows to read and set
microsoft style .ini files (like the php.ini file).
To enable support for qdbm add --with-qdbm[=DIR] .
Note:
qdbm qdbm conflicts with dbm and gdbm.
Note:
This was added in PHP 5.0.0. The qdbm library can be loaded
from >> http://fallabs.com/qdbm/index.html.
Note:
Up to PHP 4.3.0 you are able to add both db2 and db3 handler but only
one of them can be used internally. That means that you cannot have both
file formats. Starting with PHP 5.0.0 there is a configuration check
avoid such misconfigurations.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
The functions dba_open() and dba_popen() return a handle to the specified
database file to access which is used by all other dba-function calls.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
This extension has no constants defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Table of Contents
* Basic usage
----------------------------------------------------------------------
Basic usage
Example #1 DBA example
DBA is binary safe and does not have any arbitrary limits. However, it
inherits all limits set by the underlying database implementation.
All file-based databases must provide a way of setting the file mode of a
new created database, if that is possible at all. The file mode is
commonly passed as the fourth argument to dba_open() or dba_popen().
You can access all entries of a database in a linear way by using the
dba_firstkey() and dba_nextkey() functions. You may not change the
database while traversing it.
Example #2 Traversing a database
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
DBA Functions
----------------------------------------------------------------------
dba_close
(PHP 4, PHP 5)
dba_close - Close a DBA database
Description
void dba_close ( resource $handle )
dba_close() closes the established database and frees all resources of the
specified database handle.
Parameters
handle
The database handler, returned by dba_open() or dba_popen().
Return Values
No value is returned.
See Also
* dba_open() - Open database
* dba_popen() - Open database persistently
----------------------------------------------------------------------
----------------------------------------------------------------------
dba_delete
(PHP 4, PHP 5)
dba_delete - Delete DBA entry specified by key
Description
bool dba_delete ( string $key , resource $handle )
dba_delete() deletes the specified entry from the database.
Parameters
key
The key of the entry which is deleted.
handle
The database handler, returned by dba_open() or dba_popen().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* dba_exists() - Check whether key exists
* dba_fetch() - Fetch data specified by key
* dba_insert() - Insert entry
* dba_replace() - Replace or insert entry
----------------------------------------------------------------------
----------------------------------------------------------------------
dba_exists
(PHP 4, PHP 5)
dba_exists - Check whether key exists
Description
bool dba_exists ( string $key , resource $handle )
dba_exists() checks whether the specified key exists in the database.
Parameters
key
The key the check is performed for.
handle
The database handler, returned by dba_open() or dba_popen().
Return Values
Returns TRUE if the key exists, FALSE otherwise.
See Also
* dba_delete() - Delete DBA entry specified by key
* dba_fetch() - Fetch data specified by key
* dba_insert() - Insert entry
* dba_replace() - Replace or insert entry
----------------------------------------------------------------------
----------------------------------------------------------------------
dba_fetch
(PHP 4, PHP 5)
dba_fetch - Fetch data specified by key
Description
string dba_fetch ( string $key , resource $handle )
string dba_fetch ( string $key , int $skip , resource $handle )
dba_fetch() fetches the data specified by key from the database specified
with handle.
Parameters
key
The key the data is specified by.
Note:
When working with inifiles this function accepts arrays as keys
where index 0 is the group and index 1 is the value name. See:
dba_key_split().
skip
The number of key-value pairs to ignore when using cdb databases.
This value is ignored for all other databases which do not support
multiple keys with the same name.
handle
The database handler, returned by dba_open() or dba_popen().
Return Values
Returns the associated string if the key/data pair is found, FALSE
otherwise.
Changelog
Version Description
4.3.0 The skip parameter is available to support cdb's capability of
multiple keys having the same name.
See Also
* dba_exists() - Check whether key exists
* dba_delete() - Delete DBA entry specified by key
* dba_insert() - Insert entry
* dba_replace() - Replace or insert entry
* dba_key_split() - Splits a key in string representation into array
representation
----------------------------------------------------------------------
----------------------------------------------------------------------
dba_firstkey
(PHP 4, PHP 5)
dba_firstkey - Fetch first key
Description
string dba_firstkey ( resource $handle )
dba_firstkey() returns the first key of the database and resets the
internal key pointer. This permits a linear search through the whole
database.
Parameters
handle
The database handler, returned by dba_open() or dba_popen().
Return Values
Returns the key on success or FALSE on failure.
See Also
* dba_nextkey() - Fetch next key
* dba_key_split() - Splits a key in string representation into array
representation
* Example 2 in the DBA examples
----------------------------------------------------------------------
----------------------------------------------------------------------
dba_handlers
(PHP 4 >= 4.3.0, PHP 5)
dba_handlers - List all the handlers available
Description
array dba_handlers ([ bool $full_info = false ] )
dba_handlers() list all the handlers supported by this extension.
Parameters
full_info
Turns on/off full information display in the result.
Return Values
Returns an array of database handlers. If full_info is set to TRUE, the
array will be associative with the handlers names as keys, and their
version information as value. Otherwise, the result will be an indexed
array of handlers names.
Note:
When the internal cdb library is used you will see cdb and cdb_make.
Examples
Example #1 dba_handlers() Example
$handler_version) {
// clean the versions
$handler_version = str_replace('$', '', $handler_version);
echo " - $handler_name: $handler_version\n";
}
?>
The above example will output something similar to:
Available DBA handlers:
- cdb: 0.75, Revision: 1.3.2.3
- cdb_make: 0.75, Revision: 1.2.2.4
- db2: Sleepycat Software: Berkeley DB 2.7.7: (08/20/99)
- inifile: 1.0, Revision: 1.6.2.3
- flatfile: 1.0, Revision: 1.5.2.4
----------------------------------------------------------------------
----------------------------------------------------------------------
dba_insert
(PHP 4, PHP 5)
dba_insert - Insert entry
Description
bool dba_insert ( string $key , string $value , resource $handle )
dba_insert() inserts the entry described with key and value into the
database.
Parameters
key
The key of the entry to be inserted. If this key already exist in
the database, this function will fail. Use dba_replace() if you
need to replace an existent key.
value
The value to be inserted.
handle
The database handler, returned by dba_open() or dba_popen().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* dba_exists() - Check whether key exists
* dba_delete() - Delete DBA entry specified by key
* dba_fetch() - Fetch data specified by key
* dba_replace() - Replace or insert entry
----------------------------------------------------------------------
----------------------------------------------------------------------
dba_key_split
(PHP 5)
dba_key_split - Splits a key in string representation into array
representation
Description
mixed dba_key_split ( mixed $key )
dba_key_split() splits a key (string representation) into an array
representation.
Parameters
key
The key in string representation.
Return Values
Returns an array of the form array(0 => group, 1 => value_name). This
function will return FALSE if key is NULL or FALSE.
See Also
* dba_firstkey() - Fetch first key
* dba_nextkey() - Fetch next key
* dba_fetch() - Fetch data specified by key
----------------------------------------------------------------------
----------------------------------------------------------------------
dba_list
(PHP 4 >= 4.3.0, PHP 5)
dba_list - List all open database files
Description
array dba_list ( void )
dba_list() list all open database files.
Return Values
An associative array, in the form resourceid => filename.
----------------------------------------------------------------------
----------------------------------------------------------------------
dba_nextkey
(PHP 4, PHP 5)
dba_nextkey - Fetch next key
Description
string dba_nextkey ( resource $handle )
dba_nextkey() returns the next key of the database and advances the
internal key pointer.
Parameters
handle
The database handler, returned by dba_open() or dba_popen().
Return Values
Returns the key on success or FALSE on failure.
See Also
* dba_firstkey() - Fetch first key
* dba_key_split() - Splits a key in string representation into array
representation
* Example 2 in the DBA examples
----------------------------------------------------------------------
----------------------------------------------------------------------
dba_open
(PHP 4, PHP 5)
dba_open - Open database
Description
resource dba_open ( string $path , string $mode [, string $handler [,
mixed $... ]] )
dba_open() establishes a database instance for path with mode using
handler.
Parameters
path
Commonly a regular path in your filesystem.
mode
It is r for read access, w for read/write access to an already
existing database, c for read/write access and database creation
if it doesn't currently exist, and n for create, truncate and
read/write access. The database is created in BTree mode, other
modes (like Hash or Queue) are not supported.
Additionally you can set the database lock method with the next
char. Use l to lock the database with a .lck file or d to lock the
databasefile itself. It is important that all of your applications
do this consistently.
If you want to test the access and do not want to wait for the
lock you can add t as third character. When you are absolutely
sure that you do not require database locking you can do so by
using - instead of l or d. When none of d, l or - is used, dba
will lock on the database file as it would with d.
Note:
There can only be one writer for one database file. When you use
dba on a web server and more than one request requires write
operations they can only be done one after another. Also read
during write is not allowed. The dba extension uses locks to
prevent this. See the following table:
DBA locking
already mode = mode = mode = mode = mode = mode = mode = mode =
open "rl" "rlt" "wl" "wlt" "rd" "rdt" "wd" "wdt"
not ok ok ok ok ok ok ok ok
open
mode = ok ok wait false illegal illegal illegal illegal
"rl"
mode = wait false wait false illegal illegal illegal illegal
"wl"
mode = illegal illegal illegal illegal ok ok wait false
"rd"
mode = illegal illegal illegal illegal wait false wait false
"wd"
* ok: the second call will be successfull.
* wait: the second call waits until dba_close() is called for
the first.
* false: the second call returns false.
* illegal: you must not mix "l" and "d" modifiers for mode
parameter.
handler
The name of the handler which shall be used for accessing path. It
is passed all optional parameters given to dba_open() and can act
on behalf of them.
Return Values
Returns a positive handle on success or FALSE on failure.
Changelog
Version Description
It's possible to open database files over network connection.
However in cases a socket connection will be used (as with
4.3.0 http or ftp) the connection will be locked instead of the
resource itself. This is important to know since in such
cases locking is simply ignored on the resource and other
solutions have to be found.
Locking and the mode modifiers "l", "d", "-" and "t" were
added. In previous PHP versions, you must use semaphores to
4.3.0 guard against simultaneous database access for any database
handler with the exception of GDBM. See System V semaphore
support.
open mode 'c' is broken for several internal handlers and
before 4.3.5 truncates the database instead of appending data to an
existent database. Also dbm and ndbm fail on mode 'c' in
typical configurations (this cannot be fixed).
See Also
* dba_popen() - Open database persistently
* dba_close() - Close a DBA database
----------------------------------------------------------------------
----------------------------------------------------------------------
dba_optimize
(PHP 4, PHP 5)
dba_optimize - Optimize database
Description
bool dba_optimize ( resource $handle )
dba_optimize() optimizes the underlying database.
Parameters
handle
The database handler, returned by dba_open() or dba_popen().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* dba_sync() - Synchronize database
----------------------------------------------------------------------
----------------------------------------------------------------------
dba_popen
(PHP 4, PHP 5)
dba_popen - Open database persistently
Description
resource dba_popen ( string $path , string $mode [, string $handler [,
mixed $... ]] )
dba_popen() establishes a persistent database instance for path with mode
using handler.
Parameters
path
Commonly a regular path in your filesystem.
mode
It is r for read access, w for read/write access to an already
existing database, c for read/write access and database creation
if it doesn't currently exist, and n for create, truncate and
read/write access.
handler
The name of the handler which shall be used for accessing path. It
is passed all optional parameters given to dba_popen() and can act
on behalf of them.
Return Values
Returns a positive handle on success or FALSE on failure.
See Also
* dba_open() - Open database
* dba_close() - Close a DBA database
----------------------------------------------------------------------
----------------------------------------------------------------------
dba_replace
(PHP 4, PHP 5)
dba_replace - Replace or insert entry
Description
bool dba_replace ( string $key , string $value , resource $handle )
dba_replace() replaces or inserts the entry described with key and value
into the database specified by handle.
Parameters
key
The key of the entry to be replaced.
value
The value to be replaced.
handle
The database handler, returned by dba_open() or dba_popen().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* dba_exists() - Check whether key exists
* dba_delete() - Delete DBA entry specified by key
* dba_fetch() - Fetch data specified by key
* dba_insert() - Insert entry
----------------------------------------------------------------------
----------------------------------------------------------------------
dba_sync
(PHP 4, PHP 5)
dba_sync - Synchronize database
Description
bool dba_sync ( resource $handle )
dba_sync() synchronizes the database. This will probably trigger a
physical write to the disk, if supported.
Parameters
handle
The database handler, returned by dba_open() or dba_popen().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* dba_optimize() - Optimize database
----------------------------------------------------------------------
Table of Contents
* dba_close - Close a DBA database
* dba_delete - Delete DBA entry specified by key
* dba_exists - Check whether key exists
* dba_fetch - Fetch data specified by key
* dba_firstkey - Fetch first key
* dba_handlers - List all the handlers available
* dba_insert - Insert entry
* dba_key_split - Splits a key in string representation into array
representation
* dba_list - List all open database files
* dba_nextkey - Fetch next key
* dba_open - Open database
* dba_optimize - Optimize database
* dba_popen - Open database persistently
* dba_replace - Replace or insert entry
* dba_sync - Synchronize database
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* Basic usage
* DBA Functions
* dba_close - Close a DBA database
* dba_delete - Delete DBA entry specified by key
* dba_exists - Check whether key exists
* dba_fetch - Fetch data specified by key
* dba_firstkey - Fetch first key
* dba_handlers - List all the handlers available
* dba_insert - Insert entry
* dba_key_split - Splits a key in string representation into array
representation
* dba_list - List all open database files
* dba_nextkey - Fetch next key
* dba_open - Open database
* dba_optimize - Optimize database
* dba_popen - Open database persistently
* dba_replace - Replace or insert entry
* dba_sync - Synchronize database
----------------------------------------------------------------------
----------------------------------------------------------------------
dbx
----------------------------------------------------------------------
Introduction
The dbx module is a database abstraction layer (db 'X', where 'X' is a
supported database). The dbx functions allow you to access all supported
databases using a single calling convention. The dbx-functions themselves
do not interface directly to the databases, but interface to the modules
that are used to support these databases.
Note:
This extension has been moved to the >> PECL repository and is no longer
bundled with PHP as of PHP 5.1.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
To be able to use a database with the dbx-module, the module must be
either linked or loaded into PHP, and the database module must be
supported by the dbx-module. Currently, the following databases are
supported, but others will follow:
* FrontBase (available from PHP 4.1.0).
* Microsoft SQL Server
* MySQL
* ODBC
* PostgreSQL
* Sybase-CT (available from PHP 4.2.0).
* Oracle (oci8) (available from PHP 4.3.0).
* SQLite (PHP 5).
Documentation for adding additional database support to dbx can be found
at >> http://www.guidance.nl/php/dbx/doc/.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
In order to have these functions available, you must compile PHP with dbx
support by using the --enable-dbx option and all options for the databases
that will be used, e.g. for MySQL you must also specify --with-mysql=[DIR]
. To get other supported databases to work with the dbx-module refer to
their specific documentation.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
DBX Configuration Options
Name Default Changeable Changelog
dbx.colnames_case "unchanged" PHP_INI_SYSTEM Available since PHP 4.3.0.
Removed in PHP 5.1.0.
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
dbx.colnames_case string
Columns names can be returned "unchanged" or converted to
"uppercase" or "lowercase". This directive can be overridden with
a flag to dbx_query().
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
There are two resource types used in the dbx module. The first one is the
link-object for a database connection, the second a result-object which
holds the result of a query.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
DBX_MYSQL (integer)
DBX_ODBC (integer)
DBX_PGSQL (integer)
DBX_MSSQL (integer)
DBX_FBSQL (integer)
DBX_OCI8 (integer) (available from PHP 4.3.0)
DBX_SYBASECT (integer)
DBX_SQLITE (integer) (PHP 5)
DBX_PERSISTENT (integer)
DBX_RESULT_INFO (integer)
DBX_RESULT_INDEX (integer)
DBX_RESULT_ASSOC (integer)
DBX_RESULT_UNBUFFERED (integer) (PHP 5)
DBX_COLNAMES_UNCHANGED (integer) (available from PHP 4.3.0)
DBX_COLNAMES_UPPERCASE (integer) (available from PHP 4.3.0)
DBX_COLNAMES_LOWERCASE (integer) (available from PHP 4.3.0)
DBX_CMP_NATIVE (integer)
DBX_CMP_TEXT (integer)
DBX_CMP_NUMBER (integer)
DBX_CMP_ASC (integer)
DBX_CMP_DESC (integer)
----------------------------------------------------------------------
----------------------------------------------------------------------
dbx Functions
----------------------------------------------------------------------
dbx_close
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)
dbx_close - Close an open connection/database
Description
int dbx_close ( object $link_identifier )
Parameters
link_identifier
The DBX link object to close.
Return Values
Returns 1 on success and 0 on errors.
Examples
Example #1 dbx_close() example
Notes
Note:
Always refer to the module-specific documentation as well.
See Also
* dbx_connect() - Open a connection/database
----------------------------------------------------------------------
----------------------------------------------------------------------
dbx_compare
(PHP 4 >= 4.1.0, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)
dbx_compare - Compare two rows for sorting purposes
Description
int dbx_compare ( array $row_a , array $row_b , string $column_key [, int
$flags = DBX_CMP_ASC | DBX_CMP_NATIVE ] )
dbx_compare() is a helper function for dbx_sort() to ease the make and use
of the custom sorting function.
Parameters
row_a
First row
row_b
Second row
column_key
The compared column
flags
The flags can be set to specify comparison direction:
* DBX_CMP_ASC - ascending order
* DBX_CMP_DESC - descending order
and the preferred comparison type:
* DBX_CMP_NATIVE - no type conversion
* DBX_CMP_TEXT - compare items as strings
* DBX_CMP_NUMBER - compare items numerically
One of the direction and one of the type constant can be combined
with bitwise OR operator (|).
Return Values
Returns 0 if the row_a[$column_key] is equal to row_b[$column_key], and 1
or -1 if the former is greater or is smaller than the latter one,
respectively, or vice versa if the flag is set to DBX_CMP_DESC.
Examples
Example #1 dbx_compare() example
See Also
* dbx_sort() - Sort a result from a dbx_query by a custom sort function
----------------------------------------------------------------------
----------------------------------------------------------------------
dbx_connect
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)
dbx_connect - Open a connection/database
Description
object dbx_connect ( mixed $module , string $host , string $database ,
string $username , string $password [, int $persistent ] )
Opens a connection to a database.
Parameters
module
The module parameter can be either a string or a constant, though
the latter form is preferred. The possible values are given below,
but keep in mind that they only work if the module is actually
loaded.
* DBX_MYSQL or "mysql"
* DBX_ODBC or "odbc"
* DBX_PGSQL or "pgsql"
* DBX_MSSQL or "mssql"
* DBX_FBSQL or "fbsql"
* DBX_SYBASECT or "sybase_ct"
* DBX_OCI8 or "oci8"
* DBX_SQLITE or "sqlite"
host
The SQL server host
database
The database name
username
The username
password
The password
persistent
The persistent parameter can be set to DBX_PERSISTENT, if so, a
persistent connection will be created.
The host, database, username and password parameters are expected, but not
always used depending on the connect functions for the abstracted module.
Return Values
Returns an object on success, FALSE on error. If a connection has been
made but the database could not be selected, the connection is closed and
FALSE is returned.
The returned object has three properties:
database
It is the name of the currently selected database.
handle
It is a valid handle for the connected database, and as such it
can be used in module-specific functions (if required).
handle); // dbx_close($link) would be better here
?>
module
It is used internally by dbx only, and is actually the module
number mentioned above.
Changelog
Version Description
5.0.0 Introduced DBX_SQLITE.
4.3.0 Introduced DBX_OCI8.
4.2.0 Introduced DBX_SYBASECT.
4.1.0 Introduced DBX_FBSQL.
Examples
Example #1 dbx_connect() example
Notes
Note:
Always refer to the module-specific documentation as well.
See Also
* dbx_close() - Close an open connection/database
----------------------------------------------------------------------
----------------------------------------------------------------------
dbx_error
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)
dbx_error - Report the error message of the latest function call in the
module
Description
string dbx_error ( object $link_identifier )
dbx_error() returns the last error message.
Parameters
link_identifier
The DBX link object returned by dbx_connect()
Return Values
Returns a string containing the error message from the last function call
of the abstracted module (e.g. mysql module). If there are multiple
connections in the same module, just the last error is given. If there are
connections on different modules, the latest error is returned for the
module specified by the link_identifier parameter.
Examples
Example #1 dbx_error() example
Notes
Note:
Always refer to the module-specific documentation as well.
The error message for Microsoft SQL Server is actually the result of the
mssql_get_last_message() function.
The error message for Oracle (oci8) is not implemented yet.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbx_escape_string
(PHP 4 >= 4.3.0, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)
dbx_escape_string - Escape a string so it can safely be used in an
sql-statement
Description
string dbx_escape_string ( object $link_identifier , string $text )
Escape the given string so that it can safely be used in an sql-statement.
Parameters
link_identifier
The DBX link object returned by dbx_connect()
text
The string to escape.
Return Values
Returns the text, escaped where necessary (such as quotes, backslashes
etc). On error, NULL is returned.
Examples
Example #1 dbx_escape_string() example
See Also
* dbx_query() - Send a query and fetch all results (if any)
----------------------------------------------------------------------
----------------------------------------------------------------------
dbx_fetch_row
(PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)
dbx_fetch_row - Fetches rows from a query-result that had the
DBX_RESULT_UNBUFFERED flag set
Description
mixed dbx_fetch_row ( object $result_identifier )
dbx_fetch_row() fetches rows from a result identifier that had the
DBX_RESULT_UNBUFFERED flag set.
When the DBX_RESULT_UNBUFFERED is not set in the query, dbx_fetch_row()
will fail as all rows have already been fetched into the results data
property.
As a side effect, the rows property of the query-result object is
incremented for each successful call to dbx_fetch_row().
Parameters
result_identifier
A result set returned by dbx_query().
Return Values
Returns an object on success that contains the same information as any row
would have in the dbx_query() result data property, including columns
accessible by index or fieldname when the flags for dbx_query() were set
that way.
Upon failure, returns 0 (e.g. when no more rows are available).
Examples
Example #1 How to handle the returned value
\n";
while ($row = dbx_fetch_row($result)) {
echo "\n";
foreach ($row as $field) {
echo "$field ";
}
echo " \n";
}
echo "\n";
?>
See Also
* dbx_query() - Send a query and fetch all results (if any)
----------------------------------------------------------------------
----------------------------------------------------------------------
dbx_query
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)
dbx_query - Send a query and fetch all results (if any)
Description
mixed dbx_query ( object $link_identifier , string $sql_statement [, int
$flags ] )
Sends a query and fetch all results.
Parameters
link_identifier
The DBX link object returned by dbx_connect()
sql_statement
SQL statement.
Data inside the query should be properly escaped.
flags
The flags parameter is used to control the amount of information
that is returned. It may be any combination of the following
constants with the bitwise OR operator (|). The DBX_COLNAMES_*
flags override the dbx.colnames_case setting from php.ini.
DBX_RESULT_INDEX
It is always set, that is, the returned object has a
data property which is a 2 dimensional array indexed
numerically. For example, in the expression
data[2][3] 2 stands for the row (or record) number
and 3 stands for the column (or field) number. The
first row and column are indexed at 0. If
DBX_RESULT_ASSOC is also specified, the returning
object contains the information related to
DBX_RESULT_INFO too, even if it was not specified.
DBX_RESULT_INFO
It provides info about columns, such as field names
and field types.
DBX_RESULT_ASSOC
It effects that the field values can be accessed with
the respective column names used as keys to the
returned object's data property. Associated results
are actually references to the numerically indexed
data, so modifying data[0][0] causes that
data[0]['field_name_for_first_column'] is modified as
well.
DBX_RESULT_UNBUFFERED
This flag will not create the data property, and the
rows property will initially be 0. Use this flag for
large datasets, and use dbx_fetch_row() to retrieve
the results row by row. The dbx_fetch_row() function
will return rows that are conformant to the flags set
with this query. Incidentally, it will also update
the rows each time it is called.
DBX_COLNAMES_UNCHANGED
The case of the returned column names will not be
changed.
DBX_COLNAMES_UPPERCASE
The case of the returned column names will be changed
to uppercase.
DBX_COLNAMES_LOWERCASE
The case of the returned column names will be changed
to lowercase.
Note that DBX_RESULT_INDEX is always used, regardless of the
actual value of flags parameter. This means that only the
following combinations are effective:
* DBX_RESULT_INDEX
* DBX_RESULT_INDEX | DBX_RESULT_INFO
* DBX_RESULT_INDEX | DBX_RESULT_INFO | DBX_RESULT_ASSOC - this
is the default, if flags is not specified.
Return Values
dbx_query() returns an object or 1 on success, and 0 on failure. The
result object is returned only if the query given in sql_statement
produces a result set (i.e. a SELECT query, even if the result set is
empty).
The returned object has four or five properties depending on flags:
handle
It is a valid handle for the connected database, and as such it
can be used in module specific functions (if required).
handle, 0);
?>
cols and rows
These contain the number of columns (or fields) and rows (or
records) respectively.
rows; // number of records
echo $result->cols; // number of fields
?>
info (optional)
It is returned only if either DBX_RESULT_INFO or DBX_RESULT_ASSOC
is specified in the flags parameter. It is a 2 dimensional array,
that has two named rows (name and type) to retrieve column
information.
Example #1 lists each field's name and type
cols; $i++ ) {
echo $result->info['name'][$i] . "\n";
echo $result->info['type'][$i] . "\n";
}
?>
data
This property contains the actual resulting data, possibly
associated with column names as well depending on flags. If
DBX_RESULT_ASSOC is set, it is possible to use
$result->data[2]["field_name"].
Example #2 outputs the content of data property into HTML table
\n";
foreach ($result->data as $row) {
echo "\n";
foreach ($row as $field) {
echo "$field ";
}
echo " \n";
}
echo "\n";
?>
Example #3 How to handle UNBUFFERED queries
\n";
while ($row = dbx_fetch_row($result)) {
echo "\n";
foreach ($row as $field) {
echo "$field ";
}
echo " \n";
}
echo "\n";
?>
Changelog
Version Description
5.0.0 Introduced DBX_RESULT_UNBUFFERED.
4.3.0 Introduced DBX_COLNAMES_UNCHANGED, DBX_COLNAMES_UPPERCASE, and
DBX_COLNAMES_LOWERCASE.
Examples
Example #4 How to handle the returned value
Notes
Note:
Always refer to the module-specific documentation as well.
Column names for queries on an Oracle database are returned in
lowercase.
See Also
* dbx_escape_string() - Escape a string so it can safely be used in an
sql-statement
* dbx_fetch_row() - Fetches rows from a query-result that had the
DBX_RESULT_UNBUFFERED flag set
* dbx_connect() - Open a connection/database
----------------------------------------------------------------------
----------------------------------------------------------------------
dbx_sort
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)
dbx_sort - Sort a result from a dbx_query by a custom sort function
Description
bool dbx_sort ( object $result , string $user_compare_function )
Sort a result from a dbx_query() call with a custom sort function.
Parameters
result
A result set returned by dbx_query().
user_compare_function
The user-defined comparison function. It must accept two arguments
and return an integer less than, equal to, or greater than zero if
the first argument is considered to be respectively less than,
equal to, or greater than the second.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 dbx_sort() example
Notes
Note:
It is always better to use ORDER BY SQL clause instead of dbx_sort() if
possible.
See Also
* dbx_compare() - Compare two rows for sorting purposes
----------------------------------------------------------------------
Table of Contents
* dbx_close - Close an open connection/database
* dbx_compare - Compare two rows for sorting purposes
* dbx_connect - Open a connection/database
* dbx_error - Report the error message of the latest function call in
the module
* dbx_escape_string - Escape a string so it can safely be used in an
sql-statement
* dbx_fetch_row - Fetches rows from a query-result that had the
DBX_RESULT_UNBUFFERED flag set
* dbx_query - Send a query and fetch all results (if any)
* dbx_sort - Sort a result from a dbx_query by a custom sort function
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* dbx Functions
* dbx_close - Close an open connection/database
* dbx_compare - Compare two rows for sorting purposes
* dbx_connect - Open a connection/database
* dbx_error - Report the error message of the latest function call
in the module
* dbx_escape_string - Escape a string so it can safely be used in
an sql-statement
* dbx_fetch_row - Fetches rows from a query-result that had the
DBX_RESULT_UNBUFFERED flag set
* dbx_query - Send a query and fetch all results (if any)
* dbx_sort - Sort a result from a dbx_query by a custom sort
function
----------------------------------------------------------------------
----------------------------------------------------------------------
ODBC (Unified)
----------------------------------------------------------------------
Introduction
In addition to normal ODBC support, the Unified ODBC functions in PHP
allow you to access several databases that have borrowed the semantics of
the ODBC API to implement their own API. Instead of maintaining multiple
database drivers that were all nearly identical, these drivers have been
unified into a single set of ODBC functions.
The following databases are supported by the Unified ODBC functions:
>> Adabas D, >> IBM DB2, >> iODBC, >> Solid, and >> Sybase SQL Anywhere.
Note:
With the exception of iODBC, there is no ODBC involved when connecting
to the above databases. The functions that you use to speak natively to
them just happen to share the same names and syntax as the ODBC
functions. However, building PHP with iODBC support enables you to use
any ODBC-compliant drivers with your PHP applications. More information
on iODBC, is available at >> www.iodbc.org with the alternative unixODBC
available at >> www.unixodbc.org.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
To access any of the supported databases you need to have the required
libraries installed.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
--with-adabas[=DIR]
Include Adabas D support. DIR is the Adabas base install
directory, defaults to /usr/local.
--with-sapdb[=DIR]
Include SAP DB support. DIR is SAP DB base install directory,
defaults to /usr/local.
--with-solid[=DIR]
Include Solid support. DIR is the Solid base install directory,
defaults to /usr/local/solid.
--with-ibm-db2[=DIR]
Include IBM DB2 support. DIR is the DB2 base install directory,
defaults to /home/db2inst1/sqllib.
--with-empress[=DIR]
Include Empress support. DIR is the Empress base install
directory, defaults to $EMPRESSPATH. From PHP 4, this option only
supports Empress Version 8.60 and above.
--with-empress-bcs[=DIR]
Include "Empress Local Access" support. DIR is the Empress base
install directory, defaults to $EMPRESSPATH. From PHP 4, this
option only supports Empress Version 8.60 and above.
--with-birdstep[=DIR]
Include Birdstep support. DIR is the Birdstep base install
directory, defaults to /usr/local/birdstep.
--with-custom-odbc[=DIR]
Include a user defined ODBC support. The DIR is ODBC install base
directory, which defaults to /usr/local. Make sure to define
CUSTOM_ODBC_LIBS and have some odbc.h in your include dirs. E.g.,
you should define following for Sybase SQL Anywhere 5.5.00 on QNX,
prior to run configure script:
CPPFLAGS="-DODBC_QNX -DSQLANY_BUG"
LDFLAGS=-lunix
CUSTOM_ODBC_LIBS="-ldblib -lodbc".
--with-iodbc[=DIR]
Include iODBC support. DIR is the iODBC base install directory,
defaults to /usr/local.
--with-esoob[=DIR]
Include Easysoft OOB support. DIR is the OOB base install
directory, defaults to /usr/local/easysoft/oob/client.
--with-unixODBC[=DIR]
Include unixODBC support. DIR is the unixODBC base install
directory, defaults to /usr/local.
--with-openlink[=DIR]
Include OpenLink ODBC support. DIR is the OpenLink base install
directory, defaults to /usr/local. This is the same as iODBC.
--with-dbmaker[=DIR]
Include DBMaker support. DIR is the DBMaker base install
directory, defaults to where the latest version of DBMaker is
installed (such as /home/dbmaker/3.6).
The Windows version of PHP has built-in support for this extension. You do
not need to load any additional extensions in order to use these
functions.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Unified ODBC Configuration Options
Name Default Changeable Changelog
odbc.default_db * NULL PHP_INI_ALL
odbc.default_user * NULL PHP_INI_ALL
odbc.default_pw * NULL PHP_INI_ALL
odbc.allow_persistent "1" PHP_INI_SYSTEM
odbc.check_persistent "1" PHP_INI_SYSTEM
odbc.max_persistent "-1" PHP_INI_SYSTEM
odbc.max_links "-1" PHP_INI_SYSTEM
odbc.defaultlrl "4096" PHP_INI_ALL
odbc.defaultbinmode "1" PHP_INI_ALL
odbc.default_cursortype "3" PHP_INI_ALL Available as of PHP 5.3.0
Note: Entries marked with * are not implemented yet.
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
odbc.default_db string
ODBC data source to use if none is specified in odbc_connect() or
odbc_pconnect().
odbc.default_user string
User name to use if none is specified in odbc_connect() or
odbc_pconnect().
odbc.default_pw string
Password to use if none is specified in odbc_connect() or
odbc_pconnect().
odbc.allow_persistent boolean
Whether to allow persistent ODBC connections.
odbc.check_persistent boolean
Check that a connection is still valid before reuse.
odbc.max_persistent integer
The maximum number of persistent ODBC connections per process.
odbc.max_links integer
The maximum number of ODBC connections per process, including
persistent connections.
odbc.defaultlrl integer
Handling of LONG fields. Specifies the number of bytes returned to
variables.
When an integer is used, the value is measured in bytes. Shorthand
notation, as described in this FAQ, may also be used.
odbc.defaultbinmode integer
Handling of binary data.
odbc.default_cursortype integer
Controls the ODBC cursor model. Possible values are
SQL_CURSOR_FORWARD_ONLY, SQL_CURSOR_KEYSET_DRIVEN,
SQL_CURSOR_DYNAMIC and SQL_CURSOR_STATIC (default).
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension defines two resource types: an ODBC connection identifier
and an ODBC result identifier.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
ODBC_TYPE (integer)
ODBC_BINMODE_PASSTHRU (integer)
ODBC_BINMODE_RETURN (integer)
ODBC_BINMODE_CONVERT (integer)
SQL_ODBC_CURSORS (integer)
SQL_CUR_USE_DRIVER (integer)
SQL_CUR_USE_IF_NEEDED (integer)
SQL_CUR_USE_ODBC (integer)
SQL_CONCURRENCY (integer)
SQL_CONCUR_READ_ONLY (integer)
SQL_CONCUR_LOCK (integer)
SQL_CONCUR_ROWVER (integer)
SQL_CONCUR_VALUES (integer)
SQL_CURSOR_TYPE (integer)
SQL_CURSOR_FORWARD_ONLY (integer)
SQL_CURSOR_KEYSET_DRIVEN (integer)
SQL_CURSOR_DYNAMIC (integer)
SQL_CURSOR_STATIC (integer)
SQL_KEYSET_SIZE (integer)
SQL_CHAR (integer)
SQL_VARCHAR (integer)
SQL_LONGVARCHAR (integer)
SQL_DECIMAL (integer)
SQL_NUMERIC (integer)
SQL_BIT (integer)
SQL_TINYINT (integer)
SQL_SMALLINT (integer)
SQL_INTEGER (integer)
SQL_BIGINT (integer)
SQL_REAL (integer)
SQL_FLOAT (integer)
SQL_DOUBLE (integer)
SQL_BINARY (integer)
SQL_VARBINARY (integer)
SQL_LONGVARBINARY (integer)
SQL_DATE (integer)
SQL_TIME (integer)
SQL_TIMESTAMP (integer)
SQL_TYPE_DATE (integer)
SQL_TYPE_TIME (integer)
SQL_TYPE_TIMESTAMP (integer)
SQL_BEST_ROWID (integer)
SQL_ROWVER (integer)
SQL_SCOPE_CURROW (integer)
SQL_SCOPE_TRANSACTION (integer)
SQL_SCOPE_SESSION (integer)
SQL_NO_NULLS (integer)
SQL_NULLABLE (integer)
SQL_INDEX_UNIQUE (integer)
SQL_INDEX_ALL (integer)
SQL_ENSURE (integer)
SQL_QUICK (integer)
----------------------------------------------------------------------
----------------------------------------------------------------------
ODBC Functions
----------------------------------------------------------------------
odbc_autocommit
(PHP 4, PHP 5)
odbc_autocommit - Toggle autocommit behaviour
Description
mixed odbc_autocommit ( resource $connection_id [, bool $OnOff = false ] )
Toggles autocommit behaviour.
By default, auto-commit is on for a connection. Disabling auto-commit is
equivalent with starting a transaction.
Parameters
connection_id
The ODBC connection identifier, see odbc_connect() for details.
OnOff
If OnOff is TRUE, auto-commit is enabled, if it is FALSE
auto-commit is disabled.
Return Values
Without the OnOff parameter, this function returns auto-commit status for
connection_id. Non-zero is returned if auto-commit is on, 0 if it is off,
or FALSE if an error occurs.
If OnOff is set, this function returns TRUE on success and FALSE on
failure.
See Also
* odbc_commit() - Commit an ODBC transaction
* odbc_rollback() - Rollback a transaction
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_binmode
(PHP 4, PHP 5)
odbc_binmode - Handling of binary column data
Description
bool odbc_binmode ( resource $result_id , int $mode )
Enables handling of binary column data. ODBC SQL types affected are
BINARY, VARBINARY, and LONGVARBINARY.
When binary SQL data is converted to character C data, each byte (8 bits)
of source data is represented as two ASCII characters. These characters
are the ASCII character representation of the number in its hexadecimal
form. For example, a binary 00000001 is converted to "01" and a binary
11111111 is converted to "FF".
LONGVARBINARY handling
binmode longreadlen result
ODBC_BINMODE_PASSTHRU 0 passthru
ODBC_BINMODE_RETURN 0 passthru
ODBC_BINMODE_CONVERT 0 passthru
ODBC_BINMODE_PASSTHRU 0 passthru
ODBC_BINMODE_PASSTHRU >0 passthru
ODBC_BINMODE_RETURN >0 return as is
ODBC_BINMODE_CONVERT >0 return as char
If odbc_fetch_into() is used, passthru means that an empty string is
returned for these columns.
Parameters
result_id
The result identifier.
If result_id is 0, the settings apply as default for new results.
Note: Default for longreadlen is 4096 and mode defaults to
ODBC_BINMODE_RETURN. Handling of binary long columns is also
affected by odbc_longreadlen().
mode
Possible values for mode are:
* ODBC_BINMODE_PASSTHRU: Passthru BINARY data
* ODBC_BINMODE_RETURN: Return as is
* ODBC_BINMODE_CONVERT: Convert to char and return
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_close_all
(PHP 4, PHP 5)
odbc_close_all - Close all ODBC connections
Description
void odbc_close_all ( void )
odbc_close_all() will close down all connections to database server(s).
Parameters
This function has no parameters.
Return Values
No value is returned.
Notes
Note:
This function will fail if there are open transactions on a connection.
This connection will remain open in this case.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_close
(PHP 4, PHP 5)
odbc_close - Close an ODBC connection
Description
void odbc_close ( resource $connection_id )
Closes down the connection to the database server.
Parameters
connection_id
The ODBC connection identifier, see odbc_connect() for details.
Return Values
No value is returned.
Notes
Note:
This function will fail if there are open transactions on this
connection. The connection will remain open in this case.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_columnprivileges
(PHP 4, PHP 5)
odbc_columnprivileges - Lists columns and associated privileges for the
given table
Description
resource odbc_columnprivileges ( resource $connection_id , string
$qualifier , string $owner , string $table_name , string $column_name )
Lists columns and associated privileges for the given table.
Parameters
connection_id
The ODBC connection identifier, see odbc_connect() for details.
qualifier
The qualifier.
owner
The owner.
table_name
The table name.
column_name
The column_name argument accepts search patterns ('%' to match
zero or more characters and '_' to match a single character).
The owner, table_name, and column_name accept search patterns ('%' to
match zero or more characters and '_' to match a single character).
Return Values
Returns an ODBC result identifier or FALSE on failure. This result
identifier can be used to fetch a list of columns and associated
privileges.
The result set has the following columns:
* TABLE_QUALIFIER
* TABLE_OWNER
* TABLE_NAME
* GRANTOR
* GRANTEE
* PRIVILEGE
* IS_GRANTABLE
The result set is ordered by TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_columns
(PHP 4, PHP 5)
odbc_columns - Lists the column names in specified tables
Description
resource odbc_columns ( resource $connection_id [, string $qualifier [,
string $schema [, string $table_name [, string $column_name ]]]] )
Lists all columns in the requested range.
Parameters
connection_id
The ODBC connection identifier, see odbc_connect() for details.
qualifier
The qualifier.
schema
The owner.
table_name
The table name.
column_name
The column name.
The schema, table_name, and column_name accept search patterns ('%' to
match zero or more characters and '_' to match a single character).
Return Values
Returns an ODBC result identifier or FALSE on failure.
The result set has the following columns:
* TABLE_QUALIFIER
* TABLE_SCHEM
* TABLE_NAME
* COLUMN_NAME
* DATA_TYPE
* TYPE_NAME
* PRECISION
* LENGTH
* SCALE
* RADIX
* NULLABLE
* REMARKS
The result set is ordered by TABLE_QUALIFIER, TABLE_SCHEM and TABLE_NAME.
See Also
* odbc_columnprivileges() - Lists columns and associated privileges for
the given table to retrieve associated privileges
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_commit
(PHP 4, PHP 5)
odbc_commit - Commit an ODBC transaction
Description
bool odbc_commit ( resource $connection_id )
Commits all pending transactions on the connection.
Parameters
connection_id
The ODBC connection identifier, see odbc_connect() for details.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_connect
(PHP 4, PHP 5)
odbc_connect - Connect to a datasource
Description
resource odbc_connect ( string $dsn , string $user , string $password [,
int $cursor_type ] )
The connection id returned by this functions is needed by other ODBC
functions. You can have multiple connections open at once as long as they
either use different db or different credentials.
With some ODBC drivers, executing a complex stored procedure may fail with
an error similar to: "Cannot open a cursor on a stored procedure that has
anything other than a single select statement in it". Using
SQL_CUR_USE_ODBC may avoid that error. Also, some drivers don't support
the optional row_number parameter in odbc_fetch_row(). SQL_CUR_USE_ODBC
might help in that case, too.
Parameters
dsn
The database source name for the connection. Alternatively, a
DSN-less connection string can be used.
user
The username.
password
The password.
cursor_type
This sets the type of cursor to be used for this connection. This
parameter is not normally needed, but can be useful for working
around problems with some ODBC drivers.
The following constants are defined for cursortype:
* SQL_CUR_USE_IF_NEEDED
* SQL_CUR_USE_ODBC
* SQL_CUR_USE_DRIVER
Return Values
Returns an ODBC connection id or 0 (FALSE) on error.
Examples
Example #1 DSN-less connections
See Also
* For persistent connections: odbc_pconnect() - Open a persistent
database connection
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_cursor
(PHP 4, PHP 5)
odbc_cursor - Get cursorname
Description
string odbc_cursor ( resource $result_id )
Gets the cursorname for the given result_id.
Parameters
result_id
The result identifier.
Return Values
Returns the cursor name, as a string.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_data_source
(PHP 4 >= 4.3.0, PHP 5)
odbc_data_source - Returns information about a current connection
Description
array odbc_data_source ( resource $connection_id , int $fetch_type )
This function will return the list of available DSN (after calling it
several times).
Parameters
connection_id
The ODBC connection identifier, see odbc_connect() for details.
fetch_type
The fetch_type can be one of two constant types: SQL_FETCH_FIRST,
SQL_FETCH_NEXT. Use SQL_FETCH_FIRST the first time this function
is called, thereafter use the SQL_FETCH_NEXT.
Return Values
Returns FALSE on error, and an array upon success.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_do
(PHP 4, PHP 5)
odbc_do - Alias of odbc_exec()
Description
This function is an alias of: odbc_exec().
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_error
(PHP 4 >= 4.0.5, PHP 5)
odbc_error - Get the last error code
Description
string odbc_error ([ resource $connection_id ] )
Returns a six-digit ODBC state, or an empty string if there has been no
errors.
Parameters
connection_id
The ODBC connection identifier, see odbc_connect() for details.
Return Values
If connection_id is specified, the last state of that connection is
returned, else the last state of any connection is returned.
This function returns meaningful value only if last odbc query failed
(i.e. odbc_exec() returned FALSE).
See Also
* odbc_errormsg() - Get the last error message
* odbc_exec() - Prepare and execute an SQL statement
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_errormsg
(PHP 4 >= 4.0.5, PHP 5)
odbc_errormsg - Get the last error message
Description
string odbc_errormsg ([ resource $connection_id ] )
Returns a string containing the last ODBC error message, or an empty
string if there has been no errors.
Parameters
connection_id
The ODBC connection identifier, see odbc_connect() for details.
Return Values
If connection_id is specified, the last state of that connection is
returned, else the last state of any connection is returned.
This function returns meaningful value only if last odbc query failed
(i.e. odbc_exec() returned FALSE).
See Also
* odbc_error() - Get the last error code
* odbc_exec() - Prepare and execute an SQL statement
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_exec
(PHP 4, PHP 5)
odbc_exec - Prepare and execute an SQL statement
Description
resource odbc_exec ( resource $connection_id , string $query_string [, int
$flags ] )
Sends an SQL statement to the database server.
Parameters
connection_id
The ODBC connection identifier, see odbc_connect() for details.
query_string
The SQL statement.
flags
This parameter is currently not used.
Return Values
Returns an ODBC result identifier if the SQL command was executed
successfully, or FALSE on error.
See Also
* odbc_prepare() - Prepares a statement for execution
* odbc_execute() - Execute a prepared statement
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_execute
(PHP 4, PHP 5)
odbc_execute - Execute a prepared statement
Description
bool odbc_execute ( resource $result_id [, array $parameters_array ] )
Executes a statement prepared with odbc_prepare().
Parameters
result_id
The result id resource, from odbc_prepare().
parameters_array
Parameters in parameter_array will be substituted for placeholders
in the prepared statement in order. Elements of this array will be
converted to strings by calling this function.
Any parameters in parameter_array which start and end with single
quotes will be taken as the name of a file to read and send to the
database server as the data for the appropriate placeholder.
If you wish to store a string which actually begins and ends with
single quotes, you must add a space or other non-single-quote
character to the beginning or end of the parameter, which will
prevent the parameter from being taken as a file name. If this is
not an option, then you must use another mechanism to store the
string, such as executing the query directly with odbc_exec()).
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 odbc_execute() and odbc_prepare() example
In the following code, $success will only be TRUE if all three parameters
to myproc are IN parameters:
If you need to call a stored procedure using INOUT or OUT parameters, the
recommended workaround is to use a native extension for your database (for
example, mssql for MS SQL Server, or oci8 for Oracle).
Changelog
Version Description
4.2.0 File reading is now subject to safe mode and open-basedir
restrictions in parameters_array.
4.1.1 Remote files are no longer supported in parameters_array.
See Also
* odbc_prepare() - Prepares a statement for execution
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_fetch_array
(PHP 4 >= 4.0.2, PHP 5)
odbc_fetch_array - Fetch a result row as an associative array
Description
array odbc_fetch_array ( resource $result [, int $rownumber ] )
Fetch an associative array from an ODBC query. See the changelog below for
when this function is available.
Parameters
result
The result resource from odbc_exec().
rownumber
Optionally choose which row number to retrieve.
Return Values
Returns an array that corresponds to the fetched row, or FALSE if there
are no more rows.
Changelog
Version Description
4.3.3 This function exists when compiled with IBM DB2 or UnixODBC
support.
4.3.2 This function exists when compiled for Windows.
4.0.2 This function exists when compiled with DBMaker support.
See Also
* odbc_fetch_row() - Fetch a row
* odbc_fetch_object() - Fetch a result row as an object
* odbc_num_rows() - Number of rows in a result
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_fetch_into
(PHP 4, PHP 5)
odbc_fetch_into - Fetch one result row into array
Description
int odbc_fetch_into ( resource $result_id , array &$result_array [, int
$rownumber ] )
Fetch one result row into array.
Parameters
result_id
The result resource.
result_array
The result array that can be of any type since it will be
converted to type array. The array will contain the column values
starting at array index 0.
rownumber
The row number.
Return Values
Returns the number of columns in the result; FALSE on error.
Changelog
Version Description
4.2.0 The result_array and rownumber parameters have been swapped. This
allows the rownumber to be a constant again.
4.0.6 The rownumber can no longer be passed in as a constant, but rather
as a variable. This again changed in 4.2.0.
4.0.5 The result_array parameter no longer needs to be passed in by
reference.
Examples
Example #1 odbc_fetch_into() examples
or
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_fetch_object
(PHP 4 >= 4.0.2, PHP 5)
odbc_fetch_object - Fetch a result row as an object
Description
object odbc_fetch_object ( resource $result [, int $rownumber ] )
Fetch an object from an ODBC query. See the changelog below for when this
function is available.
Parameters
result
The result resource from odbc_exec().
rownumber
Optionally choose which row number to retrieve.
Return Values
Returns an object that corresponds to the fetched row, or FALSE if there
are no more rows.
Changelog
Version Description
4.3.3 This function exists when compiled with IBM DB2 or UnixODBC
support.
4.3.2 This function exists when compiled for Windows.
4.0.2 This function exists when compiled with DBMaker support.
See Also
* odbc_fetch_row() - Fetch a row
* odbc_fetch_array() - Fetch a result row as an associative array
* odbc_num_rows() - Number of rows in a result
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_fetch_row
(PHP 4, PHP 5)
odbc_fetch_row - Fetch a row
Description
bool odbc_fetch_row ( resource $result_id [, int $row_number ] )
Fetches a row of the data that was returned by odbc_do() or odbc_exec().
After odbc_fetch_row() is called, the fields of that row can be accessed
with odbc_result().
Parameters
result_id
The result identifier.
row_number
If row_number is not specified, odbc_fetch_row() will try to fetch
the next row in the result set. Calls to odbc_fetch_row() with and
without row_number can be mixed.
To step through the result more than once, you can call
odbc_fetch_row() with row_number 1, and then continue doing
odbc_fetch_row() without row_number to review the result. If a
driver doesn't support fetching rows by number, the row_number
parameter is ignored.
Return Values
Returns TRUE if there was a row, FALSE otherwise.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_field_len
(PHP 4, PHP 5)
odbc_field_len - Get the length (precision) of a field
Description
int odbc_field_len ( resource $result_id , int $field_number )
Gets the length of the field referenced by number in the given result
identifier.
Parameters
result_id
The result identifier.
field_number
The field number. Field numbering starts at 1.
Return Values
Returns the field name as a string, or FALSE on error.
See Also
* odbc_field_scale() - Get the scale of a field to get the scale of a
floating point number
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_field_name
(PHP 4, PHP 5)
odbc_field_name - Get the columnname
Description
string odbc_field_name ( resource $result_id , int $field_number )
Gets the name of the field occupying the given column number in the given
result identifier.
Parameters
result_id
The result identifier.
field_number
The field number. Field numbering starts at 1.
Return Values
Returns the field name as a string, or FALSE on error.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_field_num
(PHP 4, PHP 5)
odbc_field_num - Return column number
Description
int odbc_field_num ( resource $result_id , string $field_name )
Gets the number of the column slot that corresponds to the named field in
the given result identifier.
Parameters
result_id
The result identifier.
field_name
The field name.
Return Values
Returns the field number as a integer, or FALSE on error. Field numbering
starts at 1.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_field_precision
(PHP 4, PHP 5)
odbc_field_precision - Alias of odbc_field_len()
Description
This function is an alias of: odbc_field_len().
See Also
* odbc_field_scale() - Get the scale of a field to get the scale of a
floating point number.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_field_scale
(PHP 4, PHP 5)
odbc_field_scale - Get the scale of a field
Description
int odbc_field_scale ( resource $result_id , int $field_number )
Gets the scale of the field referenced by number in the given result
identifier.
Parameters
result_id
The result identifier.
field_number
The field number. Field numbering starts at 1.
Return Values
Returns the field scale as a integer, or FALSE on error.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_field_type
(PHP 4, PHP 5)
odbc_field_type - Datatype of a field
Description
string odbc_field_type ( resource $result_id , int $field_number )
Gets the SQL type of the field referenced by number in the given result
identifier.
Parameters
result_id
The result identifier.
field_number
The field number. Field numbering starts at 1.
Return Values
Returns the field type as a string, or FALSE on error.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_foreignkeys
(PHP 4, PHP 5)
odbc_foreignkeys - Retrieves a list of foreign keys
Description
resource odbc_foreignkeys ( resource $connection_id , string $pk_qualifier
, string $pk_owner , string $pk_table , string $fk_qualifier , string
$fk_owner , string $fk_table )
Retrieves a list of foreign keys in the specified table or a list of
foreign keys in other tables that refer to the primary key in the
specified table
Parameters
connection_id
The ODBC connection identifier, see odbc_connect() for details.
pk_qualifier
The primary key qualifier.
pk_owner
The primary key owner.
pk_table
The primary key table.
fk_qualifier
The foreign key qualifier.
fk_owner
The foreign key owner.
fk_table
The foreign key table.
Return Values
Returns an ODBC result identifier or FALSE on failure.
The result set has the following columns:
* PKTABLE_QUALIFIER
* PKTABLE_OWNER
* PKTABLE_NAME
* PKCOLUMN_NAME
* FKTABLE_QUALIFIER
* FKTABLE_OWNER
* FKTABLE_NAME
* FKCOLUMN_NAME
* KEY_SEQ
* UPDATE_RULE
* DELETE_RULE
* FK_NAME
* PK_NAME
If pk_table contains a table name, odbc_foreignkeys() returns a result set
containing the primary key of the specified table and all of the foreign
keys that refer to it.
If fk_table contains a table name, odbc_foreignkeys() returns a result set
containing all of the foreign keys in the specified table and the primary
keys (in other tables) to which they refer.
If both pk_table and fk_table contain table names, odbc_foreignkeys()
returns the foreign keys in the table specified in fk_table that refer to
the primary key of the table specified in pk_table. This should be one key
at most.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_free_result
(PHP 4, PHP 5)
odbc_free_result - Free resources associated with a result
Description
bool odbc_free_result ( resource $result_id )
Free resources associated with a result.
odbc_free_result() only needs to be called if you are worried about using
too much memory while your script is running. All result memory will
automatically be freed when the script is finished.
Parameters
result_id
The result identifier.
Return Values
Always returns TRUE.
Notes
Note:
If auto-commit is disabled (see odbc_autocommit()) and you call
odbc_free_result() before committing, all pending transactions are
rolled back.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_gettypeinfo
(PHP 4, PHP 5)
odbc_gettypeinfo - Retrieves information about data types supported by the
data source
Description
resource odbc_gettypeinfo ( resource $connection_id [, int $data_type ] )
Retrieves information about data types supported by the data source.
Parameters
connection_id
The ODBC connection identifier, see odbc_connect() for details.
data_type
The data type, which can be used to restrict the information to a
single data type.
Return Values
Returns an ODBC result identifier or FALSE on failure.
The result set has the following columns:
* TYPE_NAME
* DATA_TYPE
* PRECISION
* LITERAL_PREFIX
* LITERAL_SUFFIX
* CREATE_PARAMS
* NULLABLE
* CASE_SENSITIVE
* SEARCHABLE
* UNSIGNED_ATTRIBUTE
* MONEY
* AUTO_INCREMENT
* LOCAL_TYPE_NAME
* MINIMUM_SCALE
* MAXIMUM_SCALE
The result set is ordered by DATA_TYPE and TYPE_NAME.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_longreadlen
(PHP 4, PHP 5)
odbc_longreadlen - Handling of LONG columns
Description
bool odbc_longreadlen ( resource $result_id , int $length )
Enables handling of LONG and LONGVARBINARY columns.
Parameters
result_id
The result identifier.
length
The number of bytes returned to PHP is controlled by the parameter
length. If it is set to 0, Long column data is passed through to
the client.
Return Values
Returns TRUE on success or FALSE on failure.
Notes
Note:
Handling of LONGVARBINARY columns is also affected by odbc_binmode().
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_next_result
(PHP 4 >= 4.0.5, PHP 5)
odbc_next_result - Checks if multiple results are available
Description
bool odbc_next_result ( resource $result_id )
Checks if there are more result sets available as well as allowing access
to the next result set via odbc_fetch_array(), odbc_fetch_row(),
odbc_result(), etc.
Parameters
result_id
The result identifier.
Return Values
Returns TRUE if there are more result sets, FALSE otherwise.
Examples
Example #1 odbc_next_result()
The above example will output:
Dump first result set array(1) {
["A"]=>
string(1) "A"
}
bool(false)
Get second results set bool(true)
Dump second result set array(1) {
["B"]=>
string(1) "B"
}
bool(false)
Get third results set bool(true)
Dump third result set array(1) {
["C"]=>
string(1) "C"
}
bool(false)
Try for a fourth result set bool(false)
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_num_fields
(PHP 4, PHP 5)
odbc_num_fields - Number of columns in a result
Description
int odbc_num_fields ( resource $result_id )
Gets the number of fields (columns) in an ODBC result.
Parameters
result_id
The result identifier returned by odbc_exec().
Return Values
Returns the number of fields, or -1 on error.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_num_rows
(PHP 4, PHP 5)
odbc_num_rows - Number of rows in a result
Description
int odbc_num_rows ( resource $result_id )
Gets the number of rows in a result. For INSERT, UPDATE and DELETE
statements odbc_num_rows() returns the number of rows affected. For a
SELECT clause this can be the number of rows available.
Parameters
result_id
The result identifier returned by odbc_exec().
Return Values
Returns the number of rows in an ODBC result. This function will return -1
on error.
Notes
Note:
Using odbc_num_rows() to determine the number of rows available after a
SELECT will return -1 with many drivers.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_pconnect
(PHP 4, PHP 5)
odbc_pconnect - Open a persistent database connection
Description
resource odbc_pconnect ( string $dsn , string $user , string $password [,
int $cursor_type ] )
Opens a persistent database connection.
This function is much like odbc_connect(), except that the connection is
not really closed when the script has finished. Future requests for a
connection with the same dsn, user, password combination (via
odbc_connect() and odbc_pconnect()) can reuse the persistent connection.
Parameters
See odbc_connect() for details.
Return Values
Returns an ODBC connection id or 0 (FALSE) on error.
Notes
Note: Persistent connections have no effect if PHP is used as a CGI
program.
See Also
* odbc_connect() - Connect to a datasource
* Persistent Database Connections
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_prepare
(PHP 4, PHP 5)
odbc_prepare - Prepares a statement for execution
Description
resource odbc_prepare ( resource $connection_id , string $query_string )
Prepares a statement for execution. The result identifier can be used
later to execute the statement with odbc_execute().
Some databases (such as IBM DB2, MS SQL Server, and Oracle) support stored
procedures that accept parameters of type IN, INOUT, and OUT as defined by
the ODBC specification. However, the Unified ODBC driver currently only
supports parameters of type IN to stored procedures.
Parameters
connection_id
The ODBC connection identifier, see odbc_connect() for details.
query_string
The query string statement being prepared.
Return Values
Returns an ODBC result identifier if the SQL command was prepared
successfully. Returns FALSE on error.
Examples
Example #1 odbc_execute() and odbc_prepare() example
In the following code, $success will only be TRUE if all three parameters
to myproc are IN parameters:
If you need to call a stored procedure using INOUT or OUT parameters, the
recommended workaround is to use a native extension for your database (for
example, mssql for MS SQL Server, or oci8 for Oracle).
See Also
* odbc_execute() - Execute a prepared statement
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_primarykeys
(PHP 4, PHP 5)
odbc_primarykeys - Gets the primary keys for a table
Description
resource odbc_primarykeys ( resource $connection_id , string $qualifier ,
string $owner , string $table )
Returns a result identifier that can be used to fetch the column names
that comprise the primary key for a table.
Parameters
connection_id
The ODBC connection identifier, see odbc_connect() for details.
qualifier
owner
table
Return Values
Returns an ODBC result identifier or FALSE on failure.
The result set has the following columns:
* TABLE_QUALIFIER
* TABLE_OWNER
* TABLE_NAME
* COLUMN_NAME
* KEY_SEQ
* PK_NAME
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_procedurecolumns
(PHP 4, PHP 5)
odbc_procedurecolumns - Retrieve information about parameters to
procedures
Description
resource odbc_procedurecolumns ( resource $connection_id )
resource odbc_procedurecolumns ( resource $connection_id , string
$qualifier , string $owner , string $proc , string $column )
Retrieve information about parameters to procedures.
Parameters
connection_id
The ODBC connection identifier, see odbc_connect() for details.
qualifier
The qualifier.
owner
The owner. This parameter accepts the following search patterns:
"%" to match zero or more characters, and "_" to match a single
character.
proc
The proc. This parameter accepts the following search patterns:
"%" to match zero or more characters, and "_" to match a single
character.
column
The column. This parameter accepts the following search patterns:
"%" to match zero or more characters, and "_" to match a single
character.
Return Values
Returns the list of input and output parameters, as well as the columns
that make up the result set for the specified procedures. Returns an ODBC
result identifier or FALSE on failure.
The result set has the following columns:
* PROCEDURE_QUALIFIER
* PROCEDURE_OWNER
* PROCEDURE_NAME
* COLUMN_NAME
* COLUMN_TYPE
* DATA_TYPE
* TYPE_NAME
* PRECISION
* LENGTH
* SCALE
* RADIX
* NULLABLE
* REMARKS
The result set is ordered by PROCEDURE_QUALIFIER, PROCEDURE_OWNER,
PROCEDURE_NAME and COLUMN_TYPE.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_procedures
(PHP 4, PHP 5)
odbc_procedures - Get the list of procedures stored in a specific data
source
Description
resource odbc_procedures ( resource $connection_id )
resource odbc_procedures ( resource $connection_id , string $qualifier ,
string $owner , string $name )
Lists all procedures in the requested range.
Parameters
connection_id
The ODBC connection identifier, see odbc_connect() for details.
qualifier
The qualifier.
owner
The owner. This parameter accepts the following search patterns:
"%" to match zero or more characters, and "_" to match a single
character.
name
The name. This parameter accepts the following search patterns:
"%" to match zero or more characters, and "_" to match a single
character.
Return Values
Returns an ODBC result identifier containing the information or FALSE on
failure.
The result set has the following columns:
* PROCEDURE_QUALIFIER
* PROCEDURE_OWNER
* PROCEDURE_NAME
* NUM_INPUT_PARAMS
* NUM_OUTPUT_PARAMS
* NUM_RESULT_SETS
* REMARKS
* PROCEDURE_TYPE
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_result_all
(PHP 4, PHP 5)
odbc_result_all - Print result as HTML table
Description
int odbc_result_all ( resource $result_id [, string $format ] )
Prints all rows from a result identifier produced by odbc_exec(). The
result is printed in HTML table format.
Parameters
result_id
The result identifier.
format
Additional overall table formatting.
Return Values
Returns the number of rows in the result or FALSE on error.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_result
(PHP 4, PHP 5)
odbc_result - Get result data
Description
mixed odbc_result ( resource $result_id , mixed $field )
Get result data
Parameters
result_id
The ODBC resource.
field
The field name being retrieved. It can either be an integer
containing the column number of the field you want; or it can be a
string containing the name of the field.
Return Values
Returns the string contents of the field, FALSE on error, NULL for NULL
data, or TRUE for binary data.
Examples
The first call to odbc_result() returns the value of the third field in
the current record of the query result. The second function call to
odbc_result() returns the value of the field whose field name is "val" in
the current record of the query result. An error occurs if a column number
parameter for a field is less than one or exceeds the number of columns
(or fields) in the current record. Similarly, an error occurs if a field
with a name that is not one of the fieldnames of the table(s) that is(are)
being queried.
Example #1 odbc_result() examples
Notes
Field indices start from 1. Regarding the way binary or long column data
is returned refer to odbc_binmode() and odbc_longreadlen().
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_rollback
(PHP 4, PHP 5)
odbc_rollback - Rollback a transaction
Description
bool odbc_rollback ( resource $connection_id )
Rolls back all pending statements on the connection.
Parameters
connection_id
The ODBC connection identifier, see odbc_connect() for details.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_setoption
(PHP 4, PHP 5)
odbc_setoption - Adjust ODBC settings
Description
bool odbc_setoption ( resource $id , int $function , int $option , int
$param )
This function allows fiddling with the ODBC options for a particular
connection or query result. It was written to help find work around to
problems in quirky ODBC drivers. You should probably only use this
function if you are an ODBC programmer and understand the effects the
various options will have. You will certainly need a good ODBC reference
to explain all the different options and values that can be used.
Different driver versions support different options.
Because the effects may vary depending on the ODBC driver, use of this
function in scripts to be made publicly available is strongly discouraged.
Also, some ODBC options are not available to this function because they
must be set before the connection is established or the query is prepared.
However, if on a particular job it can make PHP work so your boss doesn't
tell you to use a commercial product, that's all that really matters.
Parameters
id
Is a connection id or result id on which to change the settings.
For SQLSetConnectOption(), this is a connection id. For
SQLSetStmtOption(), this is a result id.
function
Is the ODBC function to use. The value should be 1 for
SQLSetConnectOption() and 2 for SQLSetStmtOption().
option
The option to set.
param
The value for the given option.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 odbc_setoption() examples
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_specialcolumns
(PHP 4, PHP 5)
odbc_specialcolumns - Retrieves special columns
Description
resource odbc_specialcolumns ( resource $connection_id , int $type ,
string $qualifier , string $owner , string $table , int $scope , int
$nullable )
Retrieves either the optimal set of columns that uniquely identifies a row
in the table, or columns that are automatically updated when any value in
the row is updated by a transaction.
Parameters
connection_id
The ODBC connection identifier, see odbc_connect() for details.
type
When the type argument is SQL_BEST_ROWID, odbc_specialcolumns()
returns the column or columns that uniquely identify each row in
the table. When the type argument is SQL_ROWVER,
odbc_specialcolumns() returns the column or columns in the
specified table, if any, that are automatically updated by the
data source when any value in the row is updated by any
transaction.
qualifier
The qualifier.
owner
The owner.
table
The table.
scope
The scope, which orders the result set.
nullable
The nullable option.
Return Values
Returns an ODBC result identifier or FALSE on failure.
The result set has the following columns:
* SCOPE
* COLUMN_NAME
* DATA_TYPE
* TYPE_NAME
* PRECISION
* LENGTH
* SCALE
* PSEUDO_COLUMN
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_statistics
(PHP 4, PHP 5)
odbc_statistics - Retrieve statistics about a table
Description
resource odbc_statistics ( resource $connection_id , string $qualifier ,
string $owner , string $table_name , int $unique , int $accuracy )
Get statistics about a table and its indexes.
Parameters
connection_id
The ODBC connection identifier, see odbc_connect() for details.
qualifier
The qualifier.
owner
The owner.
table_name
The table name.
unique
The unique attribute.
accuracy
The accuracy.
Return Values
Returns an ODBC result identifier or FALSE on failure.
The result set has the following columns:
* TABLE_QUALIFIER
* TABLE_OWNER
* TABLE_NAME
* NON_UNIQUE
* INDEX_QUALIFIER
* INDEX_NAME
* TYPE
* SEQ_IN_INDEX
* COLUMN_NAME
* COLLATION
* CARDINALITY
* PAGES
* FILTER_CONDITION
The result set is ordered by NON_UNIQUE, TYPE, INDEX_QUALIFIER, INDEX_NAME
and SEQ_IN_INDEX.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_tableprivileges
(PHP 4, PHP 5)
odbc_tableprivileges - Lists tables and the privileges associated with
each table
Description
resource odbc_tableprivileges ( resource $connection_id , string
$qualifier , string $owner , string $name )
Lists tables in the requested range and the privileges associated with
each table.
Parameters
connection_id
The ODBC connection identifier, see odbc_connect() for details.
qualifier
The qualifier.
owner
The owner. Accepts the following search patterns: ('%' to match
zero or more characters and '_' to match a single character)
name
The name. Accepts the following search patterns: ('%' to match
zero or more characters and '_' to match a single character)
Return Values
An ODBC result identifier or FALSE on failure.
The result set has the following columns:
* TABLE_QUALIFIER
* TABLE_OWNER
* TABLE_NAME
* GRANTOR
* GRANTEE
* PRIVILEGE
* IS_GRANTABLE
The result set is ordered by TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.
----------------------------------------------------------------------
----------------------------------------------------------------------
odbc_tables
(PHP 4, PHP 5)
odbc_tables - Get the list of table names stored in a specific data source
Description
resource odbc_tables ( resource $connection_id [, string $qualifier [,
string $owner [, string $name [, string $types ]]]] )
Lists all tables in the requested range.
To support enumeration of qualifiers, owners, and table types, the
following special semantics for the qualifier, owner, name, and table_type
are available:
* If qualifier is a single percent character (%) and owner and name are
empty strings, then the result set contains a list of valid qualifiers
for the data source. (All columns except the TABLE_QUALIFIER column
contain NULLs.)
* If owner is a single percent character (%) and qualifier and name are
empty strings, then the result set contains a list of valid owners for
the data source. (All columns except the TABLE_OWNER column contain
NULLs.)
* If table_type is a single percent character (%) and qualifier, owner
and name are empty strings, then the result set contains a list of
valid table types for the data source. (All columns except the
TABLE_TYPE column contain NULLs.)
Parameters
connection_id
The ODBC connection identifier, see odbc_connect() for details.
qualifier
The qualifier.
owner
The owner. Accepts search patterns ('%' to match zero or more
characters and '_' to match a single character).
name
The name. Accepts search patterns ('%' to match zero or more
characters and '_' to match a single character).
types
If table_type is not an empty string, it must contain a list of
comma-separated values for the types of interest; each value may
be enclosed in single quotes (') or unquoted. For example,
"'TABLE','VIEW'" or "TABLE, VIEW". If the data source does not
support a specified table type, odbc_tables() does not return any
results for that type.
Return Values
Returns an ODBC result identifier containing the information or FALSE on
failure.
The result set has the following columns:
* TABLE_QUALIFIER
* TABLE_OWNER
* TABLE_NAME
* TABLE_TYPE
* REMARKS
The result set is ordered by TABLE_TYPE, TABLE_QUALIFIER, TABLE_OWNER and
TABLE_NAME.
See Also
* odbc_tableprivileges() - Lists tables and the privileges associated
with each table
----------------------------------------------------------------------
Table of Contents
* odbc_autocommit - Toggle autocommit behaviour
* odbc_binmode - Handling of binary column data
* odbc_close_all - Close all ODBC connections
* odbc_close - Close an ODBC connection
* odbc_columnprivileges - Lists columns and associated privileges for
the given table
* odbc_columns - Lists the column names in specified tables
* odbc_commit - Commit an ODBC transaction
* odbc_connect - Connect to a datasource
* odbc_cursor - Get cursorname
* odbc_data_source - Returns information about a current connection
* odbc_do - Alias of odbc_exec
* odbc_error - Get the last error code
* odbc_errormsg - Get the last error message
* odbc_exec - Prepare and execute an SQL statement
* odbc_execute - Execute a prepared statement
* odbc_fetch_array - Fetch a result row as an associative array
* odbc_fetch_into - Fetch one result row into array
* odbc_fetch_object - Fetch a result row as an object
* odbc_fetch_row - Fetch a row
* odbc_field_len - Get the length (precision) of a field
* odbc_field_name - Get the columnname
* odbc_field_num - Return column number
* odbc_field_precision - Alias of odbc_field_len
* odbc_field_scale - Get the scale of a field
* odbc_field_type - Datatype of a field
* odbc_foreignkeys - Retrieves a list of foreign keys
* odbc_free_result - Free resources associated with a result
* odbc_gettypeinfo - Retrieves information about data types supported by
the data source
* odbc_longreadlen - Handling of LONG columns
* odbc_next_result - Checks if multiple results are available
* odbc_num_fields - Number of columns in a result
* odbc_num_rows - Number of rows in a result
* odbc_pconnect - Open a persistent database connection
* odbc_prepare - Prepares a statement for execution
* odbc_primarykeys - Gets the primary keys for a table
* odbc_procedurecolumns - Retrieve information about parameters to
procedures
* odbc_procedures - Get the list of procedures stored in a specific data
source
* odbc_result_all - Print result as HTML table
* odbc_result - Get result data
* odbc_rollback - Rollback a transaction
* odbc_setoption - Adjust ODBC settings
* odbc_specialcolumns - Retrieves special columns
* odbc_statistics - Retrieve statistics about a table
* odbc_tableprivileges - Lists tables and the privileges associated with
each table
* odbc_tables - Get the list of table names stored in a specific data
source
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* ODBC Functions
* odbc_autocommit - Toggle autocommit behaviour
* odbc_binmode - Handling of binary column data
* odbc_close_all - Close all ODBC connections
* odbc_close - Close an ODBC connection
* odbc_columnprivileges - Lists columns and associated privileges
for the given table
* odbc_columns - Lists the column names in specified tables
* odbc_commit - Commit an ODBC transaction
* odbc_connect - Connect to a datasource
* odbc_cursor - Get cursorname
* odbc_data_source - Returns information about a current connection
* odbc_do - Alias of odbc_exec
* odbc_error - Get the last error code
* odbc_errormsg - Get the last error message
* odbc_exec - Prepare and execute an SQL statement
* odbc_execute - Execute a prepared statement
* odbc_fetch_array - Fetch a result row as an associative array
* odbc_fetch_into - Fetch one result row into array
* odbc_fetch_object - Fetch a result row as an object
* odbc_fetch_row - Fetch a row
* odbc_field_len - Get the length (precision) of a field
* odbc_field_name - Get the columnname
* odbc_field_num - Return column number
* odbc_field_precision - Alias of odbc_field_len
* odbc_field_scale - Get the scale of a field
* odbc_field_type - Datatype of a field
* odbc_foreignkeys - Retrieves a list of foreign keys
* odbc_free_result - Free resources associated with a result
* odbc_gettypeinfo - Retrieves information about data types
supported by the data source
* odbc_longreadlen - Handling of LONG columns
* odbc_next_result - Checks if multiple results are available
* odbc_num_fields - Number of columns in a result
* odbc_num_rows - Number of rows in a result
* odbc_pconnect - Open a persistent database connection
* odbc_prepare - Prepares a statement for execution
* odbc_primarykeys - Gets the primary keys for a table
* odbc_procedurecolumns - Retrieve information about parameters to
procedures
* odbc_procedures - Get the list of procedures stored in a specific
data source
* odbc_result_all - Print result as HTML table
* odbc_result - Get result data
* odbc_rollback - Rollback a transaction
* odbc_setoption - Adjust ODBC settings
* odbc_specialcolumns - Retrieves special columns
* odbc_statistics - Retrieve statistics about a table
* odbc_tableprivileges - Lists tables and the privileges associated
with each table
* odbc_tables - Get the list of table names stored in a specific
data source
----------------------------------------------------------------------
----------------------------------------------------------------------
PHP Data Objects
----------------------------------------------------------------------
Introduction
The PHP Data Objects (PDO) extension defines a lightweight, consistent
interface for accessing databases in PHP. Each database driver that
implements the PDO interface can expose database-specific features as
regular extension functions. Note that you cannot perform any database
functions using the PDO extension by itself; you must use a
database-specific PDO driver to access a database server.
PDO provides a data-access abstraction layer, which means that, regardless
of which database you're using, you use the same functions to issue
queries and fetch data. PDO does not provide a database abstraction; it
doesn't rewrite SQL or emulate missing features. You should use a
full-blown abstraction layer if you need that facility.
PDO ships with PHP 5.1, and is available as a PECL extension for PHP 5.0;
PDO requires the new OO features in the core of PHP 5, and so will not run
with earlier versions of PHP.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
Installing PDO on Unix systems
1. PDO and the PDO_SQLITE driver is enabled by default as of PHP 5.1.0.
You may need to enable the PDO driver for your database of choice;
consult the documentation for database-specific PDO drivers to find
out more about that. Note: When building PDO as a shared extension
(not recommended) then all PDO drivers must be loaded after PDO
itself.
2. When installing PDO as a shared module, the php.ini file needs to be
updated so that the PDO extension will be loaded automatically when
PHP runs. You will also need to enable any database specific drivers
there too; make sure that they are listed after the pdo.so line, as
PDO must be initialized before the database-specific extensions can be
loaded. If you built PDO and the database-specific extensions
statically, you can skip this step.
extension=pdo.so
Windows users
1. PDO and all the major drivers ship with PHP as shared extensions, and
simply need to be activated by editing the php.ini file:
extension=php_pdo.dll
Note:
This step is not necessary for PHP 5.3 and above, as a DLL is no
longer required for PDO.
2. Next, choose the other database-specific DLL files and either use dl()
to load them at runtime, or enable them in php.ini below php_pdo.dll.
For example:
extension=php_pdo.dll
extension=php_pdo_firebird.dll
extension=php_pdo_informix.dll
extension=php_pdo_mssql.dll
extension=php_pdo_mysql.dll
extension=php_pdo_oci.dll
extension=php_pdo_oci8.dll
extension=php_pdo_odbc.dll
extension=php_pdo_pgsql.dll
extension=php_pdo_sqlite.dll
These DLLs should exist in the system's extension_dir.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
PDO Configuration Options
Name Default Changeable Changelog
pdo.dsn.* php.ini only
Here's a short explanation of the configuration directives.
pdo.dsn.* string
Defines DSN alias. See PDO::__construct() for thorough
explanation.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
Warning
PDO uses class constants since PHP 5.1. Prior releases use global
constants in the form PDO_PARAM_BOOL.
PDO::PARAM_BOOL (integer)
Represents a boolean data type.
PDO::PARAM_NULL (integer)
Represents the SQL NULL data type.
PDO::PARAM_INT (integer)
Represents the SQL INTEGER data type.
PDO::PARAM_STR (integer)
Represents the SQL CHAR, VARCHAR, or other string data type.
PDO::PARAM_LOB (integer)
Represents the SQL large object data type.
PDO::PARAM_STMT (integer)
Represents a recordset type. Not currently supported by any
drivers.
PDO::PARAM_INPUT_OUTPUT (integer)
Specifies that the parameter is an INOUT parameter for a stored
procedure. You must bitwise-OR this value with an explicit
PDO::PARAM_* data type.
PDO::FETCH_LAZY (integer)
Specifies that the fetch method shall return each row as an object
with variable names that correspond to the column names returned
in the result set. PDO::FETCH_LAZY creates the object variable
names as they are accessed.
PDO::FETCH_ASSOC (integer)
Specifies that the fetch method shall return each row as an array
indexed by column name as returned in the corresponding result
set. If the result set contains multiple columns with the same
name, PDO::FETCH_ASSOC returns only a single value per column
name.
PDO::FETCH_NAMED (integer)
Specifies that the fetch method shall return each row as an array
indexed by column name as returned in the corresponding result
set. If the result set contains multiple columns with the same
name, PDO::FETCH_NAMED returns an array of values per column name.
PDO::FETCH_NUM (integer)
Specifies that the fetch method shall return each row as an array
indexed by column number as returned in the corresponding result
set, starting at column 0.
PDO::FETCH_BOTH (integer)
Specifies that the fetch method shall return each row as an array
indexed by both column name and number as returned in the
corresponding result set, starting at column 0.
PDO::FETCH_OBJ (integer)
Specifies that the fetch method shall return each row as an object
with property names that correspond to the column names returned
in the result set.
PDO::FETCH_BOUND (integer)
Specifies that the fetch method shall return TRUE and assign the
values of the columns in the result set to the PHP variables to
which they were bound with the PDOStatement::bindParam() or
PDOStatement::bindColumn() methods.
PDO::FETCH_COLUMN (integer)
Specifies that the fetch method shall return only a single
requested column from the next row in the result set.
PDO::FETCH_CLASS (integer)
Specifies that the fetch method shall return a new instance of the
requested class, mapping the columns to named properties in the
class.
Note: The magic __set() method is called if the property doesn't
exist in the requested class
PDO::FETCH_INTO (integer)
Specifies that the fetch method shall update an existing instance
of the requested class, mapping the columns to named properties in
the class.
PDO::FETCH_FUNC (integer)
PDO::FETCH_GROUP (integer)
PDO::FETCH_UNIQUE (integer)
PDO::FETCH_KEY_PAIR (integer)
Fetch into an array where the 1st column is a key and all
subsequent columns are values. Available since PHP 5.2.3.
PDO::FETCH_CLASSTYPE (integer)
Determine the class name from the value of first column.
PDO::FETCH_SERIALIZE (integer)
As PDO::FETCH_INTO but object is provided as a serialized string.
Available since PHP 5.1.0.
PDO::FETCH_PROPS_LATE (integer)
Available since PHP 5.2.0
PDO::ATTR_AUTOCOMMIT (integer)
If this value is FALSE, PDO attempts to disable autocommit so that
the connection begins a transaction.
PDO::ATTR_PREFETCH (integer)
Setting the prefetch size allows you to balance speed against
memory usage for your application. Not all database/driver
combinations support setting of the prefetch size. A larger
prefetch size results in increased performance at the cost of
higher memory usage.
PDO::ATTR_TIMEOUT (integer)
Sets the timeout value in seconds for communications with the
database.
PDO::ATTR_ERRMODE (integer)
See the Errors and error handling section for more information
about this attribute.
PDO::ATTR_SERVER_VERSION (integer)
This is a read only attribute; it will return information about
the version of the database server to which PDO is connected.
PDO::ATTR_CLIENT_VERSION (integer)
This is a read only attribute; it will return information about
the version of the client libraries that the PDO driver is using.
PDO::ATTR_SERVER_INFO (integer)
This is a read only attribute; it will return some meta
information about the database server to which PDO is connected.
PDO::ATTR_CONNECTION_STATUS (integer)
PDO::ATTR_CASE (integer)
Force column names to a specific case specified by the PDO::CASE_*
constants.
PDO::ATTR_CURSOR_NAME (integer)
Get or set the name to use for a cursor. Most useful when using
scrollable cursors and positioned updates.
PDO::ATTR_CURSOR (integer)
Selects the cursor type. PDO currently supports either
PDO::CURSOR_FWDONLY and PDO::CURSOR_SCROLL. Stick with
PDO::CURSOR_FWDONLY unless you know that you need a scrollable
cursor.
PDO::ATTR_DRIVER_NAME (string)
Returns the name of the driver.
Example #1 using PDO::ATTR_DRIVER_NAME
getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') {
echo "Running on mysql; doing something mysql specific here\n";
}
?>
PDO::ATTR_ORACLE_NULLS (integer)
Convert empty strings to SQL NULL values on data fetches.
PDO::ATTR_PERSISTENT (integer)
Request a persistent connection, rather than creating a new
connection. See Connections and Connection management for more
information on this attribute.
PDO::ATTR_STATEMENT_CLASS (integer)
PDO::ATTR_FETCH_CATALOG_NAMES (integer)
Prepend the containing catalog name to each column name returned
in the result set. The catalog name and column name are separated
by a decimal (.) character. Support of this attribute is at the
driver level; it may not be supported by your driver.
PDO::ATTR_FETCH_TABLE_NAMES (integer)
Prepend the containing table name to each column name returned in
the result set. The table name and column name are separated by a
decimal (.) character. Support of this attribute is at the driver
level; it may not be supported by your driver.
PDO::ATTR_STRINGIFY_FETCHES (integer)
PDO::ATTR_MAX_COLUMN_LEN (integer)
PDO::ATTR_DEFAULT_FETCH_MODE (integer)
Available since PHP 5.2.0
PDO::ATTR_EMULATE_PREPARES (integer)
Available since PHP 5.1.3.
PDO::ERRMODE_SILENT (integer)
Do not raise an error or exception if an error occurs. The
developer is expected to explicitly check for errors. This is the
default mode. See Errors and error handling for more information
about this attribute.
PDO::ERRMODE_WARNING (integer)
Issue a PHP E_WARNING message if an error occurs. See Errors and
error handling for more information about this attribute.
PDO::ERRMODE_EXCEPTION (integer)
Throw a PDOException if an error occurs. See Errors and error
handling for more information about this attribute.
PDO::CASE_NATURAL (integer)
Leave column names as returned by the database driver.
PDO::CASE_LOWER (integer)
Force column names to lower case.
PDO::CASE_UPPER (integer)
Force column names to upper case.
PDO::NULL_NATURAL (integer)
PDO::NULL_EMPTY_STRING (integer)
PDO::NULL_TO_STRING (integer)
PDO::FETCH_ORI_NEXT (integer)
Fetch the next row in the result set. Valid only for scrollable
cursors.
PDO::FETCH_ORI_PRIOR (integer)
Fetch the previous row in the result set. Valid only for
scrollable cursors.
PDO::FETCH_ORI_FIRST (integer)
Fetch the first row in the result set. Valid only for scrollable
cursors.
PDO::FETCH_ORI_LAST (integer)
Fetch the last row in the result set. Valid only for scrollable
cursors.
PDO::FETCH_ORI_ABS (integer)
Fetch the requested row by row number from the result set. Valid
only for scrollable cursors.
PDO::FETCH_ORI_REL (integer)
Fetch the requested row by relative position from the current
position of the cursor in the result set. Valid only for
scrollable cursors.
PDO::CURSOR_FWDONLY (integer)
Create a PDOStatement object with a forward-only cursor. This is
the default cursor choice, as it is the fastest and most common
data access pattern in PHP.
PDO::CURSOR_SCROLL (integer)
Create a PDOStatement object with a scrollable cursor. Pass the
PDO::FETCH_ORI_* constants to control the rows fetched from the
result set.
PDO::ERR_NONE (string)
Corresponds to SQLSTATE '00000', meaning that the SQL statement
was successfully issued with no errors or warnings. This constant
is for your convenience when checking PDO::errorCode() or
PDOStatement::errorCode() to determine if an error occurred. You
will usually know if this is the case by examining the return code
from the method that raised the error condition anyway.
PDO::PARAM_EVT_ALLOC (integer)
Allocation event
PDO::PARAM_EVT_FREE (integer)
Deallocation event
PDO::PARAM_EVT_EXEC_PRE (integer)
Event triggered prior to execution of a prepared statement.
PDO::PARAM_EVT_EXEC_POST (integer)
Event triggered subsequent to execution of a prepared statement.
PDO::PARAM_EVT_FETCH_PRE (integer)
Event triggered prior to fetching a result from a resultset.
PDO::PARAM_EVT_FETCH_POST (integer)
Event triggered subsequent to fetching a result from a resultset.
PDO::PARAM_EVT_NORMALIZE (integer)
Event triggered during bound parameter registration allowing the
driver to normalize the parameter name.
----------------------------------------------------------------------
----------------------------------------------------------------------
Connections and Connection management
Connections are established by creating instances of the PDO base class.
It doesn't matter which driver you want to use; you always use the PDO
class name. The constructor accepts parameters for specifying the database
source (known as the DSN) and optionally for the username and password (if
any).
Example #1 Connecting to MySQL
If there are any connection errors, a PDOException object will be thrown.
You may catch the exception if you want to handle the error condition, or
you may opt to leave it for an application global exception handler that
you set up via set_exception_handler().
Example #2 Handling connection errors
query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . " ";
die();
}
?>
Warning
If your application does not catch the exception thrown from the PDO
constructor, the default action taken by the zend engine is to terminate
the script and display a back trace. This back trace will likely reveal
the full database connection details, including the username and password.
It is your responsibility to catch this exception, either explicitly (via
a catch statement) or implicitly via set_exception_handler().
Upon successful connection to the database, an instance of the PDO class
is returned to your script. The connection remains active for the lifetime
of that PDO object. To close the connection, you need to destroy the
object by ensuring that all remaining references to it are deleted--you do
this by assigning NULL to the variable that holds the object. If you don't
do this explicitly, PHP will automatically close the connection when your
script ends.
Example #3 Closing a connection
Many web applications will benefit from making persistent connections to
database servers. Persistent connections are not closed at the end of the
script, but are cached and re-used when another script requests a
connection using the same credentials. The persistent connection cache
allows you to avoid the overhead of establishing a new connection every
time a script needs to talk to a database, resulting in a faster web
application.
Example #4 Persistent connections
true
));
?>
Note:
If you wish to use persistent connections, you must set
PDO::ATTR_PERSISTENT in the array of driver options passed to the PDO
constructor. If setting this attribute with PDO::setAttribute() after
instantiation of the object, the driver will not use persistent
connections.
Note:
If you're using the PDO ODBC driver and your ODBC libraries support ODBC
Connection Pooling (unixODBC and Windows are two that do; there may be
more), then it's recommended that you don't use persistent PDO
connections, and instead leave the connection caching to the ODBC
Connection Pooling layer. The ODBC Connection Pool is shared with other
modules in the process; if PDO is told to cache the connection, then
that connection would never be returned to the ODBC connection pool,
resulting in additional connections being created to service those other
modules.
----------------------------------------------------------------------
----------------------------------------------------------------------
Transactions and auto-commit
Now that you're connected via PDO, you must understand how PDO manages
transactions before you start issuing queries. If you've never encountered
transactions before, they offer 4 major features: Atomicity, Consistency,
Isolation and Durability (ACID). In layman's terms, any work carried out
in a transaction, even if it is carried out in stages, is guaranteed to be
applied to the database safely, and without interference from other
connections, when it is committed. Transactional work can also be
automatically undone at your request (provided you haven't already
committed it), which makes error handling in your scripts easier.
Transactions are typically implemented by "saving-up" your batch of
changes to be applied all at once; this has the nice side effect of
drastically improving the efficiency of those updates. In other words,
transactions can make your scripts faster and potentially more robust (you
still need to use them correctly to reap that benefit).
Unfortunately, not every database supports transactions, so PDO needs to
run in what is known as "auto-commit" mode when you first open the
connection. Auto-commit mode means that every query that you run has its
own implicit transaction, if the database supports it, or no transaction
if the database doesn't support transactions. If you need a transaction,
you must use the PDO::beginTransaction() method to initiate one. If the
underlying driver does not support transactions, a PDOException will be
thrown (regardless of your error handling settings: this is always a
serious error condition). Once you are in a transaction, you may use
PDO::commit() or PDO::rollBack() to finish it, depending on the success of
the code you run during the transaction.
Warning
PDO only checks for transaction capabilities on driver level. If certain
runtime conditions mean that transactions are unavailable,
PDO::beginTransaction() will still return TRUE without error if the
database server accepts the request to start a transaction.
An example of this would be trying to use transactions on MyISAM tables on
a MySQL database.
When the script ends or when a connection is about to be closed, if you
have an outstanding transaction, PDO will automatically roll it back. This
is a safety measure to help avoid inconsistency in the cases where the
script terminates unexpectedly--if you didn't explicitly commit the
transaction, then it is assumed that something went awry, so the rollback
is performed for the safety of your data.
Warning
The automatic rollback only happens if you initiate the transaction via
PDO::beginTransaction(). If you manually issue a query that begins a
transaction PDO has no way of knowing about it and thus cannot roll it
back if something bad happens.
Example #1 Executing a batch in a transaction
In the following sample, let's assume that we are creating a set of
entries for a new employee, who has been assigned an ID number of 23. In
addition to entering the basic data for that person, we also need to
record their salary. It's pretty simple to make two separate updates, but
by enclosing them within the PDO::beginTransaction() and PDO::commit()
calls, we are guaranteeing that no one else will be able to see those
changes until they are complete. If something goes wrong, the catch block
rolls back all changes made since the transaction was started, and then
prints out an error message.
true));
echo "Connected\n";
} catch (Exception $e) {
die("Unable to connect: " . $e->getMessage());
}
try {
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->beginTransaction();
$dbh->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')");
$dbh->exec("insert into salarychange (id, amount, changedate)
values (23, 50000, NOW())");
$dbh->commit();
} catch (Exception $e) {
$dbh->rollBack();
echo "Failed: " . $e->getMessage();
}
?>
You're not limited to making updates in a transaction; you can also issue
complex queries to extract data, and possibly use that information to
build up more updates and queries; while the transaction is active, you
are guaranteed that no one else can make changes while you are in the
middle of your work. For further reading on transactions, refer to the
documentation provided by your database server.
----------------------------------------------------------------------
----------------------------------------------------------------------
Prepared statements and stored procedures
Many of the more mature databases support the concept of prepared
statements. What are they? They can be thought of as a kind of compiled
template for the SQL that an application wants to run, that can be
customized using variable parameters. Prepared statements offer two major
benefits:
* The query only needs to be parsed (or prepared) once, but can be
executed multiple times with the same or different parameters. When
the query is prepared, the database will analyze, compile and optimize
it's plan for executing the query. For complex queries this process
can take up enough time that it will noticeably slow down an
application if there is a need to repeat the same query many times
with different parameters. By using a prepared statement the
application avoids repeating the analyze/compile/optimize cycle. This
means that prepared statements use fewer resources and thus run
faster.
* The parameters to prepared statements don't need to be quoted; the
driver automatically handles this. If an application exclusively uses
prepared statements, the developer can be sure that no SQL injection
will occur (however, if other portions of the query are being built up
with unescaped input, SQL injection is still possible).
Prepared statements are so useful that they are the only feature that PDO
will emulate for drivers that don't support them. This ensures that an
application will be able to use the same data access paradigm regardless
of the capabilities of the database.
Example #1 Repeated inserts using prepared statements
This example performs an INSERT query by substituting a name and a value
for the named placeholders.
prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>
Example #2 Repeated inserts using prepared statements
This example performs an INSERT query by substituting a name and a value
for the positional ? placeholders.
prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>
Example #3 Fetching data using prepared statements
This example fetches data based on a key value supplied by a form. The
user input is automatically quoted, so there is no risk of a SQL injection
attack.
prepare("SELECT * FROM REGISTRY where name = ?");
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
?>
If the database driver supports it, an application may also bind
parameters for output as well as input. Output parameters are typically
used to retrieve values from stored procedures. Output parameters are
slightly more complex to use than input parameters, in that a developer
must know how large a given parameter might be when they bind it. If the
value turns out to be larger than the size they suggested, an error is
raised.
Example #4 Calling a stored procedure with an output parameter
prepare("CALL sp_returns_string(?)");
$stmt->bindParam(1, $return_value, PDO::PARAM_STR, 4000);
// call the stored procedure
$stmt->execute();
print "procedure returned $return_value\n";
?>
Developers may also specify parameters that hold values both input and
output; the syntax is similar to output parameters. In this next example,
the string 'hello' is passed into the stored procedure, and when it
returns, hello is replaced with the return value of the procedure.
Example #5 Calling a stored procedure with an input/output parameter
prepare("CALL sp_takes_string_returns_string(?)");
$value = 'hello';
$stmt->bindParam(1, $value, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000);
// call the stored procedure
$stmt->execute();
print "procedure returned $value\n";
?>
Example #6 Invalid use of placeholder
prepare("SELECT * FROM REGISTRY where name LIKE '%?%'");
$stmt->execute(array($_GET['name']));
// placeholder must be used in the place of the whole value
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name LIKE ?");
$stmt->execute(array("%$_GET[name]%"));
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
Errors and error handling
PDO offers you a choice of 3 different error handling strategies, to fit
your style of application development.
* PDO::ERRMODE_SILENT
This is the default mode. PDO will simply set the error code for you
to inspect using the PDO::errorCode() and PDO::errorInfo() methods on
both the statement and database objects; if the error resulted from a
call on a statement object, you would invoke the
PDOStatement::errorCode() or PDOStatement::errorInfo() method on that
object. If the error resulted from a call on the database object, you
would invoke those methods on the database object instead.
* PDO::ERRMODE_WARNING
In addition to setting the error code, PDO will emit a traditional
E_WARNING message. This setting is useful during debugging/testing, if
you just want to see what problems occurred without interrupting the
flow of the application.
* PDO::ERRMODE_EXCEPTION
In addition to setting the error code, PDO will throw a PDOException
and set its properties to reflect the error code and error
information. This setting is also useful during debugging, as it will
effectively "blow up" the script at the point of the error, very
quickly pointing a finger at potential problem areas in your code
(remember: transactions are automatically rolled back if the exception
causes the script to terminate).
Exception mode is also useful because you can structure your error
handling more clearly than with traditional PHP-style warnings, and
with less code/nesting than by running in silent mode and explicitly
checking the return value of each database call.
See Exceptions for more information about Exceptions in PHP.
PDO standardizes on using SQL-92 SQLSTATE error code strings; individual
PDO drivers are responsible for mapping their native codes to the
appropriate SQLSTATE codes. The PDO::errorCode() method returns a single
SQLSTATE code. If you need more specific information about an error, PDO
also offers an PDO::errorInfo() method which returns an array containing
the SQLSTATE code, the driver specific error code and driver specific
error string.
Example #1 Create a PDO instance and set the error mode
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
Large Objects (LOBs)
At some point in your application, you might find that you need to store
"large" data in your database. Large typically means "around 4kb or more",
although some databases can happily handle up to 32kb before data becomes
"large". Large objects can be either textual or binary in nature. PDO
allows you to work with this large data type by using the PDO::PARAM_LOB
type code in your PDOStatement::bindParam() or PDOStatement::bindColumn()
calls. PDO::PARAM_LOB tells PDO to map the data as a stream, so that you
can manipulate it using the PHP Streams API.
Example #1 Displaying an image from a database
This example binds the LOB into the variable named $lob and then sends it
to the browser using fpassthru(). Since the LOB is represented as a
stream, functions such as fgets(), fread() and stream_get_contents() can
be used on it.
prepare("select contenttype, imagedata from images where id=?");
$stmt->execute(array($_GET['id']));
$stmt->bindColumn(1, $type, PDO::PARAM_STR, 256);
$stmt->bindColumn(2, $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);
header("Content-Type: $type");
fpassthru($lob);
?>
Example #2 Inserting an image into a database
This example opens up a file and passes the file handle to PDO to insert
it as a LOB. PDO will do its best to get the contents of the file up to
the database in the most efficient manner possible.
prepare("insert into images (id, contenttype, imagedata) values (?, ?, ?)");
$id = get_new_id(); // some function to allocate a new ID
// assume that we are running as part of a file upload form
// You can find more information in the PHP documentation
$fp = fopen($_FILES['file']['tmp_name'], 'rb');
$stmt->bindParam(1, $id);
$stmt->bindParam(2, $_FILES['file']['type']);
$stmt->bindParam(3, $fp, PDO::PARAM_LOB);
$db->beginTransaction();
$stmt->execute();
$db->commit();
?>
Example #3 Inserting an image into a database: Oracle
Oracle requires a slightly different syntax for inserting a lob from a
file. It's also essential that you perform the insert under a transaction,
otherwise your newly inserted LOB will be committed with a zero-length as
part of the implicit commit that happens when the query is executed:
prepare("insert into images (id, contenttype, imagedata) " .
"VALUES (?, ?, EMPTY_BLOB()) RETURNING imagedata INTO ?");
$id = get_new_id(); // some function to allocate a new ID
// assume that we are running as part of a file upload form
// You can find more information in the PHP documentation
$fp = fopen($_FILES['file']['tmp_name'], 'rb');
$stmt->bindParam(1, $id);
$stmt->bindParam(2, $_FILES['file']['type']);
$stmt->bindParam(3, $fp, PDO::PARAM_LOB);
$stmt->beginTransaction();
$stmt->execute();
$stmt->commit();
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
The PDO class
Introduction
Represents a connection between PHP and a database server.
Class synopsis
PDO {
__construct ( string $dsn [, string $username [, string $password [, array
$driver_options ]]] )
bool beginTransaction ( void )
bool commit ( void )
mixed errorCode ( void )
array errorInfo ( void )
int exec ( string $statement )
mixed getAttribute ( int $attribute )
array getAvailableDrivers ( void )
bool inTransaction ( void )
string lastInsertId ([ string $name = NULL ] )
PDOStatement prepare ( string $statement [, array $driver_options =
array() ] )
PDOStatement query ( string $statement )
string quote ( string $string [, int $parameter_type = PDO::PARAM_STR ] )
bool rollBack ( void )
bool setAttribute ( int $attribute , mixed $value )
}
----------------------------------------------------------------------
PDO::beginTransaction
(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
PDO::beginTransaction - Initiates a transaction
Description
bool PDO::beginTransaction ( void )
Turns off autocommit mode. While autocommit mode is turned off, changes
made to the database via the PDO object instance are not committed until
you end the transaction by calling PDO::commit(). Calling PDO::rollBack()
will roll back all changes to the database and return the connection to
autocommit mode.
Some databases, including MySQL, automatically issue an implicit COMMIT
when a database definition language (DDL) statement such as DROP TABLE or
CREATE TABLE is issued within a transaction. The implicit COMMIT will
prevent you from rolling back any other changes within the transaction
boundary.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Roll back a transaction
The following example begins a transaction and issues two statements that
modify the database before rolling back the changes. On MySQL, however,
the DROP TABLE statement automatically commits the transaction so that
none of the changes in the transaction are rolled back.
beginTransaction();
/* Change the database schema and data */
$sth = $dbh->exec("DROP TABLE fruit");
$sth = $dbh->exec("UPDATE dessert
SET name = 'hamburger'");
/* Recognize mistake and roll back changes */
$dbh->rollBack();
/* Database connection is now back in autocommit mode */
?>
See Also
* PDO::commit() - Commits a transaction
* PDO::rollBack() - Rolls back a transaction
* Transactions and auto-commit
----------------------------------------------------------------------
----------------------------------------------------------------------
PDO::commit
(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
PDO::commit - Commits a transaction
Description
bool PDO::commit ( void )
Commits a transaction, returning the database connection to autocommit
mode until the next call to PDO::beginTransaction() starts a new
transaction.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Commit a transaction
beginTransaction();
/* Change the database schema */
$sth = $dbh->exec("DROP TABLE fruit");
/* Commit the changes */
$dbh->commit();
/* Database connection is now back in autocommit mode */
?>
See Also
* PDO::beginTransaction() - Initiates a transaction
* PDO::rollBack() - Rolls back a transaction
* Transactions and auto-commit
----------------------------------------------------------------------
----------------------------------------------------------------------
PDO::__construct
(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
PDO::__construct - Creates a PDO instance representing a connection to a
database
Description
PDO::__construct() ( string $dsn [, string $username [, string $password
[, array $driver_options ]]] )
Creates a PDO instance to represent a connection to the requested
database.
Parameters
dsn
The Data Source Name, or DSN, contains the information required to
connect to the database.
In general, a DSN consists of the PDO driver name, followed by a
colon, followed by the PDO driver-specific connection syntax.
Further information is available from the PDO driver-specific
documentation.
The dsn parameter supports three different methods of specifying
the arguments required to create a database connection:
Driver invocation
dsn contains the full DSN.
URI invocation
dsn consists of uri: followed by a URI that defines
the location of a file containing the DSN string. The
URI can specify a local file or a remote URL.
uri:file:///path/to/dsnfile
Aliasing
dsn consists of a name name that maps to pdo.dsn.name
in php.ini defining the DSN string.
Note:
The alias must be defined in php.ini, and not
.htaccess or httpd.conf
username
The user name for the DSN string. This parameter is optional for
some PDO drivers.
password
The password for the DSN string. This parameter is optional for
some PDO drivers.
driver_options
A key=>value array of driver-specific connection options.
Return Values
Returns a PDO object on success.
Errors/Exceptions
PDO::__construct() throws a PDOException if the attempt to connect to the
requested database fails.
Examples
Example #1 Create a PDO instance via driver invocation
getMessage();
}
?>
Example #2 Create a PDO instance via URI invocation
The following example assumes that the file /usr/local/dbconnect exists
with file permissions that enable PHP to read the file. The file contains
the PDO DSN to connect to a DB2 database through the PDO_ODBC driver:
odbc:DSN=SAMPLE;UID=john;PWD=mypass
The PHP script can then create a database connection by simply passing the
uri: parameter and pointing to the file URI:
getMessage();
}
?>
Example #3 Create a PDO instance using an alias
The following example assumes that php.ini contains the following entry to
enable a connection to a MySQL database using only the alias mydb:
[PDO]
pdo.dsn.mydb="mysql:dbname=testdb;host=localhost"
getMessage();
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
PDO::errorCode
(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
PDO::errorCode - Fetch the SQLSTATE associated with the last operation on
the database handle
Description
mixed PDO::errorCode ( void )
Return Values
Returns an SQLSTATE, a five characters alphanumeric identifier defined in
the ANSI SQL-92 standard. Briefly, an SQLSTATE consists of a two
characters class value followed by a three characters subclass value. A
class value of 01 indicates a warning and is accompanied by a return code
of SQL_SUCCESS_WITH_INFO. Class values other than '01', except for the
class 'IM', indicate an error. The class 'IM' is specific to warnings and
errors that derive from the implementation of PDO (or perhaps ODBC, if
you're using the ODBC driver) itself. The subclass value '000' in any
class indicates that there is no subclass for that SQLSTATE.
PDO::errorCode() only retrieves error codes for operations performed
directly on the database handle. If you create a PDOStatement object
through PDO::prepare() or PDO::query() and invoke an error on the
statement handle, PDO::errorCode() will not reflect that error. You must
call PDOStatement::errorCode() to return the error code for an operation
performed on a particular statement handle.
Returns NULL if no operation has been run on the database handle.
Examples
Example #1 Retrieving an SQLSTATE code
exec("INSERT INTO bones(skull) VALUES ('lucy')");
echo "\nPDO::errorCode(): ";
print $dbh->errorCode();
?>
The above example will output:
PDO::errorCode(): 42S02
See Also
* PDO::errorInfo() - Fetch extended error information associated with
the last operation on the database handle
* PDOStatement::errorCode() - Fetch the SQLSTATE associated with the
last operation on the statement handle
* PDOStatement::errorInfo() - Fetch extended error information
associated with the last operation on the statement handle
----------------------------------------------------------------------
----------------------------------------------------------------------
PDO::errorInfo
(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
PDO::errorInfo - Fetch extended error information associated with the last
operation on the database handle
Description
array PDO::errorInfo ( void )
Return Values
PDO::errorInfo() returns an array of error information about the last
operation performed by this database handle. The array consists of the
following fields:
Element Information
0 SQLSTATE error code (a five characters alphanumeric identifier
defined in the ANSI SQL standard).
1 Driver-specific error code.
2 Driver-specific error message.
Note:
If the SQLSTATE error code is not set or there is no driver-specific
error, the elements following element 0 will be set to NULL.
PDO::errorInfo() only retrieves error information for operations performed
directly on the database handle. If you create a PDOStatement object
through PDO::prepare() or PDO::query() and invoke an error on the
statement handle, PDO::errorInfo() will not reflect the error from the
statement handle. You must call PDOStatement::errorInfo() to return the
error information for an operation performed on a particular statement
handle.
Examples
Example #1 Displaying errorInfo() fields for a PDO_ODBC connection to a
DB2 database
prepare('bogus sql');
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
?>
The above example will output:
PDO::errorInfo():
Array
(
[0] => HY000
[1] => 1
[2] => near "bogus": syntax error
)
See Also
* PDO::errorCode() - Fetch the SQLSTATE associated with the last
operation on the database handle
* PDOStatement::errorCode() - Fetch the SQLSTATE associated with the
last operation on the statement handle
* PDOStatement::errorInfo() - Fetch extended error information
associated with the last operation on the statement handle
----------------------------------------------------------------------
----------------------------------------------------------------------
PDO::exec
(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
PDO::exec - Execute an SQL statement and return the number of affected
rows
Description
int PDO::exec ( string $statement )
PDO::exec() executes an SQL statement in a single function call, returning
the number of rows affected by the statement.
PDO::exec() does not return results from a SELECT statement. For a SELECT
statement that you only need to issue once during your program, consider
issuing PDO::query(). For a statement that you need to issue multiple
times, prepare a PDOStatement object with PDO::prepare() and issue the
statement with PDOStatement::execute().
Parameters
statement
The SQL statement to prepare and execute.
Data inside the query should be properly escaped.
Return Values
PDO::exec() returns the number of rows that were modified or deleted by
the SQL statement you issued. If no rows were affected, PDO::exec()
returns 0.
Warning
This function may return Boolean FALSE, but may also return a non-Boolean
value which evaluates to FALSE, such as 0 or "". Please read the section
on Booleans for more information. Use the === operator for testing the
return value of this function.
The following example incorrectly relies on the return value of
PDO::exec(), wherein a statement that affected 0 rows results in a call to
die():
exec() or die(print_r($db->errorInfo(), true));
?>
Examples
Example #1 Issuing a DELETE statement
Count the number of rows deleted by a DELETE statement with no WHERE
clause.
exec("DELETE FROM fruit WHERE colour = 'red'");
/* Return number of rows that were deleted */
print("Deleted $count rows.\n");
?>
The above example will output:
Deleted 1 rows.
See Also
* PDO::prepare() - Prepares a statement for execution and returns a
statement object
* PDO::query() - Executes an SQL statement, returning a result set as a
PDOStatement object
* PDOStatement::execute() - Executes a prepared statement
----------------------------------------------------------------------
----------------------------------------------------------------------
PDO::getAttribute
(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)
PDO::getAttribute - Retrieve a database connection attribute
Description
mixed PDO::getAttribute ( int $attribute )
This function returns the value of a database connection attribute. To
retrieve PDOStatement attributes, refer to PDOStatement::getAttribute().
Note that some database/driver combinations may not support all of the
database connection attributes.
Parameters
attribute
One of the PDO::ATTR_* constants. The constants that apply to
database connections are as follows:
* PDO::ATTR_AUTOCOMMIT
* PDO::ATTR_CASE
* PDO::ATTR_CLIENT_VERSION
* PDO::ATTR_CONNECTION_STATUS
* PDO::ATTR_DRIVER_NAME
* PDO::ATTR_ERRMODE
* PDO::ATTR_ORACLE_NULLS
* PDO::ATTR_PERSISTENT
* PDO::ATTR_PREFETCH
* PDO::ATTR_SERVER_INFO
* PDO::ATTR_SERVER_VERSION
* PDO::ATTR_TIMEOUT
Return Values
A successful call returns the value of the requested PDO attribute. An
unsuccessful call returns null.
Examples
Example #1 Retrieving database connection attributes
getAttribute(constant("PDO::ATTR_$val")) . "\n";
}
?>
See Also
* PDO::setAttribute() - Set an attribute
* PDOStatement::getAttribute() - Retrieve a statement attribute
* PDOStatement::setAttribute() - Set a statement attribute
----------------------------------------------------------------------
----------------------------------------------------------------------
PDO::getAvailableDrivers
(PHP 5 >= 5.1.3, PECL pdo >= 1.0.3)
PDO::getAvailableDrivers - Return an array of available PDO drivers
Description
array PDO::getAvailableDrivers ( void )
array pdo_drivers ( void )
This function returns all currently available PDO drivers which can be
used in DSN parameter of PDO::__construct(). This is a static method.
Return Values
PDO::getAvailableDrivers() returns an array of PDO driver names. If no
drivers are available, it returns an empty array.
Examples
Example #1 A PDO::getAvailableDrivers() example
The above example will output something similar to:
Array
(
[0] => mysql
[1] => sqlite
)
----------------------------------------------------------------------
----------------------------------------------------------------------
PDO::inTransaction
(PHP 5 >= 5.3.3, Bundled pdo_pgsql)
PDO::inTransaction - Checks if inside a transaction
Description
bool PDO::inTransaction ( void )
Checks if a transaction is currently active within the driver.
Parameters
This function has no parameters.
Return Values
Returns TRUE if a transaction is currently active, and FALSE if not.
Return Values
Note:
Note that currently only the PostgreSQL driver implements this method.
----------------------------------------------------------------------
----------------------------------------------------------------------
PDO::lastInsertId
(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
PDO::lastInsertId - Returns the ID of the last inserted row or sequence
value
Description
string PDO::lastInsertId ([ string $name = NULL ] )
Returns the ID of the last inserted row, or the last value from a sequence
object, depending on the underlying driver. For example, PDO_PGSQL()
requires you to specify the name of a sequence object for the name
parameter.
Note:
This method may not return a meaningful or consistent result across
different PDO drivers, because the underlying database may not even
support the notion of auto-increment fields or sequences.
Parameters
name
Name of the sequence object from which the ID should be returned.
Return Values
If a sequence name was not specified for the name parameter,
PDO::lastInsertId() returns a string representing the row ID of the last
row that was inserted into the database.
If a sequence name was specified for the name parameter,
PDO::lastInsertId() returns a string representing the last value retrieved
from the specified sequence object.
If the PDO driver does not support this capability, PDO::lastInsertId()
triggers an IM001 SQLSTATE.
----------------------------------------------------------------------
----------------------------------------------------------------------
PDO::prepare
(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
PDO::prepare - Prepares a statement for execution and returns a statement
object
Description
PDOStatement PDO::prepare ( string $statement [, array $driver_options =
array() ] )
Prepares an SQL statement to be executed by the PDOStatement::execute()
method. The SQL statement can contain zero or more named (:name) or
question mark (?) parameter markers for which real values will be
substituted when the statement is executed. You cannot use both named and
question mark parameter markers within the same SQL statement; pick one or
the other parameter style. Use these parameters to bind any user-input, do
not include the user-input directly in the query.
You must include a unique parameter marker for each value you wish to pass
in to the statement when you call PDOStatement::execute(). You cannot use
a named parameter marker of the same name twice in a prepared statement.
You cannot bind multiple values to a single named parameter in, for
example, the IN() clause of an SQL statement.
Calling PDO::prepare() and PDOStatement::execute() for statements that
will be issued multiple times with different parameter values optimizes
the performance of your application by allowing the driver to negotiate
client and/or server side caching of the query plan and meta information,
and helps to prevent SQL injection attacks by eliminating the need to
manually quote the parameters.
PDO will emulate prepared statements/bound parameters for drivers that do
not natively support them, and can also rewrite named or question mark
style parameter markers to something more appropriate, if the driver
supports one style but not the other.
Parameters
statement
This must be a valid SQL statement for the target database server.
driver_options
This array holds one or more key=>value pairs to set attribute
values for the PDOStatement object that this method returns. You
would most commonly use this to set the PDO::ATTR_CURSOR value to
PDO::CURSOR_SCROLL to request a scrollable cursor. Some drivers
have driver specific options that may be set at prepare-time.
Return Values
If the database server successfully prepares the statement, PDO::prepare()
returns a PDOStatement object. If the database server cannot successfully
prepare the statement, PDO::prepare() returns FALSE or emits PDOException
(depending on error handling).
Note:
Emulated prepared statements does not communicate with the database
server so PDO::prepare() does not check the statement.
Examples
Example #1 Prepare an SQL statement with named parameters
prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
$yellow = $sth->fetchAll();
?>
Example #2 Prepare an SQL statement with question mark parameters
prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->execute(array(150, 'red'));
$red = $sth->fetchAll();
$sth->execute(array(175, 'yellow'));
$yellow = $sth->fetchAll();
?>
See Also
* PDO::exec() - Execute an SQL statement and return the number of
affected rows
* PDO::query() - Executes an SQL statement, returning a result set as a
PDOStatement object
* PDOStatement::execute() - Executes a prepared statement
----------------------------------------------------------------------
----------------------------------------------------------------------
PDO::query
(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)
PDO::query - Executes an SQL statement, returning a result set as a
PDOStatement object
Description
PDOStatement PDO::query ( string $statement )
PDOStatement PDO::query ( string $statement , int $PDO::FETCH_COLUMN , int
$colno )
PDOStatement PDO::query ( string $statement , int $PDO::FETCH_CLASS ,
string $classname , array $ctorargs )
PDOStatement PDO::query ( string $statement , int $PDO::FETCH_INTO ,
object $object )
PDO::query() executes an SQL statement in a single function call,
returning the result set (if any) returned by the statement as a
PDOStatement object.
For a query that you need to issue multiple times, you will realize better
performance if you prepare a PDOStatement object using PDO::prepare() and
issue the statement with multiple calls to PDOStatement::execute().
If you do not fetch all of the data in a result set before issuing your
next call to PDO::query(), your call may fail. Call
PDOStatement::closeCursor() to release the database resources associated
with the PDOStatement object before issuing your next call to
PDO::query().
Note:
Although this function is only documented as having a single parameter,
you may pass additional arguments to this function. They will be treated
as though you called PDOStatement::setFetchMode() on the resultant
statement object.
Parameters
statement
The SQL statement to prepare and execute.
Data inside the query should be properly escaped.
Return Values
PDO::query() returns a PDOStatement object, or FALSE on failure.
Examples
Example #1 Demonstrate PDO::query
A nice feature of PDO::query() is that it enables you to iterate over the
rowset returned by a successfully executed SELECT statement.
query($sql) as $row) {
print $row['name'] . "\t";
print $row['color'] . "\t";
print $row['calories'] . "\n";
}
}
?>
The above example will output:
apple red 150
banana yellow 250
kiwi brown 75
lemon yellow 25
orange orange 300
pear green 150
watermelon pink 90
See Also
* PDO::exec() - Execute an SQL statement and return the number of
affected rows
* PDO::prepare() - Prepares a statement for execution and returns a
statement object
* PDOStatement::execute() - Executes a prepared statement
----------------------------------------------------------------------
----------------------------------------------------------------------
PDO::quote
(PHP 5 >= 5.1.0, PECL pdo >= 0.2.1)
PDO::quote - Quotes a string for use in a query.
Description
string PDO::quote ( string $string [, int $parameter_type = PDO::PARAM_STR
] )
PDO::quote() places quotes around the input string (if required) and
escapes special characters within the input string, using a quoting style
appropriate to the underlying driver.
If you are using this function to build SQL statements, you are strongly
recommended to use PDO::prepare() to prepare SQL statements with bound
parameters instead of using PDO::quote() to interpolate user input into an
SQL statement. Prepared statements with bound parameters are not only more
portable, more convenient, immune to SQL injection, but are often much
faster to execute than interpolated queries, as both the server and client
side can cache a compiled form of the query.
Not all PDO drivers implement this method (notably PDO_ODBC). Consider
using prepared statements instead.
Parameters
string
The string to be quoted.
parameter_type
Provides a data type hint for drivers that have alternate quoting
styles.
Return Values
Returns a quoted string that is theoretically safe to pass into an SQL
statement. Returns FALSE if the driver does not support quoting in this
way.
Examples
Example #1 Quoting a normal string
quote($string) . "\n";
?>
The above example will output:
Unquoted string: Nice
Quoted string: 'Nice'
Example #2 Quoting a dangerous string
quote($string) . "\n";
?>
The above example will output:
Unquoted string: Naughty ' string
Quoted string: 'Naughty '' string'
Example #3 Quoting a complex string
quote($string) . "\n";
?>
The above example will output:
Unquoted string: Co'mpl''ex "st'"ring
Quoted string: 'Co''mpl''''ex "st''"ring'
See Also
* PDO::prepare() - Prepares a statement for execution and returns a
statement object
* PDOStatement::execute() - Executes a prepared statement
----------------------------------------------------------------------
----------------------------------------------------------------------
PDO::rollBack
(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
PDO::rollBack - Rolls back a transaction
Description
bool PDO::rollBack ( void )
Rolls back the current transaction, as initiated by
PDO::beginTransaction(). It is an error to call this method if no
transaction is active.
If the database was set to autocommit mode, this function will restore
autocommit mode after it has rolled back the transaction.
Some databases, including MySQL, automatically issue an implicit COMMIT
when a database definition language (DDL) statement such as DROP TABLE or
CREATE TABLE is issued within a transaction. The implicit COMMIT will
prevent you from rolling back any other changes within the transaction
boundary.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Roll back a transaction
The following example begins a transaction and issues two statements that
modify the database before rolling back the changes. On MySQL, however,
the DROP TABLE statement automatically commits the transaction so that
none of the changes in the transaction are rolled back.
beginTransaction();
/* Change the database schema and data */
$sth = $dbh->exec("DROP TABLE fruit");
$sth = $dbh->exec("UPDATE dessert
SET name = 'hamburger'");
/* Recognize mistake and roll back changes */
$dbh->rollBack();
/* Database connection is now back in autocommit mode */
?>
See Also
* PDO::beginTransaction() - Initiates a transaction
* PDO::commit() - Commits a transaction
* Transactions and auto-commit
----------------------------------------------------------------------
----------------------------------------------------------------------
PDO::setAttribute
(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
PDO::setAttribute - Set an attribute
Description
bool PDO::setAttribute ( int $attribute , mixed $value )
Sets an attribute on the database handle. Some of the available generic
attributes are listed below; some drivers may make use of additional
driver specific attributes.
* PDO::ATTR_CASE: Force column names to a specific case.
* PDO::CASE_LOWER: Force column names to lower case.
* PDO::CASE_NATURAL: Leave column names as returned by the database
driver.
* PDO::CASE_UPPER: Force column names to upper case.
* PDO::ATTR_ERRMODE: Error reporting.
* PDO::ERRMODE_SILENT: Just set error codes.
* PDO::ERRMODE_WARNING: Raise E_WARNING.
* PDO::ERRMODE_EXCEPTION: Throw exceptions.
* PDO::ATTR_ORACLE_NULLS (available with all drivers, not just Oracle):
Conversion of NULL and empty strings.
* PDO::NULL_NATURAL: No conversion.
* PDO::NULL_EMPTY_STRING: Empty string is converted to NULL.
* PDO::NULL_TO_STRING: NULL is converted to an empty string.
* PDO::ATTR_STRINGIFY_FETCHES: Convert numeric values to strings when
fetching. Requires bool.
* PDO::ATTR_STATEMENT_CLASS: Set user-supplied statement class derived
from PDOStatement. Cannot be used with persistent PDO instances.
Requires array(string classname, array(mixed constructor_args)).
* PDO::ATTR_TIMEOUT: Specifies the timeout duration in seconds. Not all
drivers support this option, and it's meaning may differ from driver
to driver. For example, sqlite will wait for up to this time value
before giving up on obtaining an writable lock, but other drivers may
interpret this as a connect or a read timeout interval. Requires int.
* PDO::ATTR_AUTOCOMMIT (available in OCI, Firebird and MySQL): Whether
to autocommit every single statement.
* PDO::ATTR_EMULATE_PREPARES Enables or disables emulation of prepared
statements. Some drivers do not support native prepared statements or
have limited support for them. Use this setting to force PDO to either
always emulate prepared statements (if TRUE), or to try to use native
prepared statements (if FALSE). It will always fall back to emulating
the prepared statement if the driver cannot successfully prepare the
current query. Requires bool.
* PDO::MYSQL_ATTR_USE_BUFFERED_QUERY (available in MySQL): Use buffered
queries.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
Table of Contents
* PDO::beginTransaction - Initiates a transaction
* PDO::commit - Commits a transaction
* PDO::__construct - Creates a PDO instance representing a connection to
a database
* PDO::errorCode - Fetch the SQLSTATE associated with the last operation
on the database handle
* PDO::errorInfo - Fetch extended error information associated with the
last operation on the database handle
* PDO::exec - Execute an SQL statement and return the number of affected
rows
* PDO::getAttribute - Retrieve a database connection attribute
* PDO::getAvailableDrivers - Return an array of available PDO drivers
* PDO::inTransaction - Checks if inside a transaction
* PDO::lastInsertId - Returns the ID of the last inserted row or
sequence value
* PDO::prepare - Prepares a statement for execution and returns a
statement object
* PDO::query - Executes an SQL statement, returning a result set as a
PDOStatement object
* PDO::quote - Quotes a string for use in a query.
* PDO::rollBack - Rolls back a transaction
* PDO::setAttribute - Set an attribute
----------------------------------------------------------------------
----------------------------------------------------------------------
The PDOStatement class
Introduction
Represents a prepared statement and, after the statement is executed, an
associated result set.
Class synopsis
PDOStatement implements Traversable {
/* Properties */
readonly string $PDOStatement->queryString;
/* Methods */
bool PDOStatement::bindColumn ( mixed $column , mixed &$param [, int $type
[, int $maxlen [, mixed $driverdata ]]] )
bool PDOStatement::bindParam ( mixed $parameter , mixed &$variable [, int
$data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )
bool PDOStatement::bindValue ( mixed $parameter , mixed $value [, int
$data_type = PDO::PARAM_STR ] )
bool PDOStatement::closeCursor ( void )
int PDOStatement::columnCount ( void )
bool PDOStatement::debugDumpParams ( void )
string PDOStatement::errorCode ( void )
array PDOStatement::errorInfo ( void )
bool PDOStatement::execute ([ array $input_parameters ] )
mixed PDOStatement::fetch ([ int $fetch_style = PDO::FETCH_BOTH [, int
$cursor_orientation = PDO::FETCH_ORI_NEXT [, int $cursor_offset = 0 ]]] )
array PDOStatement::fetchAll ([ int $fetch_style = PDO::FETCH_BOTH [,
mixed $fetch_argument [, array $ctor_args = array() ]]] )
string PDOStatement::fetchColumn ([ int $column_number = 0 ] )
mixed PDOStatement::fetchObject ([ string $class_name = "stdClass" [,
array $ctor_args ]] )
mixed PDOStatement::getAttribute ( int $attribute )
array PDOStatement::getColumnMeta ( int $column )
bool PDOStatement::nextRowset ( void )
int PDOStatement::rowCount ( void )
bool PDOStatement::setAttribute ( int $attribute , mixed $value )
bool PDOStatement::setFetchMode ( int $mode )
}
Properties
queryString
Used query string.
----------------------------------------------------------------------
PDOStatement->bindColumn
(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
PDOStatement->bindColumn - Bind a column to a PHP variable
Description
bool PDOStatement::bindColumn ( mixed $column , mixed &$param [, int $type
[, int $maxlen [, mixed $driverdata ]]] )
PDOStatement::bindColumn() arranges to have a particular variable bound to
a given column in the result-set from a query. Each call to
PDOStatement::fetch() or PDOStatement::fetchAll() will update all the
variables that are bound to columns.
Note:
Since information about the columns is not always available to PDO until
the statement is executed, portable applications should call this
function after PDOStatement::execute().
However, to be able to bind a LOB column as a stream when using the
PgSQL driver, applications should call this method before calling
PDOStatement::execute(), otherwise the large object OID will be returned
as an integer.
Parameters
column
Number of the column (1-indexed) or name of the column in the
result set. If using the column name, be aware that the name
should match the case of the column, as returned by the driver.
param
Name of the PHP variable to which the column will be bound.
type
Data type of the parameter, specified by the PDO::PARAM_*
constants.
maxlen
A hint for pre-allocation.
driverdata
Optional parameter(s) for the driver.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Binding result set output to PHP variables
Binding columns in the result set to PHP variables is an effective way to
make the data contained in each row immediately available to your
application. The following example demonstrates how PDO allows you to bind
and retrieve columns with a variety of options and with intelligent
defaults.
prepare($sql);
$stmt->execute();
/* Bind by column number */
$stmt->bindColumn(1, $name);
$stmt->bindColumn(2, $colour);
/* Bind by column name */
$stmt->bindColumn('calories', $cals);
while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
$data = $name . "\t" . $colour . "\t" . $cals . "\n";
print $data;
}
}
catch (PDOException $e) {
print $e->getMessage();
}
}
readData($dbh);
?>
The above example will output:
apple red 150
banana yellow 175
kiwi green 75
orange orange 150
mango red 200
strawberry red 25
See Also
* PDOStatement::execute() - Executes a prepared statement
* PDOStatement::fetch() - Fetches the next row from a result set
* PDOStatement::fetchAll() - Returns an array containing all of the
result set rows
* PDOStatement::fetchColumn() - Returns a single column from the next
row of a result set
----------------------------------------------------------------------
----------------------------------------------------------------------
PDOStatement->bindParam
(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
PDOStatement->bindParam - Binds a parameter to the specified variable name
Description
bool PDOStatement::bindParam ( mixed $parameter , mixed &$variable [, int
$data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )
Binds a PHP variable to a corresponding named or question mark placeholder
in the SQL statement that was use to prepare the statement. Unlike
PDOStatement::bindValue(), the variable is bound as a reference and will
only be evaluated at the time that PDOStatement::execute() is called.
Most parameters are input parameters, that is, parameters that are used in
a read-only fashion to build up the query. Some drivers support the
invocation of stored procedures that return data as output parameters, and
some also as input/output parameters that both send in data and are
updated to receive it.
Parameters
parameter
Parameter identifier. For a prepared statement using named
placeholders, this will be a parameter name of the form :name. For
a prepared statement using question mark placeholders, this will
be the 1-indexed position of the parameter.
variable
Name of the PHP variable to bind to the SQL statement parameter.
data_type
Explicit data type for the parameter using the PDO::PARAM_*
constants. To return an INOUT parameter from a stored procedure,
use the bitwise OR operator to set the PDO::PARAM_INPUT_OUTPUT
bits for the data_type parameter.
length
Length of the data type. To indicate that a parameter is an OUT
parameter from a stored procedure, you must explicitly set the
length.
driver_options
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Execute a prepared statement with named placeholders
prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>
Example #2 Execute a prepared statement with question mark placeholders
prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>
Example #3 Call a stored procedure with an INOUT parameter
prepare('CALL puree_fruit(?)');
$sth->bindParam(1, $colour, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 12);
$sth->execute();
print("After pureeing fruit, the colour is: $colour");
?>
See Also
* PDO::prepare() - Prepares a statement for execution and returns a
statement object
* PDOStatement::execute() - Executes a prepared statement
* PDOStatement::bindValue() - Binds a value to a parameter
----------------------------------------------------------------------
----------------------------------------------------------------------
PDOStatement->bindValue
(PHP 5 >= 5.1.0, PECL pdo >= 1.0.0)
PDOStatement->bindValue - Binds a value to a parameter
Description
bool PDOStatement::bindValue ( mixed $parameter , mixed $value [, int
$data_type = PDO::PARAM_STR ] )
Binds a value to a corresponding named or question mark placeholder in the
SQL statement that was used to prepare the statement.
Parameters
parameter
Parameter identifier. For a prepared statement using named
placeholders, this will be a parameter name of the form :name. For
a prepared statement using question mark placeholders, this will
be the 1-indexed position of the parameter.
value
The value to bind to the parameter.
data_type
Explicit data type for the parameter using the PDO::PARAM_*
constants.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Execute a prepared statement with named placeholders
prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindValue(':calories', $calories, PDO::PARAM_INT);
$sth->bindValue(':colour', $colour, PDO::PARAM_STR);
$sth->execute();
?>
Example #2 Execute a prepared statement with question mark placeholders
prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->bindValue(1, $calories, PDO::PARAM_INT);
$sth->bindValue(2, $colour, PDO::PARAM_STR);
$sth->execute();
?>
See Also
* PDO::prepare() - Prepares a statement for execution and returns a
statement object
* PDOStatement::execute() - Executes a prepared statement
* PDOStatement::bindParam() - Binds a parameter to the specified
variable name
----------------------------------------------------------------------
----------------------------------------------------------------------
PDOStatement->closeCursor
(PHP 5 >= 5.1.0, PECL pdo >= 0.9.0)
PDOStatement->closeCursor - Closes the cursor, enabling the statement to
be executed again.
Description
bool PDOStatement::closeCursor ( void )
PDOStatement::closeCursor() frees up the connection to the server so that
other SQL statements may be issued, but leaves the statement in a state
that enables it to be executed again.
This method is useful for database drivers that do not support executing a
PDOStatement object when a previously executed PDOStatement object still
has unfetched rows. If your database driver suffers from this limitation,
the problem may manifest itself in an out-of-sequence error.
PDOStatement::closeCursor() is implemented either as an optional driver
specific method (allowing for maximum efficiency), or as the generic PDO
fallback if no driver specific function is installed. The PDO generic
fallback is semantically the same as writing the following code in your
PHP script:
fetch())
;
if (!$stmt->nextRowset())
break;
} while (true);
?>
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 A PDOStatement::closeCursor() example
In the following example, the $stmt PDOStatement object returns multiple
rows but the application fetches only the first row, leaving the
PDOStatement object in a state of having unfetched rows. To ensure that
the application will work with all database drivers, the author inserts a
call to PDOStatement::closeCursor() on $stmt before executing the
$otherStmt PDOStatement object.
prepare('SELECT foo FROM bar');
/* Create a second PDOStatement object */
$otherStmt = $dbh->prepare('SELECT foobaz FROM foobar');
/* Execute the first statement */
$stmt->execute();
/* Fetch only the first row from the results */
$stmt->fetch();
/* The following call to closeCursor() may be required by some drivers */
$stmt->closeCursor();
/* Now we can execute the second statement */
$otherStmt->execute();
?>
See Also
* PDOStatement::execute() - Executes a prepared statement
----------------------------------------------------------------------
----------------------------------------------------------------------
PDOStatement->columnCount
(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)
PDOStatement->columnCount - Returns the number of columns in the result
set
Description
int PDOStatement::columnCount ( void )
Use PDOStatement::columnCount() to return the number of columns in the
result set represented by the PDOStatement object.
If the PDOStatement object was returned from PDO::query(), the column
count is immediately available.
If the PDOStatement object was returned from PDO::prepare(), an accurate
column count will not be available until you invoke
PDOStatement::execute().
Return Values
Returns the number of columns in the result set represented by the
PDOStatement object. If there is no result set,
PDOStatement::columnCount() returns 0.
Examples
Example #1 Counting columns
This example demonstrates how PDOStatement::columnCount() operates with
and without a result set.
prepare("SELECT name, colour FROM fruit");
/* Count the number of columns in the (non-existent) result set */
$colcount = $sth->columnCount();
print("Before execute(), result set has $colcount columns (should be 0)\n");
$sth->execute();
/* Count the number of columns in the result set */
$colcount = $sth->columnCount();
print("After execute(), result set has $colcount columns (should be 2)\n");
?>
The above example will output:
Before execute(), result set has 0 columns (should be 0)
After execute(), result set has 2 columns (should be 2)
See Also
* PDO::prepare() - Prepares a statement for execution and returns a
statement object
* PDOStatement::execute() - Executes a prepared statement
* PDOStatement::rowCount() - Returns the number of rows affected by the
last SQL statement
----------------------------------------------------------------------
----------------------------------------------------------------------
PDOStatement->debugDumpParams
(PHP 5 >= 5.1.0, PECL pdo >= 0.9.0)
PDOStatement->debugDumpParams - Dump an SQL prepared command
Description
bool PDOStatement::debugDumpParams ( void )
Dumps the informations contained by a prepared statement directly on the
output. It will provide the SQL query in use, the number of parameters
used (Params), the list of parameters, with their name, type (paramtype)
as an integer, their key name or position, the value, and the position in
the query (if this is supported by the PDO driver, otherwise, it will be
-1).
This is a debug function, which dump directly the data on the normal
output.
Tip
As with anything that outputs its result directly to the browser, the
output-control functions can be used to capture the output of this
function, and save it in a string (for example).
This will only dumps the parameters in the statement at the moment of the
dump. Extra parameters are not stored in the statement, and not displayed.
Return Values
No value is returned.
Examples
Example #1 PDOStatement::debugDumpParams() example with named parameters
prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindValue(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
$sth->debugDumpParams();
?>
The above example will output:
SQL: [96] SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour
Params: 2
Key: Name: [9] :calories
paramno=-1
name=[9] ":calories"
is_param=1
param_type=1
Key: Name: [7] :colour
paramno=-1
name=[7] ":colour"
is_param=1
param_type=2
Example #2 PDOStatement::debugDumpParams() example with unnamed parameters
prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindValue(2, $colour, PDO::PARAM_STR);
$sth->execute();
$sth->debugDumpParams();
?>
The above example will output:
SQL: [82] SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?
Params: 2
Key: Position #0:
paramno=0
name=[0] ""
is_param=1
param_type=1
Key: Position #1:
paramno=1
name=[0] ""
is_param=1
param_type=2
See Also
* PDO::prepare() - Prepares a statement for execution and returns a
statement object
* PDOStatement::bindParam() - Binds a parameter to the specified
variable name
* PDOStatement::bindValue() - Binds a value to a parameter
----------------------------------------------------------------------
----------------------------------------------------------------------
PDOStatement->errorCode
(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
PDOStatement->errorCode - Fetch the SQLSTATE associated with the last
operation on the statement handle
Description
string PDOStatement::errorCode ( void )
Return Values
Identical to PDO::errorCode(), except that PDOStatement::errorCode() only
retrieves error codes for operations performed with PDOStatement objects.
Examples
Example #1 Retrieving an SQLSTATE code
prepare('SELECT skull FROM bones');
$err->execute();
echo "\nPDOStatement::errorCode(): ";
print $err->errorCode();
?>
The above example will output:
PDOStatement::errorCode(): 42S02
See Also
* PDO::errorCode() - Fetch the SQLSTATE associated with the last
operation on the database handle
* PDO::errorInfo() - Fetch extended error information associated with
the last operation on the database handle
* PDOStatement::errorInfo() - Fetch extended error information
associated with the last operation on the statement handle
----------------------------------------------------------------------
----------------------------------------------------------------------
PDOStatement->errorInfo
(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
PDOStatement->errorInfo - Fetch extended error information associated with
the last operation on the statement handle
Description
array PDOStatement::errorInfo ( void )
Return Values
PDOStatement::errorInfo() returns an array of error information about the
last operation performed by this statement handle. The array consists of
the following fields:
Element Information
0 SQLSTATE error code (a five characters alphanumeric identifier
defined in the ANSI SQL standard).
1 Driver specific error code.
2 Driver specific error message.
Examples
Example #1 Displaying errorInfo() fields for a PDO_ODBC connection to a
DB2 database
prepare('SELECT skull FROM bones');
$sth->execute();
echo "\nPDOStatement::errorInfo():\n";
$arr = $sth->errorInfo();
print_r($arr);
?>
The above example will output:
PDOStatement::errorInfo():
Array
(
[0] => 42S02
[1] => -204
[2] => [IBM][CLI Driver][DB2/LINUX] SQL0204N "DANIELS.BONES" is an undefined name. SQLSTATE=42704
)
See Also
* PDO::errorCode() - Fetch the SQLSTATE associated with the last
operation on the database handle
* PDO::errorInfo() - Fetch extended error information associated with
the last operation on the database handle
* PDOStatement::errorCode() - Fetch the SQLSTATE associated with the
last operation on the statement handle
----------------------------------------------------------------------
----------------------------------------------------------------------
PDOStatement->execute
(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
PDOStatement->execute - Executes a prepared statement
Description
bool PDOStatement::execute ([ array $input_parameters ] )
Execute the prepared statement. If the prepared statement included
parameter markers, you must either:
* call PDOStatement::bindParam() to bind PHP variables to the parameter
markers: bound variables pass their value as input and receive the
output value, if any, of their associated parameter markers
* or pass an array of input-only parameter values
Parameters
input_parameters
An array of values with as many elements as there are bound
parameters in the SQL statement being executed. All values are
treated as PDO::PARAM_STR.
You cannot bind multiple values to a single parameter; for
example, you cannot bind two values to a single named parameter in
an IN() clause.
You cannot bind more values than specified; if more keys exist in
input_parameters than in the SQL specified in the PDO::prepare(),
then the statement will fail and an error is emitted.
Return Values
Returns TRUE on success or FALSE on failure.
Changelog
Version Description
5.2.0 The keys from input_parameters must match the ones declared in the
SQL. Before PHP 5.2.0 this was silently ignored.
Examples
Example #1 Execute a prepared statement with bound variables
prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>
Example #2 Execute a prepared statement with an array of insert values
(named parameters)
prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->execute(array(':calories' => $calories, ':colour' => $colour));
?>
Example #3 Execute a prepared statement with an array of insert values
(placeholders)
prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->execute(array($calories, $colour));
?>
Example #4 Execute a prepared statement with question mark placeholders
prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>
Notes
Note:
Some drivers require to close cursor before executing next statement.
See Also
* PDO::prepare() - Prepares a statement for execution and returns a
statement object
* PDOStatement::bindParam() - Binds a parameter to the specified
variable name
* PDOStatement::fetch() - Fetches the next row from a result set
* PDOStatement::fetchAll() - Returns an array containing all of the
result set rows
* PDOStatement::fetchColumn() - Returns a single column from the next
row of a result set
----------------------------------------------------------------------
----------------------------------------------------------------------
PDOStatement->fetch
(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
PDOStatement->fetch - Fetches the next row from a result set
Description
mixed PDOStatement::fetch ([ int $fetch_style = PDO::FETCH_BOTH [, int
$cursor_orientation = PDO::FETCH_ORI_NEXT [, int $cursor_offset = 0 ]]] )
Fetches a row from a result set associated with a PDOStatement object. The
fetch_style parameter determines how PDO returns the row.
Parameters
fetch_style
Controls how the next row will be returned to the caller. This
value must be one of the PDO::FETCH_* constants, defaulting to
PDO::FETCH_BOTH.
* PDO::FETCH_ASSOC: returns an array indexed by column name as
returned in your result set
* PDO::FETCH_BOTH (default): returns an array indexed by both
column name and 0-indexed column number as returned in your
result set
* PDO::FETCH_BOUND: returns TRUE and assigns the values of the
columns in your result set to the PHP variables to which they
were bound with the PDOStatement::bindColumn() method
* PDO::FETCH_CLASS: returns a new instance of the requested
class, mapping the columns of the result set to named
properties in the class. If fetch_style includes
PDO::FETCH_CLASSTYPE (e.g. PDO::FETCH_CLASS |
PDO::FETCH_CLASSTYPE) then the name of the class is
determined from a value of the first column.
* PDO::FETCH_INTO: updates an existing instance of the
requested class, mapping the columns of the result set to
named properties in the class
* PDO::FETCH_LAZY: combines PDO::FETCH_BOTH and PDO::FETCH_OBJ,
creating the object variable names as they are accessed
* PDO::FETCH_NUM: returns an array indexed by column number as
returned in your result set, starting at column 0
* PDO::FETCH_OBJ: returns an anonymous object with property
names that correspond to the column names returned in your
result set
cursor_orientation
For a PDOStatement object representing a scrollable cursor, this
value determines which row will be returned to the caller. This
value must be one of the PDO::FETCH_ORI_* constants, defaulting to
PDO::FETCH_ORI_NEXT. To request a scrollable cursor for your
PDOStatement object, you must set the PDO::ATTR_CURSOR attribute
to PDO::CURSOR_SCROLL when you prepare the SQL statement with
PDO::prepare().
offset
For a PDOStatement object representing a scrollable cursor for
which the cursor_orientation parameter is set to
PDO::FETCH_ORI_ABS, this value specifies the absolute number of
the row in the result set that shall be fetched.
For a PDOStatement object representing a scrollable cursor for
which the cursor_orientation parameter is set to
PDO::FETCH_ORI_REL, this value specifies the row to fetch relative
to the cursor position before PDOStatement::fetch() was called.
Return Values
The return value of this function on success depends on the fetch type. In
all cases, FALSE is returned on failure.
Examples
Example #1 Fetching rows using different fetch styles
prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Exercise PDOStatement::fetch styles */
print("PDO::FETCH_ASSOC: ");
print("Return next row as an array indexed by column name\n");
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r($result);
print("\n");
print("PDO::FETCH_BOTH: ");
print("Return next row as an array indexed by both column name and number\n");
$result = $sth->fetch(PDO::FETCH_BOTH);
print_r($result);
print("\n");
print("PDO::FETCH_LAZY: ");
print("Return next row as an anonymous object with column names as properties\n");
$result = $sth->fetch(PDO::FETCH_LAZY);
print_r($result);
print("\n");
print("PDO::FETCH_OBJ: ");
print("Return next row as an anonymous object with column names as properties\n");
$result = $sth->fetch(PDO::FETCH_OBJ);
print $result->NAME;
print("\n");
?>
The above example will output:
PDO::FETCH_ASSOC: Return next row as an array indexed by column name
Array
(
[NAME] => apple
[COLOUR] => red
)
PDO::FETCH_BOTH: Return next row as an array indexed by both column name and number
Array
(
[NAME] => banana
[0] => banana
[COLOUR] => yellow
[1] => yellow
)
PDO::FETCH_LAZY: Return next row as an anonymous object with column names as properties
PDORow Object
(
[NAME] => orange
[COLOUR] => orange
)
PDO::FETCH_OBJ: Return next row as an anonymous object with column names as properties
kiwi
Example #2 Fetching rows with a scrollable cursor
prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) {
$data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
print $data;
}
$stmt = null;
}
catch (PDOException $e) {
print $e->getMessage();
}
}
function readDataBackwards($dbh) {
$sql = 'SELECT hand, won, bet FROM mynumbers ORDER BY bet';
try {
$stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_LAST);
do {
$data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
print $data;
} while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_PRIOR));
$stmt = null;
}
catch (PDOException $e) {
print $e->getMessage();
}
}
print "Reading forwards:\n";
readDataForwards($conn);
print "Reading backwards:\n";
readDataBackwards($conn);
?>
The above example will output:
Reading forwards:
21 10 5
16 0 5
19 20 10
Reading backwards:
19 20 10
16 0 5
21 10 5
See Also
* PDO::prepare() - Prepares a statement for execution and returns a
statement object
* PDOStatement::execute() - Executes a prepared statement
* PDOStatement::fetchAll() - Returns an array containing all of the
result set rows
* PDOStatement::fetchColumn() - Returns a single column from the next
row of a result set
* PDOStatement::fetchObject() - Fetches the next row and returns it as
an object.
* PDOStatement::setFetchMode() - Set the default fetch mode for this
statement
----------------------------------------------------------------------
----------------------------------------------------------------------
PDOStatement->fetchAll
(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
PDOStatement->fetchAll - Returns an array containing all of the result set
rows
Description
array PDOStatement::fetchAll ([ int $fetch_style = PDO::FETCH_BOTH [,
mixed $fetch_argument [, array $ctor_args = array() ]]] )
Parameters
fetch_style
Controls the contents of the returned array as documented in
PDOStatement::fetch().
To return an array consisting of all values of a single column
from the result set, specify PDO::FETCH_COLUMN. You can specify
which column you want with the column-index parameter.
To fetch only the unique values of a single column from the result
set, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_UNIQUE.
To return an associative array grouped by the values of a
specified column, bitwise-OR PDO::FETCH_COLUMN with
PDO::FETCH_GROUP.
fetch_argument
This argument have a different meaning depending on the value of
the fetch_style parameter:
* PDO::FETCH_COLUMN: Returns the indicated 0-indexed column.
* PDO::FETCH_CLASS: Returns instances of the specified class,
mapping the columns of each row to named properties in the
class.
* PDO::FETCH_FUNC: Returns the results of calling the specified
function, using each row's columns as parameters in the call.
ctor_args
Arguments of custom class constructor when the fetch_style
parameter is PDO::FETCH_CLASS.
Return Values
PDOStatement::fetchAll() returns an array containing all of the remaining
rows in the result set. The array represents each row as either an array
of column values or an object with properties corresponding to each column
name.
Using this method to fetch large result sets will result in a heavy demand
on system and possibly network resources. Rather than retrieving all of
the data and manipulating it in PHP, consider using the database server to
manipulate the result sets. For example, use the WHERE and ORDER BY
clauses in SQL to restrict results before retrieving and processing them
with PHP.
Examples
Example #1 Fetch all remaining rows in a result set
prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>
The above example will output something similar to:
Fetch all of the remaining rows in the result set:
Array
(
[0] => Array
(
[NAME] => pear
[0] => pear
[COLOUR] => green
[1] => green
)
[1] => Array
(
[NAME] => watermelon
[0] => watermelon
[COLOUR] => pink
[1] => pink
)
)
Example #2 Fetching all values of a single column from a result set
The following example demonstrates how to return all of the values of a
single column from a result set, even though the SQL statement itself may
return multiple columns per row.
prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the values of the first column */
$result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
var_dump($result);
?>
The above example will output something similar to:
Array(3)
(
[0] =>
string(5) => apple
[1] =>
string(4) => pear
[2] =>
string(10) => watermelon
)
Example #3 Grouping all values by a single column
The following example demonstrates how to return an associative array
grouped by the values of the specified column in the result set. The array
contains three keys: values apple and pear are returned as arrays that
contain two different colours, while watermelon is returned as an array
that contains only one colour.
prepare("INSERT INTO fruit(name, colour) VALUES (?, ?)");
$insert->execute(array('apple', 'green'));
$insert->execute(array('pear', 'yellow'));
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Group values by the first column */
var_dump($sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP));
?>
The above example will output something similar to:
array(3) {
["apple"]=>
array(2) {
[0]=>
string(5) "green"
[1]=>
string(3) "red"
}
["pear"]=>
array(2) {
[0]=>
string(5) "green"
[1]=>
string(6) "yellow"
}
["watermelon"]=>
array(1) {
[0]=>
string(5) "green"
}
}
Example #4 Instantiating a class for each result
The following example demonstrates the behaviour of the PDO::FETCH_CLASS
fetch style.
prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_CLASS, "fruit");
var_dump($result);
?>
The above example will output something similar to:
array(3) {
[0]=>
object(fruit)#1 (2) {
["name"]=>
string(5) "apple"
["colour"]=>
string(5) "green"
}
[1]=>
object(fruit)#2 (2) {
["name"]=>
string(4) "pear"
["colour"]=>
string(6) "yellow"
}
[2]=>
object(fruit)#3 (2) {
["name"]=>
string(10) "watermelon"
["colour"]=>
string(4) "pink"
}
}
Example #5 Calling a function for each result
The following example demonstrates the behaviour of the PDO::FETCH_FUNC
fetch style.
prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_FUNC, "fruit");
var_dump($result);
?>
The above example will output something similar to:
array(3) {
[0]=>
string(12) "apple: green"
[1]=>
string(12) "pear: yellow"
[2]=>
string(16) "watermelon: pink"
}
See Also
* PDO::query() - Executes an SQL statement, returning a result set as a
PDOStatement object
* PDOStatement::fetch() - Fetches the next row from a result set
* PDOStatement::fetchColumn() - Returns a single column from the next
row of a result set
* PDO::prepare() - Prepares a statement for execution and returns a
statement object
* PDOStatement::setFetchMode() - Set the default fetch mode for this
statement
----------------------------------------------------------------------
----------------------------------------------------------------------
PDOStatement->fetchColumn
(PHP 5 >= 5.1.0, PECL pdo >= 0.9.0)
PDOStatement->fetchColumn - Returns a single column from the next row of a
result set
Description
string PDOStatement::fetchColumn ([ int $column_number = 0 ] )
Returns a single column from the next row of a result set or FALSE if
there are no more rows.
Parameters
column_number
0-indexed number of the column you wish to retrieve from the row.
If no value is supplied, PDOStatement::fetchColumn() fetches the
first column.
Return Values
PDOStatement::fetchColumn() returns a single column in the next row of a
result set.
Warning
There is no way to return another column from the same row if you use
PDOStatement::fetchColumn() to retrieve data.
Examples
Example #1 Return first column of the next row
prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch the first column from the next row in the result set */
print("Fetch the first column from the next row in the result set:\n");
$result = $sth->fetchColumn();
print("name = $result\n");
print("Fetch the second column from the next row in the result set:\n");
$result = $sth->fetchColumn(1);
print("colour = $result\n");
?>
The above example will output:
Fetch the first column from the next row in the result set:
name = lemon
Fetch the second column from the next row in the result set:
colour = red
See Also
* PDO::query() - Executes an SQL statement, returning a result set as a
PDOStatement object
* PDOStatement::fetch() - Fetches the next row from a result set
* PDOStatement::fetchAll() - Returns an array containing all of the
result set rows
* PDO::prepare() - Prepares a statement for execution and returns a
statement object
* PDOStatement::setFetchMode() - Set the default fetch mode for this
statement
----------------------------------------------------------------------
----------------------------------------------------------------------
PDOStatement->fetchObject
(PHP 5 >= 5.1.0, PECL pdo >= 0.2.4)
PDOStatement->fetchObject - Fetches the next row and returns it as an
object.
Description
mixed PDOStatement::fetchObject ([ string $class_name = "stdClass" [,
array $ctor_args ]] )
Fetches the next row and returns it as an object. This function is an
alternative to PDOStatement::fetch() with PDO::FETCH_CLASS or
PDO::FETCH_OBJ style.
Parameters
class_name
Name of the created class.
ctor_args
Elements of this array are passed to the constructor.
Return Values
Returns an instance of the required class with property names that
correspond to the column names or FALSE on failure.
See Also
* PDOStatement::fetch() - Fetches the next row from a result set
----------------------------------------------------------------------
----------------------------------------------------------------------
PDOStatement->getAttribute
(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)
PDOStatement->getAttribute - Retrieve a statement attribute
Description
mixed PDOStatement::getAttribute ( int $attribute )
Gets an attribute of the statement. Currently, no generic attributes exist
but only driver specific:
* PDO::ATTR_CURSOR_NAME (Firebird and ODBC specific): Get the name of
cursor for UPDATE ... WHERE CURRENT OF.
Return Values
Returns the attribute value.
See Also
* PDO::getAttribute() - Retrieve a database connection attribute
* PDO::setAttribute() - Set an attribute
* PDOStatement::setAttribute() - Set a statement attribute
----------------------------------------------------------------------
----------------------------------------------------------------------
PDOStatement->getColumnMeta
(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)
PDOStatement->getColumnMeta - Returns metadata for a column in a result
set
Description
array PDOStatement::getColumnMeta ( int $column )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Retrieves the metadata for a 0-indexed column in a result set as an
associative array.
Warning
Not all PDO drivers support PDOStatement::getColumnMeta().
Parameters
column
The 0-indexed column in the result set.
Return Values
Returns an associative array containing the following values representing
the metadata for a single column:
Column metadata
Name Value
native_type The PHP native type used to represent the column value.
The SQL type used to represent the column value in the
driver:decl_type database. If the column in the result set is the result
of a function, this value is not returned by
PDOStatement::getColumnMeta().
flags Any flags set for this column.
name The name of this column as returned by the database.
table The name of this column's table as returned by the
database.
len The length of this column. Normally -1 for types other
than floating point decimals.
precision The numeric precision of this column. Normally 0 for
types other than floating point decimals.
pdo_type The type of this column as represented by the
PDO::PARAM_* constants.
Returns FALSE if the requested column does not exist in the result set, or
if no result set exists.
Changelog
Version Description
5.2.3 table field
Examples
Example #1 Retrieving column metadata
The following example shows the results of retrieving the metadata for a
single column generated by a function (COUNT) in a PDO_SQLITE driver.
query('SELECT COUNT(*) FROM fruit');
$meta = $select->getColumnMeta(0);
var_dump($meta);
?>
The above example will output:
array(6) {
["native_type"]=>
string(7) "integer"
["flags"]=>
array(0) {
}
["name"]=>
string(8) "COUNT(*)"
["len"]=>
int(-1)
["precision"]=>
int(0)
["pdo_type"]=>
int(2)
}
See Also
* PDOStatement::columnCount() - Returns the number of columns in the
result set
* PDOStatement::rowCount() - Returns the number of rows affected by the
last SQL statement
----------------------------------------------------------------------
----------------------------------------------------------------------
PDOStatement->nextRowset
(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)
PDOStatement->nextRowset - Advances to the next rowset in a multi-rowset
statement handle
Description
bool PDOStatement::nextRowset ( void )
Some database servers support stored procedures that return more than one
rowset (also known as a result set). PDOStatement::nextRowset() enables
you to access the second and subsequent rowsets associated with a
PDOStatement object. Each rowset can have a different set of columns from
the preceding rowset.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Fetching multiple rowsets returned from a stored procedure
The following example shows how to call a stored procedure,
MULTIPLE_ROWSETS, that returns three rowsets. We use a do / while loop to
loop over the PDOStatement::nextRowset() method, which returns false and
terminates the loop when no more rowsets can be returned.
query($sql);
$i = 1;
do {
$rowset = $stmt->fetchAll(PDO::FETCH_NUM);
if ($rowset) {
printResultSet($rowset, $i);
}
$i++;
} while ($stmt->nextRowset());
function printResultSet(&$rowset, $i) {
print "Result set $i:\n";
foreach ($rowset as $row) {
foreach ($row as $col) {
print $col . "\t";
}
print "\n";
}
print "\n";
}
?>
The above example will output:
Result set 1:
apple red
banana yellow
Result set 2:
orange orange 150
banana yellow 175
Result set 3:
lime green
apple red
banana yellow
See Also
* PDOStatement::columnCount() - Returns the number of columns in the
result set
* PDOStatement::execute() - Executes a prepared statement
* PDOStatement::getColumnMeta() - Returns metadata for a column in a
result set
* PDO::query() - Executes an SQL statement, returning a result set as a
PDOStatement object
----------------------------------------------------------------------
----------------------------------------------------------------------
PDOStatement->rowCount
(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
PDOStatement->rowCount - Returns the number of rows affected by the last
SQL statement
Description
int PDOStatement::rowCount ( void )
PDOStatement::rowCount() returns the number of rows affected by the last
DELETE, INSERT, or UPDATE statement executed by the corresponding
PDOStatement object.
If the last SQL statement executed by the associated PDOStatement was a
SELECT statement, some databases may return the number of rows returned by
that statement. However, this behaviour is not guaranteed for all
databases and should not be relied on for portable applications.
Return Values
Returns the number of rows.
Examples
Example #1 Return the number of deleted rows
PDOStatement::rowCount() returns the number of rows affected by a DELETE,
INSERT, or UPDATE statement.
prepare('DELETE FROM fruit');
$del->execute();
/* Return number of rows that were deleted */
print("Return number of rows that were deleted:\n");
$count = $del->rowCount();
print("Deleted $count rows.\n");
?>
The above example will output:
Return number of rows that were deleted:
Deleted 9 rows.
Example #2 Counting rows returned by a SELECT statement
For most databases, PDOStatement::rowCount() does not return the number of
rows affected by a SELECT statement. Instead, use PDO::query() to issue a
SELECT COUNT(*) statement with the same predicates as your intended SELECT
statement, then use PDOStatement::fetchColumn() to retrieve the number of
rows that will be returned. Your application can then perform the correct
action.
100";
if ($res = $conn->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* Issue the real SELECT statement and work with the results */
$sql = "SELECT name FROM fruit WHERE calories > 100";
foreach ($conn->query($sql) as $row) {
print "Name: " . $row['NAME'] . "\n";
}
}
/* No rows matched -- do something else */
else {
print "No rows matched the query.";
}
}
$res = null;
$conn = null;
?>
The above example will output:
apple
banana
orange
pear
See Also
* PDOStatement::columnCount() - Returns the number of columns in the
result set
* PDOStatement::fetchColumn() - Returns a single column from the next
row of a result set
* PDO::query() - Executes an SQL statement, returning a result set as a
PDOStatement object
----------------------------------------------------------------------
----------------------------------------------------------------------
PDOStatement->setAttribute
(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)
PDOStatement->setAttribute - Set a statement attribute
Description
bool PDOStatement::setAttribute ( int $attribute , mixed $value )
Sets an attribute on the statement. Currently, no generic attributes are
set but only driver specific:
* PDO::ATTR_CURSOR_NAME (Firebird and ODBC specific): Set the name of
cursor for UPDATE ... WHERE CURRENT OF.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* PDO::getAttribute() - Retrieve a database connection attribute
* PDO::setAttribute() - Set an attribute
* PDOStatement::getAttribute() - Retrieve a statement attribute
----------------------------------------------------------------------
----------------------------------------------------------------------
PDOStatement->setFetchMode
(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)
PDOStatement->setFetchMode - Set the default fetch mode for this statement
Description
bool PDOStatement::setFetchMode ( int $mode )
bool PDOStatement::setFetchMode ( int $PDO::FETCH_COLUMN , int $colno )
bool PDOStatement::setFetchMode ( int $PDO::FETCH_CLASS , string
$classname , array $ctorargs )
bool PDOStatement::setFetchMode ( int $PDO::FETCH_INTO , object $object )
Parameters
mode
The fetch mode must be one of the PDO::FETCH_* constants.
colno
Column number.
classname
Class name.
ctorargs
Constructor arguments.
object
Object.
Return Values
Returns 1 on success or FALSE on failure.
Examples
Example #1 Setting the fetch mode
The following example demonstrates how PDOStatement::setFetchMode()
changes the default fetch mode for a PDOStatement object.
query($sql);
$result = $stmt->setFetchMode(PDO::FETCH_NUM);
while ($row = $stmt->fetch()) {
print $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
}
}
catch (PDOException $e) {
print $e->getMessage();
}
?>
The above example will output:
apple red 150
banana yellow 250
orange orange 300
kiwi brown 75
lemon yellow 25
pear green 150
watermelon pink 90
----------------------------------------------------------------------
Table of Contents
* PDOStatement->bindColumn - Bind a column to a PHP variable
* PDOStatement->bindParam - Binds a parameter to the specified variable
name
* PDOStatement->bindValue - Binds a value to a parameter
* PDOStatement->closeCursor - Closes the cursor, enabling the statement
to be executed again.
* PDOStatement->columnCount - Returns the number of columns in the
result set
* PDOStatement->debugDumpParams - Dump an SQL prepared command
* PDOStatement->errorCode - Fetch the SQLSTATE associated with the last
operation on the statement handle
* PDOStatement->errorInfo - Fetch extended error information associated
with the last operation on the statement handle
* PDOStatement->execute - Executes a prepared statement
* PDOStatement->fetch - Fetches the next row from a result set
* PDOStatement->fetchAll - Returns an array containing all of the result
set rows
* PDOStatement->fetchColumn - Returns a single column from the next row
of a result set
* PDOStatement->fetchObject - Fetches the next row and returns it as an
object.
* PDOStatement->getAttribute - Retrieve a statement attribute
* PDOStatement->getColumnMeta - Returns metadata for a column in a
result set
* PDOStatement->nextRowset - Advances to the next rowset in a
multi-rowset statement handle
* PDOStatement->rowCount - Returns the number of rows affected by the
last SQL statement
* PDOStatement->setAttribute - Set a statement attribute
* PDOStatement->setFetchMode - Set the default fetch mode for this
statement
----------------------------------------------------------------------
----------------------------------------------------------------------
The PDOException class
Introduction
Represents an error raised by PDO. You should not throw a PDOException
from your own code. See Exceptions for more information about Exceptions
in PHP.
Class synopsis
PDOException extends RuntimeException {
/* Properties */
public array $PDOException->errorInfo ;
protected string $message ;
protected string $code ;
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}
Properties
errorInfo
Corresponds to PDO::errorInfo() or PDOStatement::errorInfo()
message
Textual error message. Exception::getMessage() to access it.
code
SQLSTATE error code. Use Exception::getCode() to access it.
----------------------------------------------------------------------
----------------------------------------------------------------------
PDO Drivers
Table of Contents
* CUBRID (PDO)
* MS SQL Server (PDO)
* Firebird/Interbase (PDO)
* IBM (PDO)
* Informix (PDO)
* MySQL (PDO)
* MS SQL Server (PDO)
* Oracle (PDO)
* ODBC and DB2 (PDO)
* PostgreSQL (PDO)
* SQLite (PDO)
* 4D (PDO)
The following drivers currently implement the PDO interface:
Driver name Supported databases
PDO_CUBRID Cubrid
PDO_DBLIB FreeTDS / Microsoft SQL Server / Sybase
PDO_FIREBIRD Firebird/Interbase 6
PDO_IBM IBM DB2
PDO_INFORMIX IBM Informix Dynamic Server
PDO_MYSQL MySQL 3.x/4.x/5.x
PDO_OCI Oracle Call Interface
PDO_ODBC ODBC v3 (IBM DB2, unixODBC and win32 ODBC)
PDO_PGSQL PostgreSQL
PDO_SQLITE SQLite 3 and SQLite 2
PDO_SQLSRV Microsoft SQL Server / SQL Azure
PDO_4D 4D
----------------------------------------------------------------------
CUBRID Functions (PDO_CUBRID)
Introduction
PDO_CUBRID is a driver that implements the PHP Data Objects (PDO)
interface to enable access from PHP to CUBRID databases.
Note:
Current version of PDO_CUBRID doesn't support persistent connection now.
Installation
To build the PDO_CUBRID extension, the CUBRID DBMS must be installed on
the same system as PHP. PDO_CUBRID is a >> PECL extension, so follow the
instructions in Installation of PECL extensions to install the PDO_CUBRID
extension. Issue the configure command to point to the location of your
CUBRID base dir as follows:
$ ./configure --with-pdo-cubrid=/path/to/CUBRID[,shared]
The configure command defaults to the value of the CUBRID environment
variable.
A DLL for this PECL extension is currently unavailable. See also the
building on Windows section. Detailed information about installation on
Linux and Windows manually, please read build-guide.html in PECL package
CUBRID for reference.
Features
PDO_CUBRID Features
Feature Description
Scrollable PDO_CUBRID supports scrollable cursors. The default cursor type is forward
cursors only, and you can use parameter driver_options in PDO::prepare() to change
cursor type.
Timeout PDO_CUBRID supports sql statement execution timeout setting; You can use
PDO::setAttribute() to set timeout value.
PDO_CUBRID supports both autocommit_mode and transaction, and
autocommit_mode is disabled by default. You can use PDO::setAttribute() to
change its state.
Autocommit_mode
and Transaction If you use PDO::beginTransaction() to begin a transaction, it will disable
autocommit_mode automatically and restore it after PDO::commit() or
PDO::rollBack(). Note that before disabling the autocommit_mode, any pending
work is automatically committed.
Multiple SQL PDO_CUBRID supports Multiple SQL statements. Multiple SQL statements are
Statements separated by semicolons (;)
Schema PDO_CUBRID implements a function PDO::cubrid_schema() to get schema
Information information.
PDO_CUBRID supports BLOB/CLOB data type. The LOB in PDO is represented as a
stream, so you can insert LOBs by binding a stream, and get LOBs by reading
a stream returned by CUBRID PDO. For example:
Example #1 Insert LOBs in CUBRID PDO
prepare($sql_stmt);
$ret = $stmt->bindParam(1, $fp, PDO::PARAM_LOB);
LOBs $ret = $stmt->execute();
?>
Example #2 Fetch LOBs in CUBRID PDO
prepare($sql_stmt);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_NUM);
header("Content-Type: image/png");
fpassthru($result[0]);
?>
The PDOStatement::getColumnMeta() in CUBRID PDO will return an associative
array containing the following values:
* type
* name
* table
* def
* precision
Column meta * scale
* not_null
* auto_increment
* unique_key
* multiple_key
* primary_key
* foreign_key
* reverse_index
* reverse_unique
Predefined Constants
The constants below are defined by this driver, and will only be available
when the extension has been either compiled into PHP or dynamically loaded
at runtime. In addition, these driver-specific constants should only be
used if you are using this driver. Using driver-specific attributes with
another driver may result in unexpected behaviour. PDO::getAttribute() may
be used to obtain the PDO_ATTR_DRIVER_NAME attribute to check the driver,
if your code can run against multiple drivers.
The following constants can be used when setting the database attribute.
They can be passed to PDO::getAttribute() or PDO::setAttribute().
PDO::CUBRID attribute flags
Constant Description
PDO::CUBRID_ATTR_ISOLATION_LEVEL Transaction isolation level for the
database connection.
PDO::CUBRID_ATTR_LOCK_TIMEOUT Transaction timeout in seconds.
Read only. The maximum string length
PDO::CUBRID_ATTR_MAX_STRING_LENGTH for bit, varbit, char, varchar, nchar,
nchar varying data types when using
CUBRID PDO API.
The following constants can be used when setting the transaction isolation
level. They can be passed to PDO::getAttribute() or returned by
PDO::setAttribute().
PDO::CUBRID isolation level flags
Constant Description
The lowest isolation level (1). A
dirty, non-repeatable or phantom
PDO::TRAN_COMMIT_CLASS_UNCOMMIT_INSTANCE read may occur for the tuple and
a non-repeatable read may occur
for the table as well.
A relatively low isolation level
PDO::TRAN_COMMIT_CLASS_COMMIT_INSTANCE (2). A dirty read does not occur,
but non-repeatable or phantom
read may occur.
The default isolation of CUBRID
(3). A dirty, non-repeatable or
PDO::TRAN_REP_CLASS_UNCOMMIT_INSTANCE phantom read may occur for the
tuple, but repeatable read is
ensured for the table.
A relatively low isolation level
PDO::TRAN_REP_CLASS_COMMIT_INSTANCE (4). A dirty read does not occur,
but non-repeatable or phantom
read may.
A relatively high isolation level
PDO::TRAN_REP_CLASS_REP_INSTANCE (5). A dirty or non-repeatable
read does not occur, but a
phantom read may.
The highest isolation level (6).
Problems concerning concurrency
PDO::TRAN_SERIALIZABLE (e.g. dirty read, non-repeatable
read, phantom read, etc.) do not
occur.
The following constants can be used when getting schema information. They
can be passed to PDO::cubrid_schema().
PDO::CUBRID schema flags
Constant Description
PDO::CUBRID_SCH_TABLE Get name and type of table in CUBRID.
PDO::CUBRID_SCH_VIEW Get name and type of view in CUBRID.
PDO::CUBRID_SCH_QUERY_SPEC Get the query definition of view.
PDO::CUBRID_SCH_ATTRIBUTE Get the attributes of table column.
PDO::CUBRID_SCH_TABLE_ATTRIBUTE Get the attributes of table.
Get the instance method. The instance
method is a method called by a class
PDO::CUBRID_SCH_METHOD instance. It is used more often than
the class method because most
operations are executed in the
instance.
Get the class method. The class method
is a method called by a class object.
PDO::CUBRID_SCH_TABLE_METHOD It is usually used to create a new
class instance or to initialize it. It
is also used to access or update class
attributes.
PDO::CUBRID_SCH_METHOD_FILE Get the information of the file where
the method of the table is defined.
PDO::CUBRID_SCH_SUPER_TABLE Get the name and type of table which
table inherites attributes from.
PDO::CUBRID_SCH_SUB_TABLE Get the name and type of table which
inherites attributes from this table.
PDO::CUBRID_SCH_CONSTRAINT Get the table constraints.
PDO::CUBRID_SCH_TRIGGER Get the table triggers.
PDO::CUBRID_SCH_TABLE_PRIVILEGE Get the privilege information of table.
PDO::CUBRID_SCH_COL_PRIVILEGE Get the privilege information of
column.
PDO::CUBRID_SCH_DIRECT_SUPER_TABLE Get the direct super table of table.
PDO::CUBRID_SCH_PRIMARY_KEY Get the table primary key.
PDO::CUBRID_SCH_IMPORTED_KEYS Get imported keys of table.
PDO::CUBRID_SCH_EXPORTED_KEYS Get exported keys of table.
PDO::CUBRID_SCH_CROSS_REFERENCE Get reference relationship of tow
tables.
----------------------------------------------------------------------
PDO_CUBRID DSN
(No version information available, might only be in SVN)
PDO_CUBRID DSN - Connecting to CUBRID databases
Description
The PDO_CUBRID Data Source Name (DSN) is composed of the following
elements, delimited by semicolons:
DSN prefix
The DSN prefix is cubrid:.
host
The hostname on which the database server resides.
port
The port on which the database server is running.
dbname
The name of the database.
Examples
Example #1 PDO_CUBRID DSN examples
The following example shows a PDO_CUBRID DSN for connecting to a CUBRID
database:
cubrid:host=localhost;port=33000;dbname=demodb
----------------------------------------------------------------------
----------------------------------------------------------------------
PDO::cubrid_schema
(No version information available, might only be in SVN)
PDO::cubrid_schema - Get the requested schema information
Description
array PDO::cubrid_schema ( int $schema_type [, string $table_name [,
string $col_name ]] )
This function is used to get the requested schema information from
database. You have to designate table_name, if you want to get information
on certain table, col_name, if you want to get information on certain
column (can be used only with PDO::CUBRID_SCH_COL_PRIVILEGE).
The result of this function is returned as a two-dimensional array (column
(associative array) * row (numeric array)). The following tables shows
types of schema and the column structure of the result array to be
returned based on the schema type.
Result Composition of Each Type
Schema Column Column Name Value
Number
PDO::CUBRID_SCH_TABLE 1 NAME
0:system
2 TYPE table
1:view
2:table
PDO::CUBRID_SCH_VIEW 1 NAME
2 TYPE 1:view
PDO::CUBRID_SCH_QUERY_SPEC 1 QUERY_SPEC
PDO::CUBRID_SCH_ATTRIBUTE / 1 ATTR_NAME
PDO::CUBRID_SCH_TABLE_ATTRIBUTE
2 DOMAIN
3 SCALE
4 PRECISION
5 INDEXED 1:indexed
6 NOT NULL 1:not null
7 SHARED 1:shared
8 UNIQUE 1:unique
9 DEFAULT
10 ATTR_ORDER base:1
11 CLASS_NAME
12 SOURCE_CLASS
13 IS_KEY 1:key
PDO::CUBRID_SCH_METHOD / 1 NAME
PDO::CUBRID_SCH_TABLE_METHOD
2 RET_DOMAIN
3 ARG_DOMAIN
PDO::CUBRID_SCH_METHOD_FILE 1 METHOD_FILE
PDO::CUBRID_SCH_SUPER_TABLE /
PDO::CUBRID_SCH_DIRECT_SUPER_TABLE / 1 CLASS_NAME
PDO::CUBRID_SCH_SUB_TABLE
0:system
2 TYPE table
1:view
2:table
0:unique
1:index
PDO::CUBRID_SCH_CONSTRAINT 1 TYPE 2:reverse
unique
3:reverse
index
2 NAME
3 ATTR_NAME
4 NUM_PAGES
5 NUM_KEYS
6 PRIMARY_KEY 1:primary
key
7 KEY_ORDER base:1
PDO::CUBRID_SCH_TRIGGER 1 NAME
2 STATUS
3 EVENT
4 TARGET_CLASS
5 TARGET_ATTR
6 ACTION_TIME
7 ACTION
8 PRIORITY
9 CONDITION_TIME
10 CONDITION
PDO::CUBRID_SCH_TABLE_PRIVILEGE / 1 CLASS_NAME /
PDO::CUBRID_SCH_COL_PRIVILEGE ATTR_NAME
2 PRIVILEGE
3 GRANTABLE
PDO::CUBRID_SCH_PRIMARY_KEY 1 CLASS_NAME
2 ATTR_NAME
3 KEY_SEQ base:1
4 KEY_NAME
PDO::CUBRID_SCH_IMPORTED_KEYS /
PDO::CUBRID_SCH_EXPORTED_KEYS / 1 PKTABLE_NAME
PDO::CUBRID_SCH_CROSS_REFERENCE
2 PKCOLUMN_NAME
3 FKTABLE_NAME base:1
4 FKCOLUMN_NAME
5 KEY_SEQ base:1
0:cascade
6 UPDATE_ACTION 1:restrict
2:no action
3:set null
0:cascade
7 DELETE_ACTION 1:restrict
2:no action
3:set null
8 FK_NAME
9 PK_NAME
Parameters
schema_type
Schema type that you want to know.
table_name
Table you want to know the schema of.
col_name
Column you want to know the schema of.
Return Values
Array containing the schema information, when process is successful;
FALSE, when process is unsuccessful
Examples
Example #1 A PDO::cubrid_schema() example
This example shows how to get primary key and foreign keys of table game.
cubrid_schema(PDO::CUBRID_SCH_PRIMARY_KEY, "game");
print_r($pk_list);
$fk_list = $dbh->cubrid_schema(PDO::CUBRID_SCH_IMPORTED_KEYS, "game");
print_r($fk_list);
?>
The above example will output:
Result:
Array
(
[0] => Array
(
[CLASS_NAME] => game
[ATTR_NAME] => athlete_code
[KEY_SEQ] => 3
[KEY_NAME] => pk_game_host_year_event_code_athlete_code
)
[1] => Array
(
[CLASS_NAME] => game
[ATTR_NAME] => event_code
[KEY_SEQ] => 2
[KEY_NAME] => pk_game_host_year_event_code_athlete_code
)
[2] => Array
(
[CLASS_NAME] => game
[ATTR_NAME] => host_year
[KEY_SEQ] => 1
[KEY_NAME] => pk_game_host_year_event_code_athlete_code
)
)
Array
(
[0] => Array
(
[PKTABLE_NAME] => athlete
[PKCOLUMN_NAME] => code
[FKTABLE_NAME] => game
[FKCOLUMN_NAME] => athlete_code
[KEY_SEQ] => 1
[UPDATE_RULE] => 1
[DELETE_RULE] => 1
[FK_NAME] => fk_game_athlete_code
[PK_NAME] => pk_athlete_code
)
[1] => Array
(
[PKTABLE_NAME] => event
[PKCOLUMN_NAME] => code
[FKTABLE_NAME] => game
[FKCOLUMN_NAME] => event_code
[KEY_SEQ] => 1
[UPDATE_RULE] => 1
[DELETE_RULE] => 1
[FK_NAME] => fk_game_event_code
[PK_NAME] => pk_event_code
)
)
----------------------------------------------------------------------
Table of Contents
* PDO_CUBRID DSN - Connecting to CUBRID databases
* PDO::cubrid_schema - Get the requested schema information
----------------------------------------------------------------------
----------------------------------------------------------------------
Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Introduction
Warning
This extension is EXPERIMENTAL. The behaviour of this extension including
the names of its functions and any other documentation surrounding this
extension may change without notice in a future release of PHP. This
extension should be used at your own risk.
PDO_DBLIB is a driver that implements the PHP Data Objects (PDO) interface
to enable access from PHP to Microsoft SQL Server and Sybase databases
through the FreeTDS libary.
This extension is not available anymore on Windows with PHP 5.3 or later.
On Windows, you should use SqlSrv, an alternative driver for MS SQL is
available from Microsoft:
>> http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx .
If it is not possible to use SqlSrv, you can use the PDO_ODBC driver to
connect to Microsoft SQL Server and Sybase databases, as the native
Windows DB-LIB is ancient, thread un-safe and no longer supported by
Microsoft.
----------------------------------------------------------------------
PDO_DBLIB DSN
(PECL PDO_DBLIB >= 0.9.0)
PDO_DBLIB DSN - Connecting to Microsoft SQL Server and Sybase databases
Description
The PDO_DBLIB Data Source Name (DSN) is composed of the following
elements:
DSN prefix
The DSN prefix is sybase: if PDO_DBLIB was linked against the
Sybase ct-lib libraries, mssql: if PDO_DBLIB was linked against
the Microsoft SQL Server libraries, or dblib: if PDO_DBLIB was
linked against the FreeTDS libraries.
host
The hostname on which the database server resides. Defaults to
127.0.0.1.
dbname
The name of the database.
charset
The client character set.
appname
The application name (used in sysprocesses). Defaults to "PHP
Generic DB-lib" or "PHP freetds".
secure
Currently unused.
Examples
Example #1 PDO_DBLIB DSN examples
The following examples show a PDO_DBLIB DSN for connecting to Microsoft
SQL Server and Sybase databases:
mssql:host=localhost;dbname=testdb
sybase:host=localhost;dbname=testdb
dblib:host=localhost;dbname=testdb
----------------------------------------------------------------------
Table of Contents
* PDO_DBLIB DSN - Connecting to Microsoft SQL Server and Sybase
databases
----------------------------------------------------------------------
----------------------------------------------------------------------
Firebird/Interbase Functions (PDO_FIREBIRD)
Introduction
Warning
This extension is EXPERIMENTAL. The behaviour of this extension including
the names of its functions and any other documentation surrounding this
extension may change without notice in a future release of PHP. This
extension should be used at your own risk.
PDO_FIREBIRD is a driver that implements the PHP Data Objects (PDO)
interface to enable access from PHP to Firebird and Interbase databases.
Installation
Use --with-pdo-firebird[=DIR] to install the PDO Firebird extension, where
the optional [=DIR] is the Firebird base install directory.
$ ./configure --with-pdo-firebird
Predefined Constants
The constants below are defined by this driver, and will only be available
when the extension has been either compiled into PHP or dynamically loaded
at runtime. In addition, these driver-specific constants should only be
used if you are using this driver. Using driver-specific attributes with
another driver may result in unexpected behaviour. PDO::getAttribute() may
be used to obtain the PDO_ATTR_DRIVER_NAME attribute to check the driver,
if your code can run against multiple drivers.
PDO::FB_ATTR_DATE_FORMAT (integer)
Available since PHP 5.3.0.
Sets the date format.
PDO::FB_ATTR_TIME_FORMAT (integer)
Sets the time format.
Available since PHP 5.3.0.
PDO::FB_ATTR_TIMESTAMP_FORMAT (integer)
Sets the timestamp format.
Available since PHP 5.3.0.
----------------------------------------------------------------------
PDO_FIREBIRD DSN
(PECL PDO_FIREBIRD >= 0.1.0)
PDO_FIREBIRD DSN - Connecting to Firebird and Interbase databases
Description
The PDO_FIREBIRD Data Source Name (DSN) is composed of the following
elements:
DSN prefix
The DSN prefix is firebird:.
dbname
The name of the database.
charset
The character set.
role
The SQL role name.
Examples
Example #1 PDO_FIREBIRD DSN examples
The following example shows a PDO_FIREBIRD DSN for connecting to Firebird
and Interbase databases:
firebird:dbname=DATABASE.GDE
----------------------------------------------------------------------
Table of Contents
* PDO_FIREBIRD DSN - Connecting to Firebird and Interbase databases
----------------------------------------------------------------------
----------------------------------------------------------------------
IBM Functions (PDO_IBM)
Introduction
PDO_IBM is a driver that implements the PHP Data Objects (PDO) interface
to enable access from PHP to IBM databases.
Installation
To build the PDO_IBM extension, the DB2 Client v9.1 or later must be
installed on the same system as PHP. The DB2 Client can be downloaded from
the IBM >> Application Development Site.
Note: Note
The DB2 Client v9.1 or later supports direct access to DB2 for Linux,
UNIX, and Windows v8 and v9.1 servers.
The DB2 Client v9.1 also supports access to DB2 UDB for i5 and DB2 UDB
for z/OS servers using the separately purchased >> DB2 Connect product.
PDO_IBM is a >> PECL extension, so follow the instructions in Installation
of PECL extensions to install the PDO_IBM extension. Issue the configure
command to point to the location of your DB2 Client header files and
libraries as follows:
bash$ ./configure --with-pdo-ibm=/path/to/sqllib[,shared]
The configure command defaults to the value of the DB2DIR environment
variable.
----------------------------------------------------------------------
PDO_IBM DSN
(PECL PDO_IBM >= 0.9.0)
PDO_IBM DSN - Connecting to IBM databases
Description
The PDO_IBM Data Source Name (DSN) is based on the IBM CLI DSN. The major
components of the PDO_IBM DSN are:
DSN prefix
The DSN prefix is ibm:.
DSN
The DSN can be any of the following:
* a) Data source setup using db2cli.ini or odbc.ini
* b) Catalogued database name i.e. database alias in the DB2
client catalog
* c) Complete connection string in the following format:
DRIVER={IBM DB2 ODBC
DRIVER};DATABASE=database;HOSTNAME=hostname;PORT=port;PROTOCOL=TCPIP;UID=username;PWD=password;
where the parameters represent the following values:
database
The name of the database.
hostname
The hostname or IP address of the database
server.
port
The TCP/IP port on which the database is
listening for requests.
username
The username with which you are connecting to
the database.
password
The password with which you are connecting to
the database.
Examples
Example #1 PDO_IBM DSN example using db2cli.ini
The following example shows a PDO_IBM DSN for connecting to an DB2
database cataloged as DB2_9 in db2cli.ini:
$db = new PDO("ibm:DSN=DB2_9", "", "");
[DB2_9]
Database=testdb
Protocol=tcpip
Hostname=11.22.33.444
Servicename=56789
Example #2 PDO_IBM DSN example using a connection string
The following example shows a PDO_IBM DSN for connecting to an DB2
database named testdb using the DB2 CLI connection string syntax.
$db = new PDO("ibm:DRIVER={IBM DB2 ODBC DRIVER};DATABASE=testdb;" .
"HOSTNAME=11.22.33.444;PORT=56789;PROTOCOL=TCPIP;", "testuser", "tespass");
----------------------------------------------------------------------
Table of Contents
* PDO_IBM DSN - Connecting to IBM databases
----------------------------------------------------------------------
----------------------------------------------------------------------
Informix Functions (PDO_INFORMIX)
Introduction
PDO_INFORMIX is a driver that implements the PHP Data Objects (PDO)
interface to enable access from PHP to Informix databases.
Installation
To build the PDO_INFORMIX extension, the Informix Client SDK 2.81 UC1 or
higher must be installed on the same system as PHP. The Informix Client
SDK is available from the >> IBM Informix Support Site.
PDO_INFORMIX is a >> PECL extension, so follow the instructions in
Installation of PECL extensions to install the PDO_INFORMIX extension.
Issue the configure command to point to the location of your Informix
Client SDK header files and libraries as follows:
bash$ ./configure --with-pdo-informix=/path/to/SDK[,shared]
The configure command defaults to the value of the INFORMIXDIR environment
variable.
Scrollable cursors
PDO_INFORMIX supports scrollable cursors; however, they are not enabled by
default. To enable scrollable cursor support, you must either set
ENABLESCROLLABLECURSORS=1 in the corresponding ODBC connection settings in
odbc.ini or pass the EnableScrollableCursors=1 clause in the DSN
connection string.
----------------------------------------------------------------------
PDO_INFORMIX DSN
(PECL PDO_INFORMIX >= 0.1.0)
PDO_INFORMIX DSN - Connecting to Informix databases
Description
The PDO_INFORMIX Data Source Name (DSN) is based on the Informix ODBC DSN
string. Details on configuring an Informix ODBC DSN are available from the
>> Informix Dynamic Server Information Center. The major components of the
PDO_INFORMIX DSN are:
DSN prefix
The DSN prefix is informix:.
DSN
The DSN can be either a data source setup using odbc.ini or a
complete >> connection string.
Examples
Example #1 PDO_INFORMIX DSN example using odbc.ini
The following example shows a PDO_INFORMIX DSN for connecting to an
Informix database cataloged as Infdrv33 in odbc.ini:
$db = new PDO("informix:DSN=Infdrv33", "", "");
[ODBC Data Sources]
Infdrv33=INFORMIX 3.3 32-BIT
[Infdrv33]
Driver=/opt/informix/csdk_2.81.UC1G2/lib/cli/iclis09b.so
Description=INFORMIX 3.3 32-BIT
Database=common_db
LogonID=testuser
pwd=testpass
Servername=ids_server
DB_LOCALE=en_US.819
OPTIMIZEAUTOCOMMIT=1
ENABLESCROLLABLECURSORS=1
Example #2 PDO_INFORMIX DSN example using a connection string
The following example shows a PDO_INFORMIX DSN for connecting to an
Informix database named common_db using the Informix connection string
syntax.
$db = new PDO("informix:host=host.domain.com; service=9800;
database=common_db; server=ids_server; protocol=onsoctcp;
EnableScrollableCursors=1", "testuser", "tespass");
----------------------------------------------------------------------
Table of Contents
* PDO_INFORMIX DSN - Connecting to Informix databases
----------------------------------------------------------------------
----------------------------------------------------------------------
MySQL Functions (PDO_MYSQL)
Introduction
PDO_MYSQL is a driver that implements the PHP Data Objects (PDO) interface
to enable access from PHP to MySQL 3.x, 4.x and 5.x databases.
PDO_MYSQL will take advantage of native prepared statement support present
in MySQL 4.1 and higher. If you're using an older version of the mysql
client libraries, PDO will emulate them for you.
Warning
Beware: Some MySQL table types (storage engines) do not support
transactions. When writing transactional database code using a table type
that does not support transactions, MySQL will pretend that a transaction
was initiated successfully. In addition, any DDL queries issued will
implicitly commit any pending transactions.
Installation
Use --with-pdo-mysql[=DIR] to install the PDO MySQL extension, where the
optional [=DIR] is the MySQL base install directory. If mysqlnd is passed
as [=DIR], then the MySQL native driver will be used.
Optionally, the --with-mysql-sock[=DIR] sets to location to the MySQL unix
socket pointer for all MySQL extensions, including PDO_MYSQL. If
unspecified, the default locations are searched.
Optionally, the --with-zlib-dir[=DIR] is used to set the path to the libz
install prefix.
$ ./configure --with-pdo-mysql --with-mysql-sock=/var/mysql/mysql.sock
Predefined Constants
The constants below are defined by this driver, and will only be available
when the extension has been either compiled into PHP or dynamically loaded
at runtime. In addition, these driver-specific constants should only be
used if you are using this driver. Using driver-specific attributes with
another driver may result in unexpected behaviour. PDO::getAttribute() may
be used to obtain the PDO_ATTR_DRIVER_NAME attribute to check the driver,
if your code can run against multiple drivers.
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY (integer)
If this attribute is set to TRUE on a PDOStatement, the MySQL
driver will use the buffered versions of the MySQL API. If you're
writing portable code, you should use PDOStatement::fetchAll()
instead.
Example #1 Forcing queries to be buffered in mysql
getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') {
$stmt = $db->prepare('select * from foo',
array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));
} else {
die("my application only works with mysql; I should use \$stmt->fetchAll() instead");
}
?>
PDO::MYSQL_ATTR_LOCAL_INFILE (integer)
Enable LOAD LOCAL INFILE.
Note, this constant can only be used in the driver_options array
when constructing a new database handle.
PDO::MYSQL_ATTR_INIT_COMMAND (integer)
Command to execute when connecting to the MySQL server. Will
automatically be re-executed when reconnecting.
Note, this constant can only be used in the driver_options array
when constructing a new database handle.
PDO::MYSQL_ATTR_READ_DEFAULT_FILE (integer)
Read options from the named option file instead of from my.cnf.
This option is not available if mysqlnd is used, because mysqlnd
does not read the mysql configuration files.
PDO::MYSQL_ATTR_READ_DEFAULT_GROUP (integer)
Read options from the named group from my.cnf or the file
specified with MYSQL_READ_DEFAULT_FILE. This option is not
available if mysqlnd is used, because mysqlnd does not read the
mysql configuration files.
PDO::MYSQL_ATTR_MAX_BUFFER_SIZE (integer)
Maximum buffer size. Defaults to 1 MiB. This constant is not
supported when compiled against mysqlnd.
PDO::MYSQL_ATTR_DIRECT_QUERY (integer)
Perform direct queries, don't use prepared statements.
PDO::MYSQL_ATTR_FOUND_ROWS (integer)
Return the number of found (matched) rows, not the number of
changed rows.
PDO::MYSQL_ATTR_IGNORE_SPACE (integer)
Permit spaces after function names. Makes all functions names
reserved words.
PDO::MYSQL_ATTR_COMPRESS (integer)
Enable network communication compression. This is not supported
when compiled against mysqlnd.
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
PDO_MYSQL Configuration Options
Name Default Changeable
pdo_mysql.default_socket "/tmp/mysql.sock" PHP_INI_SYSTEM
pdo_mysql.debug NULL PHP_INI_SYSTEM
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
pdo_mysql.default_socket string
Sets a Unix domain socket. This value can either be set at compile
time if a domain socket is found at configure. This ini setting is
Unix only.
pdo_mysql.debug boolean
Enables debugging for PDO_MYSQL. This setting is only available
when PDO_MYSQL is compiled against mysqlnd and in PDO debug mode.
----------------------------------------------------------------------
PDO_MYSQL DSN
(PECL PDO_MYSQL >= 0.1.0)
PDO_MYSQL DSN - Connecting to MySQL databases
Description
The PDO_MYSQL Data Source Name (DSN) is composed of the following
elements:
DSN prefix
The DSN prefix is mysql:.
host
The hostname on which the database server resides.
port
The port number where the database server is listening.
dbname
The name of the database.
unix_socket
The MySQL Unix socket (shouldn't be used with host or port).
charset
The character set.
Prior to PHP 5.3.6, this element was silently ignored. The same
behaviour can be partly replicated with the
PDO::MYSQL_ATTR_INIT_COMMAND driver option, as the following
example shows.
Warning
The method in the below example can only be used with character
sets that share the same lower 7 bit representation as ASCII, such
as ISO-8859-1 and UTF-8. Users using character sets that have
different representations (such as UTF-16 or Big5) must use the
charset option provided in PHP 5.3.6 and later versions.
Example #1 Setting the connection character set to UTF-8 prior to
PHP 5.3.6
'SET NAMES utf8',
);
$dbh = new PDO($dsn, $username, $password, $options);
?>
Changelog
Version Description
5.3.6 Prior to version 5.3.6, charset was ignored.
Examples
Example #2 PDO_MYSQL DSN examples
The following example shows a PDO_MYSQL DSN for connecting to MySQL
databases:
mysql:host=localhost;dbname=testdb
More complete examples:
mysql:host=localhost;port=3307;dbname=testdb
mysql:unix_socket=/tmp/mysql.sock;dbname=testdb
Notes
Note: Unix only:
When the host name is set to "localhost", then the connection to the
server is made thru a domain socket. If PDO_MYSQL is compiled against
libmysql then the location of the socket file is at libmysql's compiled
in location. If PDO_MYSQL is compiled against mysqlnd a default socket
can be set thru the pdo_mysql.default_socket setting.
----------------------------------------------------------------------
Table of Contents
* PDO_MYSQL DSN - Connecting to MySQL databases
----------------------------------------------------------------------
----------------------------------------------------------------------
Microsoft SQL Server Functions (PDO_SQLSRV)
Introduction
PDO_SQLSRV is a driver that implements the PHP Data Objects (PDO)
interface to enable access from PHP to MS SQL Server (starting with SQL
Server 2005) and SQL Azure databases.
Installation
The PDO_SQLSRV extension is enabled by adding appropriate DLL file to your
PHP extension directory and the corresponding entry to the php.ini file.
The PDO_SQLSRV download comes with several driver files. Which driver file
you use will depend on 3 factors: the PHP version you are using, whether
you are using thread-safe or non-thread-safe PHP, and whether your PHP
installation was compiled with the VC6 or VC9 compiler. For example, if
you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP
installation was compiled with the VC9 compiler, you should use the
php_pdo_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe
version compiled with the VC9 compiler if you are using IIS as your web
server). If you are running PHP 5.2, you are using thread-safe PHP, and
your PHP installation was compiled with the VC6 compiler, you should use
the php_pdo_sqlsrv_52_ts_vc6.dll file.
For more information about system requirements, see >> SQLSRV System
Requirements.
The PDO_SQLSRV extension is only compatible with PHP running on Windows.
Predefined Constants
The constants below are defined by this driver, and will only be available
when the extension has been either compiled into PHP or dynamically loaded
at runtime. In addition, these driver-specific constants should only be
used if you are using this driver. Using driver-specific attributes with
another driver may result in unexpected behaviour. PDO::getAttribute() may
be used to obtain the PDO_ATTR_DRIVER_NAME attribute to check the driver,
if your code can run against multiple drivers.
PDO::SQLSRV_TXN_READ_UNCOMMITTED (integer)
This constant is an acceptable value for the SQLSRV DSN key
TransactionIsolation. This constant sets the transaction isolation
level for the connection to Read Uncommitted.
PDO::SQLSRV_TXN_READ_COMMITTED (integer)
This constant is an acceptable value for the SQLSRV DSN key
TransactionIsolation. This constant sets the transaction isolation
level for the connection to Read Committed.
PDO::SQLSRV_TXN_REPEATABLE_READ (integer)
This constant is an acceptable value for the SQLSRV DSN key
TransactionIsolation. This constant sets the transaction isolation
level for the connection to Repeateable Read.
PDO::SQLSRV_TXN_SNAPSHOT (integer)
This constant is an acceptable value for the SQLSRV DSN key
TransactionIsolation. This constant sets the transaction isolation
level for the connection to Snapshot.
PDO::SQLSRV_TXN_SERIALIZABLE (integer)
This constant is an acceptable value for the SQLSRV DSN key
TransactionIsolation. This constant sets the transaction isolation
level for the connection to Serializable.
PDO::SQLSRV_ENCODING_BINARY (integer)
Specifies that data is sent/retrieved as a raw byte stream to/from
the server without performing encoding or translation. This
constant can be passed to PDOStatement::setAttribute,
PDO::prepare, PDOStatement::bindColumn, and
PDOStatement::bindParam.
PDO::SQLSRV_ENCODING_SYSTEM (integer)
Specifies that data is sent/retrieved to/from the server as 8-bit
characters as specified in the code page of the Windows locale
that is set on the system. Any multi-byte characters or characters
that do not map into this code page are substituted with a single
byte question mark (?) character. This constant can be passed to
PDOStatement::setAttribute, PDO::setAttribute, PDO::prepare,
PDOStatement::bindColumn, and PDOStatement::bindParam.
PDO::SQLSRV_ENCODING_UTF8 (integer)
Specifies that data is sent/retrieved to/from the server in UTF-8
encoding. This is the default encoding. This constant can be
passed to PDOStatement::setAttribute, PDO::setAttribute,
PDO::prepare, PDOStatement::bindColumn, and
PDOStatement::bindParam.
PDO::SQLSRV_ENCODING_DEFAULT (integer)
Specifies that data is sent/retrieved to/from the server according
to PDO::SQLSRV_ENCODING_SYSTEM if specified during connection. The
connection's encoding is used if specified in a prepare statement.
This constant can be passed to PDOStatement::setAttribute,
PDO::setAttribute, PDO::prepare, PDOStatement::bindColumn, and
PDOStatement::bindParam.
PDO::SQLSRV_ATTR_QUERY_TIMEOUT (integer)
A non-negative integer representing the timeout period, in
seconds. Zero (0) is the default and means no timeout. This
constant can be passed to PDOStatement::setAttribute,
PDO::setAttribute, and PDO::prepare.
PDO::SQLSRV_ATTR_DIRECT_QUERY (integer)
Indicates that a query should be executed directly, without being
prepared. This constant can be passed to PDO::setAttribute, and
PDO::prepare. For more information, see >> Direct and Prepared
Statement Execution.
----------------------------------------------------------------------
PDO_SQLSRV DSN
(No version information available, might only be in SVN)
PDO_SQLSRV DSN - Connecting to MS SQL Server and SQL Azure databases
Description
The PDO_SQLSRV Data Source Name (DSN) is composed of the following
elements:
DSN prefix
The DSN prefix is sqlsrv:.
APP
The application name used in tracing.
ConnectionPooling
Specifies whether the connection is assigned from a connection
pool (1 or TRUE) or not (0 or FALSE).
Database
The name of the database.
Encrypt
Specifies whether the communication with SQL Server is encrypted
(1 or TRUE) or unencrypted (0 or FALSE).
Failover_Partner
Specifies the server and instance of the database's mirror (if
enabled and configured) to use when the primary server is
unavailable.
LoginTimeout
Specifies the number of seconds to wait before failing the
connection attempt.
MultipleActiveResultSets
Disables or explicitly enables support for multiple active Result
sets (MARS).
QuotedId
Specifies whether to use SQL-92 rules for quoted identifiers (1 or
TRUE) or to use legacy Transact-SQL rules (0 or false).
Server
The name of the database server.
TraceFile
Specifies the path for the file used for trace data.
TraceOn
Specifies whether ODBC tracing is enabled (1 or TRUE) or disabled
(0 or FALSE) for the connection being established.
TransactionIsolation
Specifies the transaction isolation level. The accepted values for
this option are PDO::SQLSRV_TXN_READ_UNCOMMITTED,
PDO::SQLSRV_TXN_READ_COMMITTED, PDO::SQLSRV_TXN_REPEATABLE_READ,
PDO::SQLSRV_TXN_SNAPSHOT, and PDO::SQLSRV_TXN_SERIALIZABLE.
TrustServerCertificate
Specifies whether the client should trust (1 or TRUE) or reject (0
or FALSE) a self-signed server certificate.
WSID
Specifies the name of the computer for tracing.
Examples
Example #1 PDO_SQLSRV DSN examples
The following example shows how to connecto to a specified MS SQL Server
database:
$c = new PDO("sqlsrv:Server=localhost;Database=testdb", "UserName", "Password");
The following example shows how to connect to a MS SQL Server database on
a specified port:
$c = new PDO("sqlsrv:Server=localhost,1521;Database=testdb", "UserName", "Password");
The following example shows how to connecto to a SQL Azure database with
server ID 12345abcde. Note that when you connect to SQL Azure with PDO,
your username will be UserName@12345abcde (UserName@ServerId).
$c = new PDO("sqlsrv:Server=12345abcde.database.windows.net;Database=testdb", "UserName@12345abcde", "Password");
----------------------------------------------------------------------
Table of Contents
* PDO_SQLSRV DSN - Connecting to MS SQL Server and SQL Azure databases
----------------------------------------------------------------------
----------------------------------------------------------------------
Oracle Functions (PDO_OCI)
Introduction
Warning
This extension is EXPERIMENTAL. The behaviour of this extension including
the names of its functions and any other documentation surrounding this
extension may change without notice in a future release of PHP. This
extension should be used at your own risk.
PDO_OCI is a driver that implements the PHP Data Objects (PDO) interface
to enable access from PHP to Oracle databases through the OCI library.
Installation
Use --with-pdo-oci[=DIR] to install the PDO Oracle OCI extension, where
the optional [=DIR] is the Oracle Home directory. [=DIR] defaults to the
$ORACLE_HOME environment variable.
Use --with-pdo-oci=instantclient,prefix,version for an Oracle Instant
Client SDK, where prefix and version are configured.
// Using $ORACLE_HOME
$ ./configure --with-pdo-oci
// Using OIC for Linux with 10.2.0.3 RPMs with a /usr prefix
$ ./configure --with-pdo-oci=instantclient,/usr,10.2.0.3
----------------------------------------------------------------------
PDO_OCI DSN
(PECL PDO_OCI >= 0.1.0)
PDO_OCI DSN - Connecting to Oracle databases
Description
The PDO_OCI Data Source Name (DSN) is composed of the following elements:
DSN prefix
The DSN prefix is oci:.
dbname (Oracle Instant Client)
The URI for the Oracle Instant Client connection takes the form of
dbname=//hostname:port-number/database. If you are connecting to a
database defined in tnsnames.ora, use only the name of the
database: dbname=database.
charset
The client-side character set for the current environment handle.
Examples
Example #1 PDO_OCI DSN examples
The following examples show a PDO_OCI DSN for connecting to Oracle
databases:
// Connect to a database defined in tnsnames.ora
oci:dbname=mydb
// Connect using the Oracle Instant Client
oci:dbname=//localhost:1521/mydb
----------------------------------------------------------------------
Table of Contents
* PDO_OCI DSN - Connecting to Oracle databases
----------------------------------------------------------------------
----------------------------------------------------------------------
ODBC and DB2 Functions (PDO_ODBC)
Introduction
PDO_ODBC is a driver that implements the PHP Data Objects (PDO) interface
to enable access from PHP to databases through ODBC drivers or through the
IBM DB2 Call Level Interface (DB2 CLI) library. PDO_ODBC currently
supports three different "flavours" of database drivers:
ibm-db2
Supports access to IBM DB2 Universal Database, Cloudscape, and
Apache Derby servers through the free DB2 client.
unixODBC
Supports access to database servers through the unixODBC driver
manager and the database's own ODBC drivers.
generic
Offers a compile option for ODBC driver managers that are not
explicitly supported by PDO_ODBC.
On Windows, PDO_ODBC is built into the PHP core by default. It is linked
against the Windows ODBC Driver Manager so that PHP can connect to any
database cataloged as a System DSN, and is the recommended driver for
connecting to Microsoft SQL Server databases.
Installation
PDO_ODBC on UNIX systems
1. As of PHP 5.1, PDO_ODBC is included in the PHP source. You can compile
the PDO_ODBC extension as either a static or shared module using the
following configure commands.
ibm_db2
./configure --with-pdo-odbc=ibm-db2,/opt/IBM/db2/V8.1/
To build PDO_ODBC with the ibm-db2 flavour, you have to
have previously installed the DB2 application development
headers on the same machine on which you are compiling
PDO_ODBC. The DB2 application development headers are an
installable option in the DB2 servers, and are also
available as part of the DB2 Application Development
Client freely available for download from the IBM DB2
Universal Database >> support site.
If you do not supply a location for the DB2 libraries and
headers to the configure command, PDO_ODBC defaults to
/home/db2inst1/sqllib.
unixODBC
./configure --with-pdo-odbc=unixODBC,/usr/local
If you do not supply a location for the unixODBC
libraries and headers to the configure command, PDO_ODBC
defaults to /usr/local.
generic
./configure --with-pdo-odbc=generic,/usr/local,libname,ldflags,cflags
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
PDO_ODBC Configuration Options
Name Default Changeable Changelog
pdo_odbc.connection_pooling "strict" PHP_INI_ALL Available since PHP
5.1.0.
Available since PHP
5.1.1. This deprecated
pdo_odbc.db2_instance_name NULL PHP_INI_SYSTEM feature will certainly
be removed in the
future.
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
pdo_odbc.connection_pooling string
Whether to pool ODBC connections. Can be one of "strict",
"relaxed" or "off" (equals to ""). The parameter describes how
strict the connection manager should be when matching connection
parameters to existing pooled connections. strict is the recommend
default, and will result in the use of cached connections only
when all the connection parameters match exactly. relaxed will
result in the use of cached connections when similar connection
parameters are used. This can result in increased use of the
cache, at the risk of bleeding connection information between (for
example) virtual hosts.
This setting can only be changed from the php.ini file, and
affects the entire process; any other modules loaded into the
process that use the same ODBC libraries will be affected too,
including the Unified ODBC extension.
Warning
relaxed matching should not be used on a shared server, for
security reasons.
Tip
Leave this setting at the default strict setting unless you have
good reason to change it.
pdo_odbc.db2_instance_name string
If you compile PDO_ODBC using the db2 flavour, this setting sets
the value of the DB2INSTANCE environment variable on Linux and
UNIX operating systems to the specified name of the DB2 instance.
This enables PDO_ODBC to resolve the location of the DB2 libraries
and make cataloged connections to DB2 databases.
This setting can only be changed from the php.ini file, and
affects the entire process; any other modules loaded into the
process that use the same ODBC libraries will be affected too,
including the Unified ODBC extension.
This setting has no effect on Windows.
----------------------------------------------------------------------
PDO_ODBC DSN
(PECL PDO_ODBC >= 0.1.0)
PDO_ODBC DSN - Connecting to ODBC or DB2 databases
Description
The PDO_ODBC Data Source Name (DSN) is composed of the following elements:
DSN prefix
The DSN prefix is odbc:. If you are connecting to a database
cataloged in the ODBC driver manager or the DB2 catalog, you can
append the cataloged name of the database to the DSN.
DSN
The name of the database as cataloged in the ODBC driver manager
or the DB2 catalog. Alternately, you can provide a complete ODBC
connection string to connect to a database as described at
>> http://www.connectionstrings.com/.
UID
The name of the user for the connection. If you specify the user
name in the DSN, PDO ignores the value of the user name argument
in the PDO constructor.
PWD
The password of the user for the connection. If you specify the
password in the DSN, PDO ignores the value of the password
argument in the PDO constructor.
Examples
Example #1 PDO_ODBC DSN example (ODBC driver manager)
The following example shows a PDO_ODBC DSN for connecting to an ODBC
database cataloged as testdb in the ODBC driver manager:
odbc:testdb
Example #2 PDO_ODBC DSN example (IBM DB2 uncataloged connection)
The following example shows a PDO_ODBC DSN for connecting to an IBM DB2
database named SAMPLE using the full ODBC DSN syntax:
odbc:DRIVER={IBM DB2 ODBC DRIVER};HOSTNAME=localhost;PORT=50000;DATABASE=SAMPLE;PROTOCOL=TCPIP;UID=db2inst1;PWD=ibmdb2;
Example #3 PDO_ODBC DSN example (Microsoft Access uncataloged connection)
The following example shows a PDO_ODBC DSN for connecting to a Microsoft
Access database stored at C:\db.mdb using the full ODBC DSN syntax:
odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\\db.mdb;Uid=Admin
----------------------------------------------------------------------
Table of Contents
* PDO_ODBC DSN - Connecting to ODBC or DB2 databases
----------------------------------------------------------------------
----------------------------------------------------------------------
PostgreSQL Functions (PDO_PGSQL)
Introduction
PDO_PGSQL is a driver that implements the PHP Data Objects (PDO) interface
to enable access from PHP to PostgreSQL databases.
Resource Types
This extension defines a stream resource returned by PDO::pgsqlLOBOpen().
Installation
Use --with-pdo-pgsql[=DIR] to install the PDO PostgreSQL extension, where
the optional [=DIR] is the PostgreSQL base install directory, or the path
to pg_config.
$ ./configure --with-pdo-pgsql
----------------------------------------------------------------------
PDO_PGSQL DSN
(PECL PDO_PGSQL >= 0.1.0)
PDO_PGSQL DSN - Connecting to PostgreSQL databases
Description
The PDO_PGSQL Data Source Name (DSN) is composed of the following
elements, delimited by spaces or semicolons:
DSN prefix
The DSN prefix is pgsql:.
host
The hostname on which the database server resides.
port
The port on which the database server is running.
dbname
The name of the database.
user
The name of the user for the connection. If you specify the user
name in the DSN, PDO ignores the value of the user name argument
in the PDO constructor.
password
The password of the user for the connection. If you specify the
password in the DSN, PDO ignores the value of the password
argument in the PDO constructor.
Note:
The bytea fields are returned as streams.
Examples
Example #1 PDO_PGSQL DSN examples
The following example shows a PDO_PGSQL DSN for connecting to a PostgreSQL
database:
pgsql:host=localhost;port=5432;dbname=testdb;user=bruce;password=mypass
----------------------------------------------------------------------
----------------------------------------------------------------------
PDO::pgsqlLOBCreate
(PHP 5 >= 5.1.2, PECL pdo_pgsql >= 1.0.2)
PDO::pgsqlLOBCreate - Creates a new large object
Description
string PDO::pgsqlLOBCreate ( void )
PDO::pgsqlLOBCreate() creates a large object and returns the OID of that
object. You may then open a stream on the object using PDO::pgsqlLOBOpen()
to read or write data to it. The OID can be stored in columns of type OID
and be used to reference the large object, without causing the row to grow
arbitrarily large. The large object will continue to live in the database
until it is removed by calling PDO::pgsqlLOBUnlink().
Large objects can be up to 2GB in size, but are cumbersome to use; you
need to ensure that PDO::pgsqlLOBUnlink() is called prior to deleting the
last row that references its OID from your database. In addition, large
objects have no access controls. As an alternative, try the bytea column
type; recent versions of PostgreSQL allow bytea columns of up to 1GB in
size and transparently manage the storage for optimal row size.
Note: This function must be called within a transaction.
Parameters
PDO::pgsqlLOBCreate() takes no parameters.
Return Values
Returns the OID of the newly created large object on success, or FALSE on
failure.
Examples
Example #1 A PDO::pgsqlLOBCreate() example
This example creates a new large object and copies the contents of a file
into it. The OID is then stored into a table.
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$oid = $db->pgsqlLOBCreate();
$stream = $db->pgsqlLOBOpen($oid, 'w');
$local = fopen($filename, 'rb');
stream_copy_to_stream($local, $stream);
$local = null;
$stream = null;
$stmt = $db->prepare("INSERT INTO BLOBS (ident, oid) VALUES (?, ?)");
$stmt->execute(array($some_id, $oid));
$db->commit();
?>
See Also
* PDO::pgsqlLOBOpen() - Opens an existing large object stream
* PDO::pgsqlLOBUnlink() - Deletes the large object
* pg_lo_create() - Create a large object
----------------------------------------------------------------------
----------------------------------------------------------------------
PDO::pgsqlLOBOpen
(PHP 5 >= 5.1.2, PECL pdo_pgsql >= 1.0.2)
PDO::pgsqlLOBOpen - Opens an existing large object stream
Description
resource PDO::pgsqlLOBOpen ( string $oid [, string $mode = "rb" ] )
PDO::pgsqlLOBOpen() opens a stream to access the data referenced by oid.
If mode is r, the stream is opened for reading, if mode is w, then the
stream will be opened for writing. You can use all the usual filesystem
functions, such as fread(), fwrite() and fgets() to manipulate the
contents of the stream.
Note: This function, and all manipulations of the large object, must be
called and carried out within a transaction.
Parameters
oid
A large object identifier.
mode
If mode is r, open the stream for reading. If mode is w, open the
stream for writing.
Return Values
Returns a stream resource on success or FALSE on failure.
Examples
Example #1 A PDO::pgsqlLOBOpen() example
Following on from the PDO::pgsqlLOBCreate() example, this code snippet
retrieves the large object from the database and outputs it to the
browser.
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$stmt = $db->prepare("select oid from BLOBS where ident = ?");
$stmt->execute(array($some_id));
$stmt->bindColumn('oid', $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);
fpassthru($lob);
?>
See Also
* PDO::pgsqlLOBCreate() - Creates a new large object
* PDO::pgsqlLOBUnlink() - Deletes the large object
* pg_lo_open() - Open a large object
----------------------------------------------------------------------
----------------------------------------------------------------------
PDO::pgsqlLOBUnlink
(PHP 5 >= 5.1.2, PECL pdo_pgsql >= 1.0.2)
PDO::pgsqlLOBUnlink - Deletes the large object
Description
bool PDO::pgsqlLOBUnlink ( string $oid )
Deletes a large object from the database identified by OID.
Note: This function must be called within a transaction.
Parameters
oid
A large object identifier
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 A PDO::pgsqlLOBUnlink() example
This example unlinks a large object from the database prior to deleting
the row that references it from the blobs table we've been using in our
PDO::pgsqlLOBCreate() and PDO::pgsqlLOBOpen() examples.
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$db->pgsqlLOBUnlink($oid);
$stmt = $db->prepare("DELETE FROM BLOBS where ident = ?");
$stmt->execute(array($some_id));
$db->commit();
?>
See Also
* PDO::pgsqlLOBOpen() - Opens an existing large object stream
* PDO::pgsqlLOBCreate() - Creates a new large object
----------------------------------------------------------------------
Table of Contents
* PDO_PGSQL DSN - Connecting to PostgreSQL databases
* PDO::pgsqlLOBCreate - Creates a new large object
* PDO::pgsqlLOBOpen - Opens an existing large object stream
* PDO::pgsqlLOBUnlink - Deletes the large object
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite Functions (PDO_SQLITE)
Introduction
PDO_SQLITE is a driver that implements the PHP Data Objects (PDO)
interface to enable access to SQLite 3 databases.
In PHP 5.1, the SQLite extension also provides a driver for SQLite 2
databases; while it is not technically a part of the PDO_SQLITE driver, it
behaves similarly, so it is documented alongside it. The SQLite 2 driver
for PDO is provided primarily to make it easier to import legacy SQLite 2
database files into an application that uses the faster, more efficient
SQLite 3 driver. As a result, the SQLite 2 driver is not as feature-rich
as the SQLite 3 driver.
Note:
PDO_SQLITE allows using strings apart from streams together with
PDO::PARAM_LOB.
Installation
The PDO_SQLITE PDO driver is enabled by default. To disable,
--without-pdo-sqlite[=DIR] may be used, where the optional [=DIR] is the
sqlite base install directory.
----------------------------------------------------------------------
PDO_SQLITE DSN
(PECL PDO_SQLITE >= 0.2.0)
PDO_SQLITE DSN - Connecting to SQLite databases
Description
The PDO_SQLITE Data Source Name (DSN) is composed of the following
elements:
DSN prefix (SQLite 3)
The DSN prefix is sqlite:.
* To access a database on disk, append the absolute path to the
DSN prefix.
* To create a database in memory, append :memory: to the DSN
prefix.
DSN prefix (SQLite 2)
The SQLite extension in PHP 5.1 provides a PDO driver that
supports accessing and creating SQLite 2 databases. This enables
you to access databases you may have created with the SQLite
extension in previous versions of PHP.
Note:
The sqlite2 driver is only available in PHP 5.1.x if you have
enabled both PDO and ext/sqlite. It is not currently available
via PECL.
The DSN prefix for connecting to SQLite 2 databases is sqlite2:.
* To access a database on disk, append the absolute path to the
DSN prefix.
* To create a database in memory, append :memory: to the DSN
prefix.
Examples
Example #1 PDO_SQLITE DSN examples
The following examples show PDO_SQLITE DSN for connecting to SQLite
databases:
sqlite:/opt/databases/mydb.sq3
sqlite::memory:
sqlite2:/opt/databases/mydb.sq2
sqlite2::memory:
----------------------------------------------------------------------
----------------------------------------------------------------------
PDO::sqliteCreateAggregate
(PHP 5 >= 5.1.0, PECL pdo_sqlite >= 1.0.0)
PDO::sqliteCreateAggregate - Registers an aggregating User Defined
Function for use in SQL statements
Description
bool PDO::sqliteCreateAggregate ( string $function_name , callback
$step_func , callback $finalize_func [, int $num_args ] )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
This method is similar to PDO::sqliteCreateFunction except that it
registers functions that can be used to calculate a result aggregated
across all the rows of a query.
The key difference between this method and PDO::sqliteCreateFunction is
that two functions are required to manage the aggregate.
Parameters
function_name
The name of the function used in SQL statements.
step_func
Callback function called for each row of the result set. Your PHP
function should accumulate the result and store it in the
aggregation context.
This function need to be defined as:
step ( mixed $context , int $rownumber , mixed $value1 [, mixed
$value2 [, mixed $.. ]] )
context will be NULL for the first row; on subsequent rows it will
have the value that was previously returned from the step
function; you should use this to maintain the aggregate state.
rownumber will hold the current row number.
finalize_func
Callback function to aggregate the "stepped" data from each row.
Once all the rows have been processed, this function will be
called and it should then take the data from the aggregation
context and return the result. Callback functions should return a
type understood by SQLite (i.e. scalar type).
This function need to be defined as:
fini ( mixed $context , int $rownumber )
context will hold the return value from the very last call to the
step function.
rownumber will hold the number of rows over which the aggregate
was performed.
The return value of this function will be used as the return value
for the aggregate.
num_args
Hint to the SQLite parser if the callback function accepts a
predetermined number of arguments.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 max_length aggregation function example
exec("CREATE TABLE strings(a)");
$insert = $db->prepare('INSERT INTO strings VALUES (?)');
foreach ($data as $str) {
$insert->execute(array($str));
}
$insert = null;
function max_len_step(&$context, $rownumber, $string)
{
if (strlen($string) > $context) {
$context = strlen($string);
}
return $context;
}
function max_len_finalize(&$context, $rownumber)
{
return $context;
}
$db->sqliteCreateAggregate('max_len', 'max_len_step', 'max_len_finalize');
var_dump($db->query('SELECT max_len(a) from strings')->fetchAll());
?>
In this example, we are creating an aggregating function that will
calculate the length of the longest string in one of the columns of the
table. For each row, the max_len_step function is called and passed a
context parameter. The context parameter is just like any other PHP
variable and be set to hold an array or even an object value. In this
example, we are simply using it to hold the maximum length we have seen so
far; if the string has a length longer than the current maximum, we update
the context to hold this new maximum length.
After all of the rows have been processed, SQLite calls the
max_len_finalize function to determine the aggregate result. Here, we
could perform some kind of calculation based on the data found in the
context. In our simple example though, we have been calculating the result
as the query progressed, so we simply need to return the context value.
Tip
It is NOT recommended for you to store a copy of the values in the context
and then process them at the end, as you would cause SQLite to use a lot
of memory to process the query - just think of how much memory you would
need if a million rows were stored in memory, each containing a string 32
bytes in length.
Tip
You can use PDO::sqliteCreateFunction and PDO::sqliteCreateAggregate to
override SQLite native SQL functions.
Note:
This method is not available with the SQLite2 driver. Use the old style
sqlite API for that instead.
See Also
* PDO::sqliteCreateFunction
* sqlite_create_function() - Registers a "regular" User Defined Function
for use in SQL statements
* sqlite_create_aggregate() - Register an aggregating UDF for use in SQL
statements
----------------------------------------------------------------------
----------------------------------------------------------------------
PDO::sqliteCreateFunction
(PHP 5 >= 5.1.0, PECL pdo_sqlite >= 1.0.0)
PDO::sqliteCreateFunction - Registers a User Defined Function for use in
SQL statements
Description
bool PDO::sqliteCreateFunction ( string $function_name , callback
$callback [, int $num_args ] )
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
This method allows you to register a PHP function with SQLite as an UDF
(User Defined Function), so that it can be called from within your SQL
statements.
The UDF can be used in any SQL statement that can call functions, such as
SELECT and UPDATE statements and also in triggers.
Parameters
function_name
The name of the function used in SQL statements.
callback
Callback function to handle the defined SQL function.
Note: Callback functions should return a type understood by
SQLite (i.e. scalar type).
num_args
Hint to the SQLite parser if the callback function accepts a
predetermined number of arguments.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 PDO::sqliteCreateFunction() example
sqliteCreateFunction('md5rev', 'md5_and_reverse', 1);
$rows = $db->query('SELECT md5rev(filename) FROM files')->fetchAll();
?>
In this example, we have a function that calculates the md5 sum of a
string, and then reverses it. When the SQL statement executes, it returns
the value of the filename transformed by our function. The data returned
in $rows contains the processed result.
The beauty of this technique is that you do not need to process the result
using a foreach loop after you have queried for the data.
Tip
You can use PDO::sqliteCreateFunction and PDO::sqliteCreateAggregate to
override SQLite native SQL functions.
Note:
This method is not available with the SQLite2 driver. Use the old style
sqlite API for that instead.
See Also
* PDO::sqliteCreateAggregate
* sqlite_create_function() - Registers a "regular" User Defined Function
for use in SQL statements
* sqlite_create_aggregate() - Register an aggregating UDF for use in SQL
statements
----------------------------------------------------------------------
Table of Contents
* PDO_SQLITE DSN - Connecting to SQLite databases
* PDO::sqliteCreateAggregate - Registers an aggregating User Defined
Function for use in SQL statements
* PDO::sqliteCreateFunction - Registers a User Defined Function for use
in SQL statements
----------------------------------------------------------------------
----------------------------------------------------------------------
4D Functions (PDO_4D)
Introduction
Warning
This extension is EXPERIMENTAL. The behaviour of this extension including
the names of its functions and any other documentation surrounding this
extension may change without notice in a future release of PHP. This
extension should be used at your own risk.
PDO_4D is a driver that implements the PHP Data Objects (PDO) interface to
enable access from PHP to 4D databases.
4D is an integrated platform that speeds and simplifies the development
and deployment of business applications, used in over 70 countries, by a
community of thousands of developers and vertical solution providers, with
millions of end-users worldwide.
By offering a suite of integrated tools such as an ANSI SQL relational and
transactional database, a graphical development environment, a
fourth-generation language with over 1000 high-level commands, a built-in
HTTP server, application server, etc., 4D facilitates the creation and
maintenance of applications from one to hundreds of simultaneous users,
whether on Windows, Mac or from any Web client.
4D is also an open platform, offering a complete API for plug-in creation,
including various connectors that allow it to act as a back-end or
front-end for many environments (Oracle via OCI, SOAP client or server,
Flex data source, all ODBC databases, XML over HTTP, etc.)
In addition to the ability to interact with 4D applications across Web
Services, 4D databases can now be directly accessed using the PDO_4D
driver.
More details about the 4D development environment on
>> http://www.4d.com/.
PDO_4D is known to work with 4D versions 12 beta and up, for Mac OS X and
Windows. Older plat-forms may work, but are unsupported.
----------------------------------------------------------------------
PDO_4D DSN
(No version information available, might only be in SVN)
PDO_4D DSN - Connecting to 4D SQL server
Description
The PDO_4D DSN consists of:
DSN prefix
The DSN prefix is 4D:.
host
The host on which the 4D SQL server is.
port
The port number for the server. This is optional.
user
The login name when connecting to the database.
password
The password for the above login.
dbname
The name of the database. This parameter is optional, and it is
not used.
charset
The 4D character set.
Examples
Example #1 DSN examples for PDO_4D
The following examples has two DSN for PDO_4D, that connects to a 4D
database :
4D:host=localhost;charset=UTF-8
Other possible values :
4D:host=localhost
4D:
----------------------------------------------------------------------
----------------------------------------------------------------------
Constants for PDO_4D
(No version information available, might only be in SVN)
Constants for PDO_4D - Constants for PDO_4D
Predefined Constants
The constants below are defined by this driver, and will only be available
when the extension has been either compiled into PHP or dynamically loaded
at runtime. In addition, these driver-specific constants should only be
used if you are using this driver. Using driver-specific attributes with
another driver may result in unexpected behaviour. PDO::getAttribute() may
be used to obtain the PDO_ATTR_DRIVER_NAME attribute to check the driver,
if your code can run against multiple drivers.
PDO::FOURD_ATTR_CHARSET (integer)
Change the charset in which 4D returns data. (Default is UTF-8).
PDO::FOURD_ATTR_PREFERRED_IMAGE_TYPES (integer)
The requested format of the image, when selecting a row with a
column type PICTURE. It may be any type that 4D supports.
----------------------------------------------------------------------
----------------------------------------------------------------------
SQL types with PDO_4D and PHP
(No version information available, might only be in SVN)
SQL types with PDO_4D and PHP - SQL types with PDO_4D and PHP
Supported SQL types
Type SQL 4D Equivalent 4D Note
ALPHA_NUMERIC TEXT
VARCHAR TEXT
TEXT TEXT
TIMESTAMP DATE
INTERVAL HOUR
DURATION HOUR
BOOLEAN BOOLEAN
BIT BOOLEAN
BYTE INT32
INT16 SMALLINT
SMALLINT SMALLINT
INT32 INT32
INT INT32
INT64 INT64
NUMERIC INT64
REAL REAL Unsupported (use VARCHAR conversion)
FLOAT FLOAT Unsupported (use VARCHAR conversion)
DOUBLE PRECISION FLOAT
BLOB BLOB Must use a prepared statement, and
PDO::PARAM_LOB
BIT VARYING BLOB Must use a prepared statement, and
PDO::PARAM_LOB
CLOB TEXT
PICTURE PICTURE Must use a prepared statement, and
PDO::PARAM_LOB
----------------------------------------------------------------------
----------------------------------------------------------------------
SQL acceptable by 4D
(No version information available, might only be in SVN)
SQL acceptable by 4D - PDO and SQL 4D
Description
4D implements strictly the ANSI 89 standard, and have it enforced. It is
highly recommended to read the 4D SQL documentation to learn about the
available commands. The URL of the manual is : >> http://doc.4d.com/.
Below is a list of 4D SQL characteristics: it is not exhaustive, but may
serve as an introduction.
Characteristics of 4D SQL
Characteristics Alternative Note
INT is the supported
INTEGER Modify the SQL to use INT. integer type in
4Dv12.0.
CHAR Use VARCHAR instead. Unsupported in 4Dv12.0
UNION Unsupported. Make separate Unsupported in 4Dv12.0
queries.
SELECT 1 + 1; SELECT 1 + 1 FROM FROM is required
_USER_SCHEMAS;
Cast the FLOAT value into Unsupported in current
FLOAT a FLOAT or STRING, with an versions of the PDO_4D
SQL 4D function (CAST, driver
ROUND, TRUNC or TRUNCATE)
One must provide the
Take care your SQL query, right type that 4D
Strong typing or your PHP code provides expect. One can't
data with the expected insert '1' (as a
type string) in an INTEGER
column.
The PDO extension cast
PDO::execute($row)() : Use the prepared all values through
only works if all the statements, and use the execute() as string,
table's column are of right types. and expect the SQL
type TEXT or VARCHAR database to parse the
values.
Do not use NULL constants. It is not allowed to
SELECT NULL FROM TABLE Extract them from the use the NULL constant
table in the select list
SELECT * FROM TABLE Use WHERE 1 = 1 A constant can't be
WHERE 1 used in a WHERE clause
The list of tables,
schemas, index, etc.
are in these system
tables : _USER_TABLES,
SHOW TABLES Use system tables _USER_COLUMNS,
_USER_INDEXES,
_USER_CONSTRAINTS,
_USER_IND_COLUMNS,
_USER_CONS_COLUMNS, and
_USER_SCHEMAS.
To escape SQL elements
Use the following function names (tables, fields,
to protect SQL elements: users, groups, schema,
function primary key, etc.), the
SQL structure delimiter sqlEscapeElement(elem) { whole identifier must
return '[' . be between square
str_replace(']',']]', brackets, and the
$elem) . ']'; } closing brackets ']'
must be doubled.
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples with PDO_4D
(No version information available, might only be in SVN)
Examples with PDO_4D - Examples PDO_4D
This basic example show how to connect, execute a query, read data and
disconnect from a 4D SQL server.
Example #1 Basic example with PDO_4D
exec('CREATE TABLE test(id varCHAR(1) NOT NULL, val VARCHAR(10))');
} catch (PDOException $e) {
die("Erreur 4D : " . $e->getMessage());
}
$db->exec("INSERT INTO test VALUES('A', 'B')");
$db->exec("INSERT INTO test VALUES('C', 'D')");
$db->exec("INSERT INTO test VALUES('E', 'F')");
$stmt = $db->prepare('SELECT id, val from test');
$stmt->execute();
print_r($stmt->fetchAll());
unset($stmt);
unset($db);
?>
The above example will output:
Array
(
[0] => Array
(
[ID] => A
[0] => A
[VAL] => B
[1] => B
)
[1] => Array
(
[ID] => C
[0] => C
[VAL] => D
[1] => D
)
[2] => Array
(
[ID] => E
[0] => E
[VAL] => F
[1] => F
)
)
This example shows how to execute a query in 4D language, and how to read
the result through PDO_4D.
Example #2 Accessing 4D language from pdo_4d
Set up a 4D method, called method. Make sure in the method properties that
the option Available via SQL is checked. The 4D code is the following.
C_TEXTE($0)
$0:=Version application(*);
The PHP code to use the above 4D method is :
prepare('SELECT {FN method() AS VARCHAR } FROM _USER_SCHEMAS LIMIT 1');
$stmt->execute();
print_r($stmt->fetchAll());
unset($stmt);
unset($db);
?>
The above example will output:
(
[0] => Array
(
[] => F0011140
[0] => F0011140
)
)
Example #3 Escaping 4D table names
This examples illustrates how to escape characters in a 4D SQL query.
$object) {
$object = str_replace(']',']]', $object);
print "$object\n";
$db->exec('CREATE TABLE IF NOT EXISTS ['.$object.'](['.$object.'] FLOAT)');
$req = "INSERT INTO [$object] ([$object]) VALUES ($id);";
$db->query($req);
$q = $db->prepare("SELECT [$object] FROM [$object]");
$q->execute();
$x[] = $q->fetch(PDO::FETCH_NUM);
$db->exec('DROP TABLE ['.$object.'];');
}
?>
The above example will output:
[
]]
[]]
]][
[[
]]]]
[[[
]]]]]]
TBL ]]]]32[23
----------------------------------------------------------------------
Table of Contents
* PDO_4D DSN - Connecting to 4D SQL server
* Constants for PDO_4D - Constants for PDO_4D
* SQL types with PDO_4D and PHP - SQL types with PDO_4D and PHP
* SQL acceptable by 4D - PDO and SQL 4D
* Examples with PDO_4D - Examples PDO_4D
----------------------------------------------------------------------
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Connections and Connection management
* Transactions and auto-commit
* Prepared statements and stored procedures
* Errors and error handling
* Large Objects (LOBs)
* PDO - The PDO class
* PDO::beginTransaction - Initiates a transaction
* PDO::commit - Commits a transaction
* PDO::__construct - Creates a PDO instance representing a
connection to a database
* PDO::errorCode - Fetch the SQLSTATE associated with the last
operation on the database handle
* PDO::errorInfo - Fetch extended error information associated with
the last operation on the database handle
* PDO::exec - Execute an SQL statement and return the number of
affected rows
* PDO::getAttribute - Retrieve a database connection attribute
* PDO::getAvailableDrivers - Return an array of available PDO
drivers
* PDO::inTransaction - Checks if inside a transaction
* PDO::lastInsertId - Returns the ID of the last inserted row or
sequence value
* PDO::prepare - Prepares a statement for execution and returns a
statement object
* PDO::query - Executes an SQL statement, returning a result set as
a PDOStatement object
* PDO::quote - Quotes a string for use in a query.
* PDO::rollBack - Rolls back a transaction
* PDO::setAttribute - Set an attribute
* PDOStatement - The PDOStatement class
* PDOStatement->bindColumn - Bind a column to a PHP variable
* PDOStatement->bindParam - Binds a parameter to the specified
variable name
* PDOStatement->bindValue - Binds a value to a parameter
* PDOStatement->closeCursor - Closes the cursor, enabling the
statement to be executed again.
* PDOStatement->columnCount - Returns the number of columns in the
result set
* PDOStatement->debugDumpParams - Dump an SQL prepared command
* PDOStatement->errorCode - Fetch the SQLSTATE associated with the
last operation on the statement handle
* PDOStatement->errorInfo - Fetch extended error information
associated with the last operation on the statement handle
* PDOStatement->execute - Executes a prepared statement
* PDOStatement->fetch - Fetches the next row from a result set
* PDOStatement->fetchAll - Returns an array containing all of the
result set rows
* PDOStatement->fetchColumn - Returns a single column from the next
row of a result set
* PDOStatement->fetchObject - Fetches the next row and returns it
as an object.
* PDOStatement->getAttribute - Retrieve a statement attribute
* PDOStatement->getColumnMeta - Returns metadata for a column in a
result set
* PDOStatement->nextRowset - Advances to the next rowset in a
multi-rowset statement handle
* PDOStatement->rowCount - Returns the number of rows affected by
the last SQL statement
* PDOStatement->setAttribute - Set a statement attribute
* PDOStatement->setFetchMode - Set the default fetch mode for this
statement
* PDOException - The PDOException class
* PDO Drivers
* CUBRID (PDO) - CUBRID Functions (PDO_CUBRID)
* MS SQL Server (PDO) - Microsoft SQL Server and Sybase Functions
(PDO_DBLIB)
* Firebird/Interbase (PDO) - Firebird/Interbase Functions
(PDO_FIREBIRD)
* IBM (PDO) - IBM Functions (PDO_IBM)
* Informix (PDO) - Informix Functions (PDO_INFORMIX)
* MySQL (PDO) - MySQL Functions (PDO_MYSQL)
* MS SQL Server (PDO) - Microsoft SQL Server Functions (PDO_SQLSRV)
* Oracle (PDO) - Oracle Functions (PDO_OCI)
* ODBC and DB2 (PDO) - ODBC and DB2 Functions (PDO_ODBC)
* PostgreSQL (PDO) - PostgreSQL Functions (PDO_PGSQL)
* SQLite (PDO) - SQLite Functions (PDO_SQLITE)
* 4D (PDO) - 4D Functions (PDO_4D)
----------------------------------------------------------------------
* DBA - Database (dbm-style) Abstraction Layer
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* DBA Functions
* dbx
* Introduction
* Installing/Configuring
* Predefined Constants
* dbx Functions
* ODBC - ODBC (Unified)
* Introduction
* Installing/Configuring
* Predefined Constants
* ODBC Functions
* PDO - PHP Data Objects
* Introduction
* Installing/Configuring
* Predefined Constants
* Connections and Connection management
* Transactions and auto-commit
* Prepared statements and stored procedures
* Errors and error handling
* Large Objects (LOBs)
* PDO - The PDO class
* PDOStatement - The PDOStatement class
* PDOException - The PDOException class
* PDO Drivers
----------------------------------------------------------------------
----------------------------------------------------------------------
Vendor Specific Database Extensions
----------------------------------------------------------------------
CUBRID
----------------------------------------------------------------------
Introduction
These functions allow you to access CUBRID database servers. More
information about CUBRID can be found at >> CUBRID.
Documentation for CUBRID can be found at >> CUBRID Documentation.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
In order to have these functions available, you must install CUBRID, and
compile CUBRID PHP Library with CUBRID support.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here: >> http://pecl.php.net/package/cubrid.
A DLL for this PECL extension is currently unavailable. See also the
building on Windows section.
For information about manual installation on Linux and Windows systems,
please read the file build-guide.html included in the package.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
There is no runtime configuration now.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
There are three resource types used in CUBRID. The first one is the link
identifier for a database connection, the second is the a resource which
holds the result of a query, and the third a resource which holds the
query results of BLOB/CLOB data types.
connection identifier
A connection identifier returned by cubrid_connect() and
cubrid_connect_with_url().
request identifier
A request identifier returned by cubrid_prepare() and cubrid_execute().
LOB identifier
A LOB identifier returned by cubrid_lob_get().
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
The following constants can be used when executing SQL statement. They can
be passed to cubrid_prepare() and cubrid_execute().
CUBRID SQL execution flags
Constant Description
CUBRID_INCLUDE_OID Determine whether to get OID during query execution.
CUBRID_ASYNC Execute the query in asynchronous mode.
CUBRID_EXEC_QUERY_ALL Execute the query in synchronous mode. This flag
must be set when executing multiple SQL statements.
The following constants can be used when fetching the results to specify
fetch behaviour. They can be passed to cubrid_fetch() and
cubrid_fetch_array().
CUBRID fetch flags
Constant Description
CUBRID_NUM Get query result as a numeric array (0-default).
CUBRID_ASSOC Get query result as an associative array.
CUBRID_BOTH Get query result as both numeric and associative arrays
(default value).
CUBRID_OBJECT Get query result an object.
The following constants can be used when positioning the cursor in query
results. They can be passed to or returned by cubrid_move_cursor().
CUBRID cursor position flags
Constant Description
CUBRID_CURSOR_FIRST Move current cursor to the first position in the
result.
CUBRID_CURSOR_CURRENT Move current cursor as a default value if the origin
is not specified.
CUBRID_CURSOR_LAST Move current cursor to the last position in the
result.
CUBRID_CURSOR_SUCCESS Returned value of cubrid_move_cursor() function in
case of success.
CUBRID_NO_MORE_DATA Returned value of cubrid_move_cursor() function in
case of failure.
CUBRID_CURSOR_ERROR Returned value of cubrid_move_cursor() function in
case of failure.
The following constants can be used when setting the auto-commit mode for
the database connection. They can be passed to cubrid_set_autocommit() or
returned by cubrid_get_autocommit().
CUBRID auto-commit mode flags
Constant Description
CUBRID_AUTOCOMMIT_TRUE Enable the auto-commit mode.
CUBRID_AUTOCOMMIT_FALSE Disable the auto-commit mode.
The following constants can be used when setting the database parameter.
They can be passed to cubrid_set_db_parameter().
CUBRID parameter flags
Constant Description
CUBRID_PARAM_ISOLATION_LEVEL Transaction isolation level for the database
connection.
CUBRID_PARAM_LOCK_TIMEOUT Transaction timeout in seconds.
The following constants can be used when setting the transaction isolation
level. They can be passed to cubrid_set_db_parameter() or returned by
cubrid_get_db_parameter().
CUBRID isolation level flags
Constant Description
The lowest isolation level (1). A
dirty, non-repeatable or phantom read
TRAN_COMMIT_CLASS_UNCOMMIT_INSTANCE may occur for the tuple and a
non-repeatable read may occur for the
table as well.
A relatively low isolation level (2).
TRAN_COMMIT_CLASS_COMMIT_INSTANCE A dirty read does not occur, but
non-repeatable or phantom read may
occur.
The default isolation of CUBRID (3). A
dirty, non-repeatable or phantom read
TRAN_REP_CLASS_UNCOMMIT_INSTANCE may occur for the tuple, but
repeatable read is ensured for the
table.
A relatively low isolation level (4).
TRAN_REP_CLASS_COMMIT_INSTANCE A dirty read does not occur, but
non-repeatable or phantom read may.
A relatively high isolation level (5).
TRAN_REP_CLASS_REP_INSTANCE A dirty or non-repeatable read does
not occur, but a phantom read may.
The highest isolation level (6).
TRAN_SERIALIZABLE Problems concerning concurrency (e.g.
dirty read, non-repeatable read,
phantom read, etc.) do not occur.
The following constants can be used when getting schema information. They
can be passed to cubrid_schema().
CUBRID schema flags
Constant Description
CUBRID_SCH_CLASS Get name and type of table in CUBRID.
CUBRID_SCH_VCLASS Get name and type of view in CUBRID.
CUBRID_SCH_QUERY_SPEC Get the query definition of view.
CUBRID_SCH_ATTRIBUTE Get the attributes of table column.
CUBRID_SCH_CLASS_ATTRIBUTE Get the attributes of table.
Get the instance method. The instance method
is a method called by a class instance. It
CUBRID_SCH_METHOD is used more often than the class method
because most operations are executed in the
instance.
Get the class method. The class method is a
method called by a class object. It is
CUBRID_SCH_CLASS_METHOD usually used to create a new class instance
or to initialize it. It is also used to
access or update class attributes.
CUBRID_SCH_METHOD_FILE Get the information of the file where the
method of the table is defined.
CUBRID_SCH_SUPERCLASS Get the name and type of table which table
inherites attributes from.
CUBRID_SCH_SUBCLASS Get the name and type of table which
inherites attributes from this table.
CUBRID_SCH_CONSTRAINT Get the table constraints.
CUBRID_SCH_TRIGGER Get the table triggers.
CUBRID_SCH_CLASS_PRIVILEGE Get the privilege information of table.
CUBRID_SCH_ATTR_PRIVILEGE Get the privilege information of column.
CUBRID_SCH_DIRECT_SUPER_CLASS Get the direct super table of table.
CUBRID_SCH_PRIMARY_KEY Get the table primary key.
CUBRID_SCH_IMPORTED_KEYS Get imported keys of table.
CUBRID_SCH_EXPORTED_KEYS Get exported keys of table.
CUBRID_SCH_CROSS_REFERENCE Get reference relationship of tow tables.
The following constants can be used when reporting errors. They can be
returned from cubrid_error_code_facility().
CUBRID error facility code
Constant Description
CUBRID_FACILITY_DBMS The error occured in CUBRID dbms.
CUBRID_FACILITY_CAS The error occured in CUBRID broker cas.
CUBRID_FACILITY_CCI The error occured in CUBRID cci.
CUBRID_FACILITY_CLIENT The error occured in CUBRID PHP client.
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
The following is a simple example that establishes a connection between
PHP and CUBRID. This section will cover the most basic and notable
features. The following code required to connect to CUBRID database, which
means CUBRID Server and CUBRID Broker have to be running.
The example below uses the demodb database as an examples. By default it
is created during the installation. Make sure it has been created.
Example #1 Example of Data Retrieval
");
while (list($key, $colname) = each($columns)) {
echo("$colname ");
}
echo("");
/**
* Get the results from the result set.
*/
while ($row = cubrid_fetch($result)) {
echo("");
for ($i = 0; $i < $num_fields; $i++) {
echo("");
echo($row[$i]);
echo(" ");
}
echo(" ");
}
}
/**
* The PHP module in the CUBRID runs in a 3-tier architecture. Even when
* calling SELECT for transaction processing, it is processed as a part
* of the transaction. Therefore, the transaction needs to be rolled back
* by calling commit or rollback even though SELECT was called for smooth
* performance.
*/
cubrid_commit($cubrid_con);
cubrid_disconnect($cubrid_con);
?>
Example #2 Example of Data Insertion
----------------------------------------------------------------------
----------------------------------------------------------------------
CUBRID Functions
----------------------------------------------------------------------
cubrid_affected_rows
(PECL CUBRID >= 8.3.0)
cubrid_affected_rows - Return the number of rows affected by the last SQL
statement
Description
int cubrid_affected_rows ([ resource $result ] )
The cubrid_affected_rows() function is used to get the number of rows
affected by the SQL statement (INSERT, DELETE, UPDATE).
Parameters
result
Result. If the result is not specified, the last result is
assumed.
Return Values
Number of rows affected by the SQL statement, when process is successful.
-1, when SQL statement is not INSERT, DELETE or UPDATE.
FALSE, when the request identifier is not specified, and there is no last
request.
Examples
Example #1 cubrid_affected_rows() example
The above example will output:
int(5)
See Also
* cubrid_execute() - Execute a prepared SQL statement
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_bind
(PECL CUBRID >= 8.3.0)
cubrid_bind - Bind variables to a prepared statement as parameters
Description
bool cubrid_bind ( resource $req_identifier , mixed $bind_param , mixed
$bind_value [, string $bind_value_type ] )
The cubrid_bind() function is used to bind values to a corresponding named
or question mark placeholder in the SQL statement that was passed to
cubrid_prepare(). If bind_value_type is not given, string will be the
default.
Note:
If the type of data to be bound is BLOB/CLOB, CUBRID will try to map the
data as a PHP stream. If the actually bind value type is not stream,
CUBRID will convert it to string, and use it as the full path and file
name of a file on the client filesystem.
The following table shows the types of substitute values.
CUBRID Bind Date Types
Support Bind Type Corresponding SQL Type
Supported STRING CHAR, VARCHAR
NCHAR NCHAR, NVARCHAR
BIT BIT, VARBIT
NUMERIC or NUMBER SHORT, INT, NUMERIC
FLOAT FLOAT
DOUBLE DOUBLE
TIME TIME
DATE DATE
TIMESTAMP TIMESTAMP
OBJECT OBJECT
BLOB BLOB
CLOB CLOB
NULL NULL
Not supported SET SET
MULTISET MULTISET
SEQUENCE SEQUENCE
Parameters
req_identifier
Request identifier as a result of cubrid_prepare().
bind_param
Parameter identifier. For a prepared statement using named
placeholders, this will be a parameter name of the form :name
(Note that the name can only contain digit, alphabet, and
underscore, and it can not begin with digit. The name length can
not be longer than 32). For a prepared statement using question
mark placeholders, this will be the 1-indexed position of the
parameter.
bind_value
Actual value for binding.
bind_value_type
A type of the value to bind. (It is omitted by default. Thus,
system internally use string by default. However, you need to
specify the exact type of the value as an argument when they are
NCHAR, BIT, or BLOB/CLOB).
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Changelog
Version Description
8.4.0 Added named parameter support; When binding the LOB data type, it
can directly binding the path name of a file.
8.3.1 Added BLOB/CLOB data types support.
Examples
Example #1 cubrid_bind() example
The above example will output:
--- Dream Team (1992 United States men's Olympic basketball team) ---
Stockton John
Robinson David
Pippen Scottie
Mullin C.
Malone Karl
Laettner C.
Jordan Michael
Johnson Earvin
Ewing Patrick
Drexler Clyde
Bird Larry
Barkley Charles
Example #2 cubrid_bind() named parameter example
The above example will output:
Medal Type Stadium where most medals were ever won
Gold Olympic Aquatic Centre
Silver Olympic Aquatic Centre
Bronze Sydney Convention and Exhibition Centre
Example #3 cubrid_bind() BLOB/CLOB example
Example #4 cubrid_bind() BLOB/CLOB example
See Also
* cubrid_execute() - Execute a prepared SQL statement
* cubrid_prepare() - Prepare an SQL statement for execution
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_close_prepare
(PECL CUBRID >= 8.3.0)
cubrid_close_prepare - Close the request handle
Description
int cubrid_close_prepare ( resource $req_identifier )
The cubrid_close_prepare() function closes the request handle given by the
req_identifier argument, and releases the memory region related to the
handle.
Parameters
req_identifier
Request identifier.
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_close_prepare() example
See Also
* cubrid_execute() - Execute a prepared SQL statement
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_close_request
(PECL CUBRID >= 8.3.0)
cubrid_close_request - Close the request handle
Description
bool cubrid_close_request ( resource $req_identifier )
The cubrid_close_request() function closes the request handle given by the
req_identifier argument, and releases the memory region related to the
handle.
Parameters
req_identifier
Request identifier.
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_close_request() example
The above example will output:
host_year host_nation host_city opening_date closing_date mascot slogan
2004 Greece Athens 2004-8-13 2004-8-29 Athena Phevos Welcome Home
See Also
* cubrid_execute() - Execute a prepared SQL statement
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_col_get
(PECL CUBRID >= 8.3.0)
cubrid_col_get - Get contents of collection type column using OID
Description
array cubrid_col_get ( resource $conn_identifier , string $oid , string
$attr_name )
The cubrid_col_get() function is used to get contents of the elements of
the collection type (set, multiset, sequence) attribute you requested as
an array.
Parameters
conn_identifier
Connection identifier.
oid
OID of the instance that you want to read.
attr_name
Attribute name that you want to read from the instance.
Return Values
Array (0-based numerical array) containing the elements you requested,
when process is successful;
FALSE (to distinguish the error from the situation of attribute having
empty collection or NULL, in case of error, a warning message is shown; in
such case you can check the error by using cubrid_error_code()), when
process is unsuccessful.
Examples
Example #1 cubrid_col_get() example
The above example will output:
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
}
int(3)
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_col_size
(PECL CUBRID >= 8.3.0)
cubrid_col_size - Get the number of elements in collection type column
using OID
Description
int cubrid_col_size ( resource $conn_identifier , string $oid , string
$attr_name )
The cubrid_col_size() function is used to get the number of elements in a
collection type (set, multiset, sequence) attribute.
Parameters
conn_identifier
Connection identifier.
oid
OID the instance that you want to work with.
attr_name
Name of the attribute that you want to work with.
Return Values
Number of elements, when process is successful.
FALSE, when process is unsuccessful.
Changelog
Version Description
8.3.1 Change return value: when process is unsuccessful, return false,
not -1.
Examples
Example #1 cubrid_col_size() example
The above example will output:
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
}
int(3)
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_column_names
(PECL CUBRID >= 8.3.0)
cubrid_column_names - Get the column names in result
Description
array cubrid_column_names ( resource $req_identifier )
The cubrid_column_names() function is used to get the column names of the
query result by using req_identifier.
Parameters
req_identifier
Request identifier.
Return Values
Array of string which containing column names, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_column_names() example
The above example will output:
Column Names Column Types Column Maxlen
host_year integer 11
event_code integer 11
athlete_code integer 11
stadium_code integer 11
nation_code char(3) 3
medal char(1) 1
game_date date 10
See Also
* cubrid_prepare() - Prepare an SQL statement for execution
* cubrid_execute() - Execute a prepared SQL statement
* cubrid_column_types() - Get column types in result
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_column_types
(PECL CUBRID >= 8.3.0)
cubrid_column_types - Get column types in result
Description
array cubrid_column_types ( resource $req_identifier )
The cubrid_column_types() function gets column types of query results by
using req_identifier.
Parameters
req_identifier
Request identifier.
Return Values
Array of string which containing column types, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_column_types() example
The above example will output:
Column Names Column Types Column Maxlen
host_year integer 11
event_code integer 11
athlete_code integer 11
stadium_code integer 11
nation_code char(3) 3
medal char(1) 1
game_date date 10
See Also
* cubrid_column_names() - Get the column names in result
* cubrid_prepare() - Prepare an SQL statement for execution
* cubrid_execute() - Execute a prepared SQL statement
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_commit
(PECL CUBRID >= 8.3.0)
cubrid_commit - Commit a transaction
Description
bool cubrid_commit ( resource $conn_identifier )
The cubrid_commit() function is used to execute commit on the transaction
pointed by conn_identifier, currently on progress. Connection to the
server is closed after the cubrid_commit() function is called; the
connection handle is still valid, however.
In CUBRID PHP, an auto-commit mode is disabled by default for transaction
management, and you can set it by using cubrid_set_autocommit(), and get
its status by using cubrid_get_autocommit(). Before you start a
transaction, remember to disable the auto-commit mode.
Parameters
conn_identifier
Connection identifier.
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_commit() example
The above example will output:
P01 Abatis Publishers New York NY USA
P02 Core Dump Books San Francisco CA USA
P03 Schadenfreude Press Hamburg Germany
P04 Tenterhooks Press Berkeley CA USA
See Also
* cubrid_rollback() - Roll back a transaction
* cubrid_get_autocommit() - Get auto-commit mode of the connection
* cubrid_set_autocommit() - Set autocommit mode of the connection
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_connect_with_url
(PECL CUBRID >= 8.3.0)
cubrid_connect_with_url - Establish the environment for connecting to
CUBRID server
Description
resource cubrid_connect_with_url ( string $conn_url [, string $userid [,
string $passwd ]] )
The cubrid_connect_with_url() function is used to establish the
environment for connecting to your server by using connection information
passed with an url string argument. If the HA feature is enabled in
CUBRID, you must specify the connection information of the standby server,
which is used for failover when failure occurs, in the url string argument
of this function. If the user name and password is not given, then the
"PUBLIC" connection will be made by default.
::=
cci:CUBRID:::::[?]
::= [& ::=
autocommit= ::=
: [,:] :=
HOSTNAME | IP_ADDR := SECOND
* host : A host name or IP address of the master database
* db_name : A name of the database
* db_user : A name of the database user
* db_password : A database user password
* autocommit : The database connection auto-commit mode
* alhosts: Specifies the broker information of the standby server, which
is used for failover when it is impossible to connect to the active
server. You can specify multiple brokers for failover, and the
connection to the brokers is attempted in the order listed in alhosts
* rctime : An interval between the attempts to connect to the active
broker in which failure occurred. After a failure occurs, the system
connects to the broker specified by althosts (failover), terminates
the transaction, and then attempts to connect to the active broker of
the master database at every rctime. The default value is 600 seconds.
Parameters
conn_url
A character string that contains server connection information.
userid
User name for the database.
passwd
User password.
Return Values
Connection identifier, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_connect_with_url() url without properties example
Example #2 cubrid_connect_with_url() url with properties example
See Also
* cubrid_connect() - Open a connection to a CUBRID Server
* cubrid_disconnect() - Close a database connection
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_connect
(PECL CUBRID >= 8.3.0)
cubrid_connect - Open a connection to a CUBRID Server
Description
resource cubrid_connect ( string $host , int $port , string $dbname [,
string $userid [, string $passwd ]] )
The cubrid_connect() function is used to establish the environment for
connecting to your server by using your server address, port number,
database name, user name, and password. If the user name and password is
not given, then the "PUBLIC" connection will be made by default.
Parameters
host
Host name or IP address of CUBRID CAS server.
port
Port number of CUBRID CAS server (BROKER_PORT configured in
$CUBRID/conf/cubrid_broker.conf).
dbname
Name of database.
userid
User name for the database.
passwd
User password.
Return Values
Connection identifier, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_connect() example
The above example will output:
CUBRID PHP Version: 8.3.1.0005
PARAM_ISOLATION_LEVEL 3
LOCK_TIMEOUT -1
MAX_STRING_LENGTH 1073741823
PARAM_AUTO_COMMIT 0
Server Info: 8.3.1.0173
Client Info: 8.3.1
CUBRID Charset: iso8859-1
See Also
* cubrid_connect_with_url() - Establish the environment for connecting
to CUBRID server
* cubrid_disconnect() - Close a database connection
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_current_oid
(PECL CUBRID >= 8.3.0)
cubrid_current_oid - Get OID of the current cursor location
Description
string cubrid_current_oid ( resource $req_identifier )
The cubrid_current_oid() function is used to get the oid of the current
cursor location from the query result. To use cubrid_current_oid(), the
query executed must be a updatable query, and the CUBRID_INCLUDE_OID
option must be included during the query execution.
Parameters
req_identifier
Request identifier.
Return Values
Oid of current cursor location, when process is successful
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_current_oid() example
The above example will output:
Array
(
[s_name] => X
[f_name] => Mixed
)
See Also
* cubrid_execute() - Execute a prepared SQL statement
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_disconnect
(PECL CUBRID >= 8.3.0)
cubrid_disconnect - Close a database connection
Description
bool cubrid_disconnect ( resource $conn_identifier )
The cubrid_disconnect() function closes the connection handle and
disconnects from server. If there exists any request handle not closed yet
at this point, it will be closed.
Parameters
conn_identifier
Connection identifier.
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_disconnect() example
The above example will output:
CUBRID PHP Version: 8.3.1.0005
PARAM_ISOLATION_LEVEL 3
LOCK_TIMEOUT -1
MAX_STRING_LENGTH 1073741823
PARAM_AUTO_COMMIT 0
Server Info: 8.3.1.0173
Client Info: 8.3.1
CUBRID Charset: iso8859-1
See Also
* cubrid_connect() - Open a connection to a CUBRID Server
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_drop
(PECL CUBRID >= 8.3.0)
cubrid_drop - Delete an instance using OID
Description
bool cubrid_drop ( resource $conn_identifier , string $oid )
The cubrid_drop() function is used to delete an instance from database by
using oid.
Parameters
conn_identifier
Connection identifier.
oid
Oid of the instance that you want to delete.
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_drop() example
The above example will output:
--- Before Drop: ---
array(4) {
["a"]=>
string(1) "1"
["b"]=>
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
}
["c"]=>
array(4) {
[0]=>
string(2) "11"
[1]=>
string(2) "22"
[2]=>
string(2) "33"
[3]=>
string(3) "333"
}
["d"]=>
string(10) "a "
}
--- After Drop: ---
array(4) {
["a"]=>
string(1) "2"
["b"]=>
array(3) {
[0]=>
string(1) "4"
[1]=>
string(1) "5"
[2]=>
string(1) "7"
}
["c"]=>
array(4) {
[0]=>
string(2) "44"
[1]=>
string(2) "55"
[2]=>
string(2) "66"
[3]=>
string(3) "666"
}
["d"]=>
string(10) "b "
}
See Also
* cubrid_is_instance() - Check whether the instance pointed by OID
exists
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_error_code_facility
(PECL CUBRID >= 8.3.0)
cubrid_error_code_facility - Get the facility code of error
Description
int cubrid_error_code_facility ( void )
The cubrid_error_code_facility() function is used to get the facility code
(level in which the error occurred) from the error code of the error that
occurred during the API execution. Usually, you can get the error code
when API returns false as its return value.
Parameters
This function has no parameters.
Return Values
Facility code of the error code that occurred: CUBRID_FACILITY_DBMS,
CUBRID_FACILITY_CAS, CUBRID_FACILITY_CCI, CUBRID_FACILITY_CLIENT
Examples
Example #1 cubrid_error_code_facility() example
The above example will output:
Error facility: 1
Error code: -493
Error msg: Syntax: syntax error, unexpected UNKNOWN
See Also
* cubrid_error_code() - Get error code for the most recent function call
* cubrid_error_msg() - Get last error message for the most recent
function call
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_error_code
(PECL CUBRID >= 8.3.0)
cubrid_error_code - Get error code for the most recent function call
Description
int cubrid_error_code ( void )
The cubrid_error_code() function is used to get the error code of the
error that occurred during the API execution. Usually, it gets the error
code when API returns false as its return value.
Parameters
This function has no parameters.
Return Values
Error code of the error that occurred, or 0 (zero) if no error occurred.
Examples
Example #1 cubrid_error_code() example
The above example will output:
Error facility: 4
Error code: -2015
Error msg: Some parameter not binded
See Also
* cubrid_error_code_facility() - Get the facility code of error
* cubrid_error_msg() - Get last error message for the most recent
function call
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_error_msg
(PECL CUBRID >= 8.3.0)
cubrid_error_msg - Get last error message for the most recent function
call
Description
string cubrid_error_msg ( void )
The cubrid_error_msg() function is used to get the error message that
occurred during the use of CUBRID API. Usually, it gets error message when
API returns false as its return value.
Parameters
This function has no parameters.
Return Values
Error message that occurred.
Examples
Example #1 cubrid_error_msg() example
The above example will output:
Error facility: 2
Error code: -1015
Error msg: Invalid T_CCI_SCH_TYPE value
See Also
* cubrid_error_code() - Get error code for the most recent function call
* cubrid_error_code_facility() - Get the facility code of error
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_execute
(PECL CUBRID >= 8.3.0)
cubrid_execute - Execute a prepared SQL statement
Description
resource cubrid_execute ( resource $conn_identifier , string $sql [, int
$option ] )
bool cubrid_execute ( resource $request_identifier [, int $option ] )
The cubrid_execute() function is used to execute the given SQL statement.
It executes the query by using conn_identifier and SQL, and then returns
the request identifier created. It is used for simple execution of query,
where the parameter binding is not needed. In addition, the
cubrid_execute() function is used to execute the prepared statement by
means of cubrid_prepare() and cubrid_bind(). At this time, you need to
specify arguments of request_identifier and option.
The option is used to determine whether to get OID after query execution
and whether to execute the query in synchronous or asynchronous mode.
CUBRID_INCLUDE_OID and CUBRID_ASYNC (or CUBRID_EXEC_QUERY_ALL if you want
to execute multiple SQL statements) can be specified by using a bitwise OR
operator. If not specified, neither of them isselected. If the flag
CUBRID_EXEC_QUERY_ALL is set, a synchronous mode (sync_mode) is used to
retrieve query results, and in such cases the following rules are applied:
* The return value is the result of the first query.
* If an error occurs in any query, the execution is processed as a
failure.
* For a query composed of in a query composed of q1 q2 q3 if an error
occurs in q2 after q1 succeeds the execution, the result of q1 remains
valid. That is, the previous successful query executions are not
rolled back when an error occurs.
* If a query is executed successfully, the result of the second query
can be obtained using cubrid_next_result().
If the first argument is request_identifier to execute the
cubrid_prepare() function, you can specify an option, CUBRID_ASYNC only.
Parameters
conn_identifier
Connection identifier.
sql
SQL to be executed.
option
Query execution option CUBRID_INCLUDE_OID, CUBRID_ASYNC,
CUBRID_EXEC_QUERY_ALL.
request_identifier
cubrid_prepare() identifier.
Return Values
Request identifier, when process is successful and first param is
conn_identifier; TRUE, when process is successful and first argument is
request_identifier.
FALSE, when process is unsuccessful.
Changelog
Version Description
8.4.0 Add new option CUBRID_EXEC_QUERY_ALL.
Examples
Example #1 cubrid_execute() example
The above example will output:
athlete host_year score unit
Phelps Michael 2004 51.25 time
See Also
* cubrid_prepare() - Prepare an SQL statement for execution
* cubrid_bind() - Bind variables to a prepared statement as parameters
* cubrid_next_result() - Get result of next query when executing
multiple SQL statements
* cubrid_close_request() - Close the request handle
* cubrid_commit() - Commit a transaction
* cubrid_rollback() - Roll back a transaction
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_fetch
(PECL CUBRID >= 8.3.0)
cubrid_fetch - Fetch the next row from a result set
Description
mixed cubrid_fetch ( resource $result [, int $type = CUBRID_BOTH ] )
The cubrid_fetch() function is used to get a single row from the query
result. The cursor automatically moves to the next row after getting the
result.
Parameters
result
result comes from a call to cubrid_execute()
type
Array type of the fetched result CUBRID_NUM, CUBRID_ASSOC,
CUBRID_BOTH, CUBRID_OBJECT.
Return Values
Result array or object, when process is successful.
FALSE, when process is unsuccessful.
The result can be received either as an array or as an object, and you can
decide which data type to use by setting the type argument. The type
variable can be set to one of the following values:
* CUBRID_NUM : Numerical array (0-based)
* CUBRID_ASSOC : Associative array
* CUBRID_BOTH : Numerical & Associative array (default)
* CUBRID_OBJECT : object that has the attribute name as the column name
of query result
When type argument is omitted, the result will be received using
CUBRID_BOTH option as default. When you want to receive query result in
object data type, the column name of the result must obey the naming rules
for identifiers in PHP. For example, column name such as "count(*)" cannot
be received in object type.
Examples
Example #1 cubrid_fetch() example
10000");
printf("%-40s %-10s %-6s %-20s\n", "name", "area", "seats", "address");
while ($row = cubrid_fetch($req)) {
printf("%-40s %-10s %-6s %-20s\n",
$row["name"], $row["area"], $row["seats"], $row["address"]);
}
cubrid_close_request($req);
cubrid_disconnect($conn);
?>
The above example will output:
name area seats address
Panathinaiko Stadium 86300.00 50000 Athens, Greece
Olympic Stadium 54700.00 13000 Athens, Greece
Olympic Indoor Hall 34100.00 18800 Athens, Greece
Olympic Hall 52400.00 21000 Athens, Greece
Olympic Aquatic Centre 42500.00 11500 Athens, Greece
Markopoulo Olympic Equestrian Centre 64000.00 15000 Markopoulo, Athens, Greece
Faliro Coastal Zone Olympic Complex 34650.00 12171 Faliro, Athens, Greece
Athens Olympic Stadium 120400.00 71030 Maroussi, Athens, Greece
Ano Liossia 34000.00 12000 Ano Liosia, Athens, Greece
See Also
* cubrid_execute() - Execute a prepared SQL statement
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_free_result
(PECL CUBRID >= 8.3.0)
cubrid_free_result - Free the memory occupied by the result data
Description
bool cubrid_free_result ( resource $req_identifier )
This function frees the memory occupied by the result data. It returns
TRUE on success or FALSE on failure. Note that it can only frees the
client fetch buffer now, and if you want free all memory, use function
cubrid_close_request().
Parameters
req_identifier
This is the request identifier.
Return Values
TRUE on success.
FALSE on failure.
Examples
Example #1 cubrid_free_result() example
The above example will output:
array(5) {
["event_code"]=>
string(5) "20005"
["athlete"]=>
string(12) "Hayes Joanna"
["host_year"]=>
string(4) "2004"
["score"]=>
string(5) "12.37"
["unit"]=>
string(4) "time"
}
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_get_autocommit
(PECL CUBRID >= 8.4.0)
cubrid_get_autocommit - Get auto-commit mode of the connection
Description
bool cubrid_get_autocommit ( resource $conn_identifier )
The cubrid_get_autocommit() function is used to get the status of CUBRID
database connection auto-commit mode.
In CUBRID PHP, an auto-commit mode is disabled by default for transaction
management.
Parameters
conn_identifier
Connection identifier.
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
See Also
* cubrid_set_autocommit() - Set autocommit mode of the connection
* cubrid_commit() - Commit a transaction
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_get_charset
(PECL CUBRID >= 8.3.0)
cubrid_get_charset - Return the current CUBRID connection charset
Description
string cubrid_get_charset ( resource $conn_identifier )
This function returns This function returns the current CUBRID connection
charset.
Parameters
conn_identifier
The CUBRID connection.
Return Values
A string that represents the CUBRID connection charset; on success.
FALSE on failure.
Examples
Example #1 cubrid_get_charset() example
The above example will output:
CUBRID PHP Version: 8.3.1.0005
PARAM_ISOLATION_LEVEL 3
LOCK_TIMEOUT -1
MAX_STRING_LENGTH 1073741823
PARAM_AUTO_COMMIT 0
Server Info: 8.3.1.0173
Client Info: 8.3.1
CUBRID Charset: iso8859-1
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_get_class_name
(PECL CUBRID >= 8.3.0)
cubrid_get_class_name - Get the class name using OID
Description
string cubrid_get_class_name ( resource $conn_identifier , string $oid )
The cubrid_get_class_name() function is used to get the class name from
oid.
Parameters
conn_identifier
Connection identifier.
oid
OID of the instance that you want to check the existence.
Return Values
Class name when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_get_class_name() example
The above example will output:
code
See Also
* cubrid_is_instance() - Check whether the instance pointed by OID
exists
* cubrid_drop() - Delete an instance using OID
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_get_client_info
(PECL CUBRID >= 8.3.0)
cubrid_get_client_info - Return the client library version
Description
string cubrid_get_client_info ( void )
This function returns a string that represents the client library version.
Parameters
Return Values
A string that represents the client library version; on success.
FALSE on failure.
Examples
Example #1 cubrid_get_client_info() example
The above example will output:
CUBRID PHP Version: 8.3.1.0005
PARAM_ISOLATION_LEVEL 3
LOCK_TIMEOUT -1
MAX_STRING_LENGTH 1073741823
PARAM_AUTO_COMMIT 0
Server Info: 8.3.1.0173
Client Info: 8.3.1
CUBRID Charset: iso8859-1
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_get_db_parameter
(PECL CUBRID >= 8.3.0)
cubrid_get_db_parameter - Returns the CUBRID database parameters
Description
array cubrid_get_db_parameter ( resource $conn_identifier )
This function returns the CUBRID database parameters or it returns FALSE
on failure. It returns an associative array with the values for the
following parameters:
* PARAM_ISOLATION_LEVEL
* PARAM_LOCK_TIMEOUT
* PARAM_MAX_STRING_LENGTH
* PARAM_AUTO_COMMIT
Database parameters
Parameter Description
PARAM_ISOLATION_LEVEL The transaction isolation level.
CUBRID provides the lock timeout feature, which sets
the waiting time (in seconds) for the lock until the
LOCK_TIMEOUT transaction lock setting is allowed. The default
value of the lock_timeout_in_secs parameter is -1,
which means the application client will wait
indefinitely until the transaction lock is allowed.
In CUBRID PHP, an auto-commit mode is disabled by
PARAM_AUTO_COMMIT default for transaction management. It can be set by
using cubrid_set_autocommit().
The following table shows the isolation levels from 1 to 6. It consists of
table schema (row) and isolation level:
Levels of Isolation Supported by CUBRID
Name Description
In this isolation level, problems concerning
SERIALIZABLE (6) concurrency (e.g. dirty read, non-repeatable
read, phantom read, etc.) do not occur.
Another transaction T2 cannot update the schema
REPEATABLE READ CLASS with of table A while transaction T1 is viewing
REPEATABLE READ INSTANCES table A. Transaction T1 may experience phantom
(5) read for the record R that was inserted by
another transaction T2 when it is repeatedly
retrieving a specific record.
Another transaction T2 cannot update the schema
REPEATABLE READ CLASS with of table A while transaction T1 is viewing
READ COMMITTED INSTANCES table A. Transaction T1 may experience R read
(or CURSOR STABILITY) (4) (non-repeatable read) that was updated and
committed by another transaction T2 when it is
repeatedly retrieving the record R.
Default isolation level. Another transaction T2
REPEATABLE READ CLASS with cannot update the schema of table A while
READ UNCOMMITTED INSTANCES transaction T1 is viewing table A. Transaction
(3) T1 may experience R' read (dirty read) for the
record that was updated but not committed by
another transaction T2.
Transaction T1 may experience A' read
(non-repeatable read) for the table that was
READ COMMITTED CLASS with updated and committed by another transaction T2
READ COMMITTED INSTANCES while it is viewing table A repeatedly.
(2) Transaction T1 may experience R' read
(non-repeatable read) for the record that was
updated and committed by another transaction T2
while it is retrieving the record R repeatedly.
Transaction T1 may experience A' read
(non-repeatable read) for the table that was
READ COMMITTED CLASS with updated and committed by another transaction T2
READ UNCOMMITTED INSTANCES while it is repeatedly viewing table A.
(1) Transaction T1 may experience R' read (dirty
read) for the record that was updated but not
committed by another transaction T2.
Parameters
conn_identifier
The CUBRID connection. If the connection identifier is not
specified, the last link opened by cubrid_connect() is assumed.
Return Values
An associative array with CUBRID database parameters; on success.
FALSE on failure.
Changelog
Version Description
8.4.0 Change LOCK_TIMEOUT to PARAM_LOCK_TIMEOUT, and MAX_STRING_LENGTH
to PARAM_MAX_STRING_LENGTH in result.
Examples
Example #1 cubrid_get_db_parameter() example
The above example will output:
CUBRID PHP Version: 8.3.1.0005
PARAM_ISOLATION_LEVEL 3
PARAM_LOCK_TIMEOUT -1
PARAM_MAX_STRING_LENGTH 1073741823
PARAM_AUTO_COMMIT 0
Server Info: 8.3.1.0173
Client Info: 8.3.1
CUBRID Charset: iso8859-1
See Also
* cubrid_set_db_parameter() - Sets the CUBRID database parameters
* cubrid_get_autocommit() - Get auto-commit mode of the connection
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_get_server_info
(PECL CUBRID >= 8.3.0)
cubrid_get_server_info - Return the CUBRID server version
Description
string cubrid_get_server_info ( resource $conn_identifier )
This function returns a string that represents the CUBRID server version.
Parameters
conn_identifier
The CUBRID connection.
Return Values
A string that represents the CUBRID server version; on success.
FALSE on failure.
Examples
Example #1 cubrid_get_server_info() example
The above example will output:
CUBRID PHP Version: 8.3.1.0005
PARAM_ISOLATION_LEVEL 3
LOCK_TIMEOUT -1
MAX_STRING_LENGTH 1073741823
PARAM_AUTO_COMMIT 0
Server Info: 8.3.1.0173
Client Info: 8.3.1
CUBRID Charset: iso8859-1
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_get
(PECL CUBRID >= 8.3.0)
cubrid_get - Get a column using OID
Description
mixed cubrid_get ( resource $conn_identifier , string $oid [, mixed $attr
] )
The cubrid_get() function is used to get the attribute of the instance of
the given oid. You can get single attribute by using string data type for
the attr argument, or many attributes by using array data type for the
attr argument.
Parameters
conn_identifier
Connection identifier.
oid
OID of the instance that you want to read.
attr
Name of the attribute that you want to read.
Return Values
Content of the requested attribute, when process is successful; When attr
is set with string data type, the result is returned as a string; when
attr is set with array data type (0-based numerical array), then the
result is returned in associative array. When attr is omitted, then all
attributes are received in array form.
FALSE when process is unsuccessful or result is NULL (If error occurs to
distinguish empty string from NULL, then it prints the warning message.
You can check the error by using cubrid_error_code())
Examples
Example #1 cubrid_get() example
The above example will output:
string(9) "{1, 2, 3}"
array(4) {
["a"]=>
string(1) "1"
["b"]=>
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
}
["c"]=>
array(4) {
[0]=>
string(2) "11"
[1]=>
string(2) "22"
[2]=>
string(2) "33"
[3]=>
string(3) "333"
}
["d"]=>
string(10) "a "
}
See Also
* cubrid_put() - Update a column using OID
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_insert_id
(PECL CUBRID >= 8.3.0)
cubrid_insert_id - Return the ID generated for the lastest updated
AUTO_INCREMENT column
Description
string cubrid_insert_id ([ resource $conn_identifier ] )
The cubrid_insert_id() function retrieves the ID generated for the
AUTO_INCREMENT column which is updated by the previous INSERT query. It
returns 0 if the previous query does not generate new rows, or FALSE on
failure.
Note:
CUBRID supports AUTO_INCREMENT for more than one columns in a table. In
most cases, there will be a single AUTO_INCREMENT column in a table. If
there are multiple AUTO_INCREMENT columns, this function should not be
used even if it will return a value.
Parameters
conn_identifier
The connection identifier previously obtained by a call to
cubrid_connect().
Return Values
A string representing the ID generated for an AUTO_INCREMENT column by the
previous query, on success.
0, if the previous query does not generate new rows.
FALSE on failure.
Changelog
Version Description
8.4.0 Change the return value from an array to string; Remove the first
parameter class_name.
Examples
Example #1 cubrid_insert_id() example
The above example will output:
string(2) "19"
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_is_instance
(PECL CUBRID >= 8.3.0)
cubrid_is_instance - Check whether the instance pointed by OID exists
Description
int cubrid_is_instance ( resource $conn_identifier , string $oid )
The cubrid_is_instance() function is used to check whether the instance
pointed by the given oid exists or not.
Parameters
conn_identifier
Connection identifier.
oid
OID of the instance that you want to check the existence.
Return Values
1, if such instance exists;
0, if such instance does not exist;
-1, in case of error
Examples
Example #1 cubrid_is_instance() example
The above example will output:
Instance pointed by @0|0|0 doesn't exist.
See Also
* cubrid_drop() - Delete an instance using OID
* cubrid_get_class_name() - Get the class name using OID
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_lob_close
(PECL CUBRID >= 8.3.1)
cubrid_lob_close - Close BLOB/CLOB data
Description
bool cubrid_lob_close ( array $lob_identifier_array )
cubrid_lob_close() is used to close all BLOB/CLOB returned from
cubrid_lob_get().
Parameters
lob_identifier_array
LOB identifier array return from cubrid_lob_get.
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_lob_close() example
See Also
* cubrid_lob_get() - Get BLOB/CLOB data
* cubrid_lob_size() - Get BLOB/CLOB data size
* cubrid_lob_export() - Export BLOB/CLOB data to file
* cubrid_lob_send() - Read BLOB/CLOB data and send straight to browser
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_lob_export
(PECL CUBRID >= 8.3.1)
cubrid_lob_export - Export BLOB/CLOB data to file
Description
bool cubrid_lob_export ( resource $conn_identifier , resource
$lob_identifier , string $path_name )
cubrid_lob_export() is used to get BLOB/CLOB data from CUBRID database,
and saves its contents to a file. To use this function, you must use
cubrid_lob_get() first to get BLOB/CLOB info from CUBRID.
Parameters
conn_identifier
Connection identifier.
lob_identifier
LOB identifier.
path_name
Path name of the file.
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_lob_export() example
See Also
* cubrid_lob_get() - Get BLOB/CLOB data
* cubrid_lob_close() - Close BLOB/CLOB data
* cubrid_lob_size() - Get BLOB/CLOB data size
* cubrid_lob_send() - Read BLOB/CLOB data and send straight to browser
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_lob_get
(PECL CUBRID >= 8.3.1)
cubrid_lob_get - Get BLOB/CLOB data
Description
array cubrid_lob_get ( resource $conn_identifier , string $sql )
cubrid_lob_get() is used to get BLOB/CLOB meta info from CUBRID database,
CUBRID gets BLOB/CLOB by executing the SQL statement, and returns all LOBs
as a resource array. Be sure that the SQL retrieves only one column and
its data type is BLOB or CLOB.
Remember to use cubrid_lob_close() to release the LOBs if you don't need
it any more.
Parameters
conn_identifier
Connection identifier.
sql
SQL statement to be executed.
Return Values
Return an array of LOB resources, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_lob_get() example
See Also
* cubrid_lob_close() - Close BLOB/CLOB data
* cubrid_lob_size() - Get BLOB/CLOB data size
* cubrid_lob_export() - Export BLOB/CLOB data to file
* cubrid_lob_send() - Read BLOB/CLOB data and send straight to browser
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_lob_send
(PECL CUBRID >= 8.3.1)
cubrid_lob_send - Read BLOB/CLOB data and send straight to browser
Description
bool cubrid_lob_send ( resource $conn_identifier , resource
$lob_identifier )
cubrid_lob_send() reads BLOB/CLOB data and passes it straight through to
the browser. To use this function, you must use cubrid_lob_get() first to
get BLOB/CLOB info from CUBRID.
Parameters
conn_identifier
Connection identifier.
lob_identifier
LOB identifier.
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_lob_send() example
See Also
* cubrid_lob_get() - Get BLOB/CLOB data
* cubrid_lob_close() - Close BLOB/CLOB data
* cubrid_lob_size() - Get BLOB/CLOB data size
* cubrid_lob_export() - Export BLOB/CLOB data to file
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_lob_size
(PECL CUBRID >= 8.3.1)
cubrid_lob_size - Get BLOB/CLOB data size
Description
string cubrid_lob_size ( resource $lob_identifier )
cubrid_lob_size() is used to get BLOB/CLOB data size.
Parameters
lob_identifier
LOB identifier.
Return Values
A string representing LOB data size, when process is successful.
FALSE, when process is unsuccessful.
Changelog
Version Description
8.4.0 Change return value type from int to string.
Examples
Example #1 cubrid_lob_size() example
See Also
* cubrid_lob_get() - Get BLOB/CLOB data
* cubrid_lob_close() - Close BLOB/CLOB data
* cubrid_lob_export() - Export BLOB/CLOB data to file
* cubrid_lob_send() - Read BLOB/CLOB data and send straight to browser
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_lock_read
(PECL CUBRID >= 8.3.0)
cubrid_lock_read - Set a read lock on the given OID
Description
bool cubrid_lock_read ( resource $conn_identifier , string $oid )
The cubrid_lock_read() function is used to put read lock on the instance
pointed by given oid.
Parameters
conn_identifier
Connection identifier.
oid
OID of the instance that you want to put read lock on.
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_lock_read() example
The above example will output:
string(9) "{1, 2, 3}"
array(4) {
["a"]=>
string(1) "1"
["b"]=>
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
}
["c"]=>
array(4) {
[0]=>
string(2) "11"
[1]=>
string(2) "22"
[2]=>
string(2) "33"
[3]=>
string(3) "333"
}
["d"]=>
string(10) "a "
}
See Also
* cubrid_lock_write() - Set a write lock on the given OID
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_lock_write
(PECL CUBRID >= 8.3.0)
cubrid_lock_write - Set a write lock on the given OID
Description
bool cubrid_lock_write ( resource $conn_identifier , string $oid )
The cubrid_lock_write() function is used to put write lock on the instance
pointed by the given oid.
Parameters
conn_identifier
Connection identifier.
oid
OID of the instance that you want to put write lock on.
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_lock_write() example
The above example will output:
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
}
array(3) {
[0]=>
string(1) "2"
[1]=>
string(1) "4"
[2]=>
string(1) "8"
}
See Also
* cubrid_lock_read() - Set a read lock on the given OID
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_move_cursor
(PECL CUBRID >= 8.3.0)
cubrid_move_cursor - Move the cursor in the result
Description
int cubrid_move_cursor ( resource $req_identifier , int $offset [, int
$origin = CUBRID_CURSOR_CURRENT ] )
The cubrid_move_cursor() function is used to move the current cursor
location of req_identifier by the value set in the offset argument, to the
direction set in the origin argument. To set the origin argument, you can
use CUBRID_CURSOR_FIRST for the first part of the result,
CUBRID_CURSOR_CURRENT for the current location of the result, or
CUBRID_CURSOR_LAST for the last part of the result. If origin argument is
not explicitly designated, then the function uses CUBRID_CURSOR_CURRENT as
its default value.
If the value of cursor movement range goes over the valid limit, then the
cursor moves to the next location after the valid range for the cursor.
For example, if you move 20 units in the result with the size of 10, then
the cursor will move to 11th place and return CUBRID_NO_MORE_DATA.
Parameters
req_identifier
Request identifier.
offset
Number of units you want to move the cursor.
origin
Location where you want to move the cursor from
CUBRID_CURSOR_FIRST, CUBRID_CURSOR_CURRENT, CUBRID_CURSOR_LAST.
Return Values
CUBRID_CURSOR_SUCCESS, when process is successful.
CUBRID_NO_MORE_DATA, when it is not a valid cursor location.
CUBRID_CURSOR_ERROR, in case of error.
Examples
Example #1 cubrid_move_cursor() example
The above example will output:
array(2) {
[0]=>
string(1) "G"
[1]=>
string(4) "Gold"
}
array(2) {
[0]=>
string(1) "X"
[1]=>
string(5) "Mixed"
}
array(2) {
[0]=>
string(1) "M"
[1]=>
string(3) "Man"
}
See Also
* cubrid_execute() - Execute a prepared SQL statement
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_next_result
(PECL CUBRID >= 8.4.0)
cubrid_next_result - Get result of next query when executing multiple SQL
statements
Description
bool cubrid_next_result ( resource $result )
The cubrid_next_result() function is used to get results of next query if
multiple SQL statements are executed and CUBRID_EXEC_QUERY_ALL flag is set
upon cubrid_execute().
Parameters
result
result comes from a call to cubrid_execute()
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_next_result() example
The above example will output:
------------ get_result_info --------------------
Row count: 6
Column count: 2
Column Names Column Types Column Len
------------------------------------------------------------------------------
s_name char(1) 1
f_name varchar(6) 6
Last Column Name: f_name
Last Column Table: code
Last Column Type: varchar(6)
Last Column Len: 6
Second Column Flags:
------------ get_result_info --------------------
Row count: 4
Column count: 5
Column Names Column Types Column Len
------------------------------------------------------------------------------
event_code integer 11
athlete varchar(40) 40
host_year integer 11
score varchar(10) 10
unit varchar(5) 5
Last Column Name: unit
Last Column Table: history
Last Column Type: varchar(5)
Last Column Len: 5
Second Column Flags: not_null primary_key unique_key
See Also
* cubrid_execute() - Execute a prepared SQL statement
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_num_cols
(PECL CUBRID >= 8.3.0)
cubrid_num_cols - Return the number of columns in the result set
Description
int cubrid_num_cols ( resource $result )
The cubrid_num_cols() function is used to get the number of columns from
the query result. It can only be used when the query executed is a select
statement.
Parameters
result
Result.
Return Values
Number of columns, when process is successful.
-1, if SQL statement is not SELECT.
Examples
Example #1 cubrid_num_cols() example
The above example will output:
Row Num: 6
Column Num: 2
See Also
* cubrid_execute() - Execute a prepared SQL statement
* cubrid_num_rows() - Get the number of rows in the result set
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_num_rows
(PECL CUBRID >= 8.3.0)
cubrid_num_rows - Get the number of rows in the result set
Description
int cubrid_num_rows ( resource $result )
The cubrid_num_rows() function is used to get the number of rows from the
query result. You can use it only when the query executed is a select
statement. When you want to know such value for INSERT, UPDATE, or DELETE
query, you have to use the cubrid_affected_rows() function.
Note: The cubrid_num_rows() function can only be used for synchronous
query; it returns 0 when it is used for asynchronous query.
Parameters
result
Result.
Return Values
Number of rows, when process is successful.
0 when the query was done in async mode.
-1, if SQL statement is not SELECT.
Examples
Example #1 cubrid_num_rows() example
The above example will output:
Row Num: 6
Column Num: 2
See Also
* cubrid_execute() - Execute a prepared SQL statement
* cubrid_num_cols() - Return the number of columns in the result set
* cubrid_affected_rows() - Return the number of rows affected by the
last SQL statement
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_prepare
(PECL CUBRID >= 8.3.0)
cubrid_prepare - Prepare an SQL statement for execution
Description
resource cubrid_prepare ( resource $conn_identifier , string $prepare_stmt
[, int $option = 0 ] )
The cubrid_prepare() function is a sort of API which represents SQL
statements compiled previously to a given connection handle. This
pre-compiled SQL statement will be included in the cubrid_prepare().
Accordingly, you can use this statement effectively to execute several
times repeatedly or to process long data. Only a single statement can be
used and a parameter may put a question mark (?) to appropriate area in
the SQL statement. Add a parameter when you bind a value in the VALUES
clause of INSERT statement or in the WHERE clause. Note that it is allowed
to bind a value to a MARK(?) by the cubrid_bind() only.
Parameters
conn_identifier
Connection identifier.
prepare_stmt
Prepare query.
option
OID return option CUBRID_INCLUDE_OID.
Return Values
Request identifier, if process is successful;
FALSE, if process is unsuccessful.
Examples
Example #1 cubrid_prepare() example
The above example will output:
There are 27 event that exits in 2004 olympic but not in 2000. For example:
Event_code Event_name
----------------------------
20063 +91kg
20070 64kg
See Also
* cubrid_execute() - Execute a prepared SQL statement
* cubrid_bind() - Bind variables to a prepared statement as parameters
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_put
(PECL CUBRID >= 8.3.0)
cubrid_put - Update a column using OID
Description
int cubrid_put ( resource $conn_identifier , string $oid [, string $attr
], mixed $value )
The cubrid_put() function is used to update an attribute of the instance
of the given oid.
You can update single attribute by using string data type to set attr. In
such case, you can use integer, float-point, or string type data for the
value argument. To update multiple number of attributes, you can disregard
the attr argument, and set value argument with associative array data
type.
Parameters
conn_identifier
Connection identifier.
oid
OID of the instance that you want to update.
attr
Name of the attribute that you want to update.
value
New value that you want to assign to the attribute.
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_put() example
The above example will output:
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
}
array(3) {
[0]=>
string(1) "2"
[1]=>
string(1) "4"
[2]=>
string(1) "8"
}
See Also
* cubrid_get() - Get a column using OID
* cubrid_set_add() - Insert a single element to set type column using
OID
* cubrid_set_drop() - Delete an element from set type column using OID
* cubrid_seq_insert() - Insert an element to a sequence type column
using OID
* cubrid_seq_drop() - Delete an element from sequence type column using
OID
* cubrid_seq_put() - Update the element value of sequence type column
using OID
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_rollback
(PECL CUBRID >= 8.3.0)
cubrid_rollback - Roll back a transaction
Description
bool cubrid_rollback ( resource $conn_identifier )
The cubrid_rollback() function executes rollback on the transaction
pointed by conn_identifier, currently in progress.
Connection to server is closed after calling cubrid_rollback(). Connection
handle, however, is still valid.
Parameters
conn_identifier
Connection identifier.
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_rollback() example
The above example will output:
P01 Abatis Publishers New York NY USA
P02 Core Dump Books San Francisco CA USA
P03 Schadenfreude Press Hamburg Germany
P04 Tenterhooks Press Berkeley CA USA
See Also
* cubrid_commit() - Commit a transaction
* cubrid_disconnect() - Close a database connection
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_schema
(PECL CUBRID >= 8.3.0)
cubrid_schema - Get the requested schema information
Description
array cubrid_schema ( resource $conn_identifier , int $schema_type [,
string $class_name [, string $attr_name ]] )
The cubrid_schema() function is used to get the requested schema
information from database. You have to designate class_name, if you want
to get information on certain class, attr_name, if you want to get
information on certain attribute (can be used only with CUBRID_
SCH_ATTR_PRIVILEGE).
The result of the cubrid_schema function is returned as a two-dimensional
array (column (associative array) * row (numeric array)). The following
tables shows types of schema and the column structure of the result array
to be returned based on the schema type.
Result Composition of Each Type
Schema Column Column Name Value
Number
CUBRID_SCH_CLASS 1 NAME
0:system
2 TYPE class
1:vclass
2:class
CUBRID_SCH_VCLASS 1 NAME
2 TYPE 1:vclass
CUBRID_SCH_QUERY_SPEC 1 QUERY_SPEC
CUBRID_SCH_ATTRIBUTE / 1 ATTR_NAME
CUBRID_SCH_CLASS_ATTRIBUTE
2 DOMAIN
3 SCALE
4 PRECISION
5 INDEXED 1:indexed
6 NOT NULL 1:not null
7 SHARED 1:shared
8 UNIQUE 1:unique
9 DEFAULT
10 ATTR_ORDER base:1
11 CLASS_NAME
12 SOURCE_CLASS
13 IS_KEY 1:key
CUBRID_SCH_METHOD / 1 NAME
CUBRID_SCH_CLASS_METHOD
2 RET_DOMAIN
3 ARG_DOMAIN
CUBRID_SCH_METHOD_FILE 1 METHOD_FILE
CUBRID_SCH_SUPERCLASS /
CUBRID_SCH_DIRECT_SUPER_CLASS / 1 CLASS_NAME
CUBRID_SCH_SUBCLASS
0:system
2 TYPE class
1:vclass
2:class
0:unique
1:index
CUBRID_SCH_CONSTRAINT 1 TYPE 2:reverse
unique
3:reverse
index
2 NAME
3 ATTR_NAME
4 NUM_PAGES
5 NUM_KEYS
6 PRIMARY_KEY 1:primary key
7 KEY_ORDER base:1
CUBRID_SCH_TRIGGER 1 NAME
2 STATUS
3 EVENT
4 TARGET_CLASS
5 TARGET_ATTR
6 ACTION_TIME
7 ACTION
8 PRIORITY
9 CONDITION_TIME
10 CONDITION
CUBRID_SCH_CLASS_PRIVILEGE / 1 CLASS_NAME /
CUBRID_SCH_ATTR_PRIVILEGE ATTR_NAME
2 PRIVILEGE
3 GRANTABLE
CUBRID_SCH_PRIMARY_KEY 1 CLASS_NAME
2 ATTR_NAME
3 KEY_SEQ base:1
4 KEY_NAME
CUBRID_SCH_IMPORTED_KEYS /
CUBRID_SCH_EXPORTED_KEYS / 1 PKTABLE_NAME
CUBRID_SCH_CROSS_REFERENCE
2 PKCOLUMN_NAME
3 FKTABLE_NAME base:1
4 FKCOLUMN_NAME
5 KEY_SEQ base:1
0:cascade
6 UPDATE_ACTION 1:restrict
2:no action
3:set null
0:cascade
7 DELETE_ACTION 1:restrict
2:no action
3:set null
8 FK_NAME
9 PK_NAME
Parameters
conn_identifier
Connection identifier.
schema_type
Schema data that you want to know.
class_name
Class you want to know the schema of.
attr_name
Attribute you want to know the schema of.
Return Values
Array containing the schema information, when process is successful;
FALSE, when process is unsuccessful
Changelog
Version Description
8.3.1 Change return value: when process is unsuccessful, return false,
not -1.
Examples
Example #1 cubrid_schema() example
The above example will output:
--- Primary Key ---
array(3) {
[0]=>
array(4) {
["CLASS_NAME"]=>
string(4) "game"
["ATTR_NAME"]=>
string(12) "athlete_code"
["KEY_SEQ"]=>
string(1) "3"
["KEY_NAME"]=>
string(41) "pk_game_host_year_event_code_athlete_code"
}
[1]=>
array(4) {
["CLASS_NAME"]=>
string(4) "game"
["ATTR_NAME"]=>
string(10) "event_code"
["KEY_SEQ"]=>
string(1) "2"
["KEY_NAME"]=>
string(41) "pk_game_host_year_event_code_athlete_code"
}
[2]=>
array(4) {
["CLASS_NAME"]=>
string(4) "game"
["ATTR_NAME"]=>
string(9) "host_year"
["KEY_SEQ"]=>
string(1) "1"
["KEY_NAME"]=>
string(41) "pk_game_host_year_event_code_athlete_code"
}
}
--- Foreign Keys ---
array(2) {
[0]=>
array(9) {
["PKTABLE_NAME"]=>
string(7) "athlete"
["PKCOLUMN_NAME"]=>
string(4) "code"
["FKTABLE_NAME"]=>
string(4) "game"
["FKCOLUMN_NAME"]=>
string(12) "athlete_code"
["KEY_SEQ"]=>
string(1) "1"
["UPDATE_RULE"]=>
string(1) "1"
["DELETE_RULE"]=>
string(1) "1"
["FK_NAME"]=>
string(20) "fk_game_athlete_code"
["PK_NAME"]=>
string(15) "pk_athlete_code"
}
[1]=>
array(9) {
["PKTABLE_NAME"]=>
string(5) "event"
["PKCOLUMN_NAME"]=>
string(4) "code"
["FKTABLE_NAME"]=>
string(4) "game"
["FKCOLUMN_NAME"]=>
string(10) "event_code"
["KEY_SEQ"]=>
string(1) "1"
["UPDATE_RULE"]=>
string(1) "1"
["DELETE_RULE"]=>
string(1) "1"
["FK_NAME"]=>
string(18) "fk_game_event_code"
["PK_NAME"]=>
string(13) "pk_event_code"
}
}
--- Column Attribute ---
array(1) {
[0]=>
array(13) {
["ATTR_NAME"]=>
string(4) "area"
["DOMAIN"]=>
string(1) "7"
["SCALE"]=>
string(1) "2"
["PRECISION"]=>
string(2) "10"
["INDEXED"]=>
string(1) "0"
["NON_NULL"]=>
string(1) "0"
["SHARED"]=>
string(1) "0"
["UNIQUE"]=>
string(1) "0"
["DEFAULT"]=>
NULL
["ATTR_ORDER"]=>
string(1) "4"
["CLASS_NAME"]=>
string(7) "stadium"
["SOURCE_CLASS"]=>
string(7) "stadium"
["IS_KEY"]=>
string(1) "0"
}
}
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_seq_drop
(PECL CUBRID >= 8.3.0)
cubrid_seq_drop - Delete an element from sequence type column using OID
Description
bool cubrid_seq_drop ( resource $conn_identifier , string $oid , string
$attr_name , int $index )
The cubrid_seq_drop() function is used to delete an element you request
from the given sequence type attribute in the database.
Parameters
conn_identifier
Connection identifier.
oid
OID of the instance you want to work with.
attr_name
Name of the attribute that you want to delete an element from.
index
Index of the element that you want to delete (1-based).
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_seq_drop() example
The above example will output:
array(4) {
[0]=>
string(2) "11"
[1]=>
string(2) "22"
[2]=>
string(2) "33"
[3]=>
string(3) "333"
}
array(3) {
[0]=>
string(2) "11"
[1]=>
string(2) "22"
[2]=>
string(2) "33"
}
See Also
* cubrid_seq_insert() - Insert an element to a sequence type column
using OID
* cubrid_seq_put() - Update the element value of sequence type column
using OID
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_seq_insert
(PECL CUBRID >= 8.3.0)
cubrid_seq_insert - Insert an element to a sequence type column using OID
Description
bool cubrid_seq_insert ( resource $conn_identifier , string $oid , string
$attr_name , int $index , string $seq_element )
The cubrid_col_insert() function is used to insert an element to a
sequence type attribute in a requested location.
Parameters
conn_identifier
Connection identifier.
oid
OID of the instance you want to work with.
attr_name
Name of the attribute you want to insert an instance to.
index
Location of the element, you want to insert the element to
(1-based).
seq_element
Content of the element that you want to insert.
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_seq_insert() example
The above example will output:
array(4) {
[0]=>
string(2) "11"
[1]=>
string(2) "22"
[2]=>
string(2) "33"
[3]=>
string(3) "333"
}
array(5) {
[0]=>
string(2) "11"
[1]=>
string(2) "22"
[2]=>
string(2) "33"
[3]=>
string(3) "333"
[4]=>
string(2) "44"
}
See Also
* cubrid_seq_drop() - Delete an element from sequence type column using
OID
* cubrid_seq_put() - Update the element value of sequence type column
using OID
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_seq_put
(PECL CUBRID >= 8.3.0)
cubrid_seq_put - Update the element value of sequence type column using
OID
Description
bool cubrid_seq_put ( resource $conn_identifier , string $oid , string
$attr_name , int $index , string $seq_element )
The cubrid_seq_put() function is used to update the content of the
requested element in a sequent type attribute using OID.
Parameters
conn_identifier
Connection identifier.
oid
OID of the instance you want to work with.
attr_name
Name of the attribute that you want to update an element.
index
Index (1-based) of the element that you want to update.
seq_element
New content that you want to use for the update.
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_seq_put() example
The above example will output:
array(4) {
[0]=>
string(2) "11"
[1]=>
string(2) "22"
[2]=>
string(2) "33"
[3]=>
string(3) "333"
}
array(4) {
[0]=>
string(3) "111"
[1]=>
string(2) "22"
[2]=>
string(2) "33"
[3]=>
string(3) "333"
}
See Also
* cubrid_seq_drop() - Delete an element from sequence type column using
OID
* cubrid_seq_insert() - Insert an element to a sequence type column
using OID
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_set_add
(PECL CUBRID >= 8.3.0)
cubrid_set_add - Insert a single element to set type column using OID
Description
bool cubrid_set_add ( resource $conn_identifier , string $oid , string
$attr_name , string $set_element )
The cubrid_set_add() function is used to insert a single element to a set
type attribute (set, multiset, sequence) you requested.
Parameters
conn_identifier
Connection identifier.
oid
OID of the instance you want to work with.
attr_name
Name of the attribute you want to insert an element.
set_element
Content of the element you want to insert.
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_set_add() example
The above example will output:
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
}
array(4) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
[3]=>
string(1) "4"
}
See Also
* cubrid_seq_drop() - Delete an element from sequence type column using
OID
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_set_autocommit
(PECL CUBRID >= 8.4.0)
cubrid_set_autocommit - Set autocommit mode of the connection
Description
bool cubrid_set_autocommit ( resource $conn_identifier , bool $mode )
The cubrid_set_autocommit() function is used to set the CUBRID database
auto-commit mode of the current database connection.
In CUBRID PHP, an auto-commit mode is disabled by default for transaction
management. When auto-commit mode is truned from off to on, any pending
work is automatically committed.
Parameters
conn_identifier
Connection identifier.
mode
Auto-commit mode. The following constants can be used:
* CUBRID_AUTOCOMMIT_FALSE
* CUBRID_AUTOCOMMIT_TRUE
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
See Also
* cubrid_get_autocommit() - Get auto-commit mode of the connection
* cubrid_commit() - Commit a transaction
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_set_db_parameter
(PECL CUBRID >= 8.4.0)
cubrid_set_db_parameter - Sets the CUBRID database parameters
Description
bool cubrid_set_db_parameter ( resource $conn_identifier , int $param_type
, int $param_value )
The cubrid_set_db_parameter() function is used to set the CUBRID database
parameters. It can set the following CUBRID database parameters:
* PARAM_ISOLATION_LEVEL
* PARAM_LOCK_TIMEOUT
Note:
The auto-commit mode can be set by using cubrid_set_autocommit().
Parameters
conn_identifier
The CUBRID connection. If the connection identifier is not
specified, the last link opened by cubrid_connect() is assumed.
param_type
Database parameter type.
param_value
Isolation level value (1-6) or lock timeout (in seconds) value.
Return Values
TRUE on success.
FALSE on failure.
Examples
Example #1 cubrid_get_db_parameter() example
The above example will output:
array(4) {
["PARAM_ISOLATION_LEVEL"]=>
int(3)
["PARAM_LOCK_TIMEOUT"]=>
int(-1)
["PARAM_MAX_STRING_LENGTH"]=>
int(1073741823)
["PARAM_AUTO_COMMIT"]=>
int(0)
}
array(4) {
["PARAM_ISOLATION_LEVEL"]=>
int(2)
["PARAM_LOCK_TIMEOUT"]=>
int(-1)
["PARAM_MAX_STRING_LENGTH"]=>
int(1073741823)
["PARAM_AUTO_COMMIT"]=>
int(1)
}
See Also
* cubrid_get_db_parameter() - Returns the CUBRID database parameters
* cubrid_set_autocommit() - Set autocommit mode of the connection
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_set_drop
(PECL CUBRID >= 8.3.0)
cubrid_set_drop - Delete an element from set type column using OID
Description
bool cubrid_set_drop ( resource $conn_identifier , string $oid , string
$attr_name , string $set_element )
The cubrid_set_drop() function is used to delete an element that you
request from the given set type (set, multiset) attribute of the database.
Parameters
conn_identifier
Connection identifier.
oid
OID of the instance you want to work with.
attr_name
Name of the attribute you want to delete an element from.
set_element
Content of the element you want to delete.
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_set_drop() example
The above example will output:
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
}
array(2) {
[0]=>
string(1) "2"
[1]=>
string(1) "3"
}
See Also
* cubrid_set_add() - Insert a single element to set type column using
OID
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_version
(PECL CUBRID >= 8.3.0)
cubrid_version - Get the CUBRID PHP module's version
Description
string cubrid_version ( void )
The cubrid_version() function is used to get the CUBRID PHP module's
version.
Parameters
This function has no parameters.
Return Values
Version information (eg. "8.3.1.0001").
Examples
Example #1 cubrid_version() example
The above example will output:
CUBRID PHP Version: 8.3.1.0005
PARAM_ISOLATION_LEVEL 3
LOCK_TIMEOUT -1
MAX_STRING_LENGTH 1073741823
PARAM_AUTO_COMMIT 0
Server Info: 8.3.1.0173
Client Info: 8.3.1
CUBRID Charset: iso8859-1
See Also
* cubrid_error_code() - Get error code for the most recent function call
* cubrid_error_code_facility() - Get the facility code of error
----------------------------------------------------------------------
Table of Contents
* cubrid_affected_rows - Return the number of rows affected by the last
SQL statement
* cubrid_bind - Bind variables to a prepared statement as parameters
* cubrid_close_prepare - Close the request handle
* cubrid_close_request - Close the request handle
* cubrid_col_get - Get contents of collection type column using OID
* cubrid_col_size - Get the number of elements in collection type column
using OID
* cubrid_column_names - Get the column names in result
* cubrid_column_types - Get column types in result
* cubrid_commit - Commit a transaction
* cubrid_connect_with_url - Establish the environment for connecting to
CUBRID server
* cubrid_connect - Open a connection to a CUBRID Server
* cubrid_current_oid - Get OID of the current cursor location
* cubrid_disconnect - Close a database connection
* cubrid_drop - Delete an instance using OID
* cubrid_error_code_facility - Get the facility code of error
* cubrid_error_code - Get error code for the most recent function call
* cubrid_error_msg - Get last error message for the most recent function
call
* cubrid_execute - Execute a prepared SQL statement
* cubrid_fetch - Fetch the next row from a result set
* cubrid_free_result - Free the memory occupied by the result data
* cubrid_get_autocommit - Get auto-commit mode of the connection
* cubrid_get_charset - Return the current CUBRID connection charset
* cubrid_get_class_name - Get the class name using OID
* cubrid_get_client_info - Return the client library version
* cubrid_get_db_parameter - Returns the CUBRID database parameters
* cubrid_get_server_info - Return the CUBRID server version
* cubrid_get - Get a column using OID
* cubrid_insert_id - Return the ID generated for the lastest updated
AUTO_INCREMENT column
* cubrid_is_instance - Check whether the instance pointed by OID exists
* cubrid_lob_close - Close BLOB/CLOB data
* cubrid_lob_export - Export BLOB/CLOB data to file
* cubrid_lob_get - Get BLOB/CLOB data
* cubrid_lob_send - Read BLOB/CLOB data and send straight to browser
* cubrid_lob_size - Get BLOB/CLOB data size
* cubrid_lock_read - Set a read lock on the given OID
* cubrid_lock_write - Set a write lock on the given OID
* cubrid_move_cursor - Move the cursor in the result
* cubrid_next_result - Get result of next query when executing multiple
SQL statements
* cubrid_num_cols - Return the number of columns in the result set
* cubrid_num_rows - Get the number of rows in the result set
* cubrid_prepare - Prepare an SQL statement for execution
* cubrid_put - Update a column using OID
* cubrid_rollback - Roll back a transaction
* cubrid_schema - Get the requested schema information
* cubrid_seq_drop - Delete an element from sequence type column using
OID
* cubrid_seq_insert - Insert an element to a sequence type column using
OID
* cubrid_seq_put - Update the element value of sequence type column
using OID
* cubrid_set_add - Insert a single element to set type column using OID
* cubrid_set_autocommit - Set autocommit mode of the connection
* cubrid_set_db_parameter - Sets the CUBRID database parameters
* cubrid_set_drop - Delete an element from set type column using OID
* cubrid_version - Get the CUBRID PHP module's version
----------------------------------------------------------------------
----------------------------------------------------------------------
CUBRID MySQL Compatibility Functions
----------------------------------------------------------------------
cubrid_client_encoding
(PECL CUBRID >= 8.3.1)
cubrid_client_encoding - Return the current CUBRID connection charset
Description
string cubrid_client_encoding ([ resource $conn_identifier ] )
This function returns the current CUBRID connection charset.
Parameters
conn_identifier
The CUBRID connection. If the connection identifier is not
specified, the last link opened by cubrid_connect() is assumed.
Return Values
A string that represents the CUBRID connection charset; on success.
FALSE on failure.
Examples
Example #1 cubrid_client_encoding() example
The above example will output:
Result:
CUBRID current charset: iso8859-1
See Also
* cubrid_get_charset() - Return the current CUBRID connection charset
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_close
(PECL CUBRID >= 8.3.1)
cubrid_close - Close CUBRID connection
Description
bool cubrid_close ([ resource $conn_identifier ] )
The cubrid_close() function ends the transaction currently on process,
closes the connection handle and disconnects from server. If there exists
any request handle not closed yet at this point, it will be closed.
Parameters
conn_identifier
The CUBRID connection identifier. If the connection identifier is
not specified, the last connection opened by cubrid_connect() is
assumed.
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_close() example
See Also
* cubrid_connect() - Open a connection to a CUBRID Server
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_data_seek
(PECL CUBRID >= 8.3.0)
cubrid_data_seek - Move the internal row pointer of the CUBRID result
Description
int cubrid_data_seek ( resource $result , int $row_number )
This function performs the moving of the internal row pointer of the
CUBRID result (associated with the specified result identifier) to point
to a specific row number. There are functions, such as
cubrid_fetch_assoc(), which use the current stored value of row number.
Parameters
result
The result.
row_number
This is the desired row number of the new result pointer.
Return Values
CUBRID_CURSOR_SUCCESS, on success.
CUBRID_NO_MORE_DATA, when it is not a valid cursor location.
FALSE on CAS error, row count is 0, or invalid offset.
Examples
Example #1 cubrid_data_seek() example
The above example will output:
array(2) {
[0]=>
string(1) "X"
[1]=>
string(5) "Mixed"
}
array(2) {
[0]=>
string(1) "M"
[1]=>
string(3) "Man"
}
array(2) {
[0]=>
string(1) "S"
[1]=>
string(6) "Silver"
}
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_db_name
(PECL CUBRID >= 8.3.1)
cubrid_db_name - Get db name from results of cubrid_list_dbs
Description
string cubrid_db_name ( array $result , int $index )
Retrieve the database name from a call to cubrid_list_dbs().
Parameters
result
The result pointer from a call to cubrid_list_dbs().
index
The index into the result set.
Return Values
Returns the database name on success, and FALSE on failure. If FALSE is
returned, use cubrid_error() to determine the nature of the error.
Examples
Example #1 cubrid_db_name() example
See Also
* cubrid_list_dbs() - Return an array with the list of all existing
CUBRID databases
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_errno
(PECL CUBRID >= 8.3.1)
cubrid_errno - Return the numerical value of the error message from
previous CUBRID operation
Description
int cubrid_errno ([ resource $conn_identifier ] )
Returns the error number from the last CUBRID function.
The cubrid_errno() function is used to get the error code of the error
that occurred during the API execution. Usually, it gets the error code
when API returns false as its return value.
Parameters
conn_identifier
The CUBRID connection identifier. If the connection identifier is
not specified, the last connection opened by cubrid_connect() is
assumed.
Return Values
Returns the error number from the last CUBRID function, or 0 (zero) if no
error occurred.
Examples
Example #1 cubrid_errno() example
See Also
* cubrid_error() - Get the error message
* cubrid_error_code() - Get error code for the most recent function call
* cubrid_error_msg() - Get last error message for the most recent
function call
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_error
(PECL CUBRID >= 8.3.1)
cubrid_error - Get the error message
Description
string cubrid_error ([ resource $connection ] )
The cubrid_error() function is used to get the error message that occurred
during the use of CUBRID API. Usually, it gets error message when API
returns false as its return value.
Parameters
connection
Return Values
Error message that occurred.
Examples
Example #1 cubrid_error() example
See Also
* cubrid_errno() - Return the numerical value of the error message from
previous CUBRID operation
* cubrid_error_code() - Get error code for the most recent function call
* cubrid_error_msg() - Get last error message for the most recent
function call
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_fetch_array
(PECL CUBRID >=8.3.0)
cubrid_fetch_array - Fetch a result row as an associative array, a numeric
array, or both
Description
array cubrid_fetch_array ( resource $result [, int $type = CUBRID_BOTH ] )
The cubrid_fetch_array() function is used to get a single row from the
query result and returns an array. The cursor automatically moves to the
next row after getting the result.
Parameters
result
Result comes from a call to cubrid_execute()
type
Array type of the fetched result CUBRID_NUM, CUBRID_ASSOC,
CUBRID_BOTH.
Return Values
Returns an array of strings that corresponds to the fetched row, when
process is successful.
FALSE, when process is unsuccessful.
The type of returned array depends on how type is defined. By using
CUBRID_BOTH (default), you'll get an array with both associative and
number indices, and you can decide which data type to use by setting the
type argument. The type variable can be set to one of the following
values:
* CUBRID_NUM : Numerical array (0-based)
* CUBRID_ASSOC : Associative array
* CUBRID_BOTH : Numerical & Associative array (default)
Examples
Example #1 cubrid_fetch_array() example
10000");
printf("%-40s %-10s %-6s %-20s\n", "name", "area", "seats", "address");
while ($row = cubrid_fetch_array($req, CUBRID_NUM)) {
printf("%-40s %-10s %-6s %-20s\n", $row[0], $row[1], $row[2], $row[3]);
}
cubrid_close_request($req);
cubrid_disconnect($conn);
?>
The above example will output:
name area seats address
Panathinaiko Stadium 86300.00 50000 Athens, Greece
Olympic Stadium 54700.00 13000 Athens, Greece
Olympic Indoor Hall 34100.00 18800 Athens, Greece
Olympic Hall 52400.00 21000 Athens, Greece
Olympic Aquatic Centre 42500.00 11500 Athens, Greece
Markopoulo Olympic Equestrian Centre 64000.00 15000 Markopoulo, Athens, Greece
Faliro Coastal Zone Olympic Complex 34650.00 12171 Faliro, Athens, Greece
Athens Olympic Stadium 120400.00 71030 Maroussi, Athens, Greece
Ano Liossia 34000.00 12000 Ano Liosia, Athens, Greece
See Also
* cubrid_execute() - Execute a prepared SQL statement
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_fetch_assoc
(PECL CUBRID >= 8.3.0)
cubrid_fetch_assoc - Return the associative array that corresponds to the
fetched row
Description
array cubrid_fetch_assoc ( resource $result )
This function returns the associative array, that corresponds to the
fetched row, and then moves the internal data pointer ahead, or returns
FALSE when the end is reached.
Parameters
result
result comes from a call to cubrid_execute()
Return Values
Associative array, when process is successful.
FALSE when the end is reached, or error.
Examples
Example #1 cubrid_fetch_assoc() example
10000");
printf("%-40s %-10s %-6s %-20s\n", "name", "area", "seats", "address");
while ($row = cubrid_fetch_assoc($req)) {
printf("%-40s %-10s %-6s %-20s\n",
$row["name"], $row["area"], $row["seats"], $row["address"]);
}
cubrid_close_request($req);
cubrid_disconnect($conn);
?>
The above example will output:
name area seats address
Panathinaiko Stadium 86300.00 50000 Athens, Greece
Olympic Stadium 54700.00 13000 Athens, Greece
Olympic Indoor Hall 34100.00 18800 Athens, Greece
Olympic Hall 52400.00 21000 Athens, Greece
Olympic Aquatic Centre 42500.00 11500 Athens, Greece
Markopoulo Olympic Equestrian Centre 64000.00 15000 Markopoulo, Athens, Greece
Faliro Coastal Zone Olympic Complex 34650.00 12171 Faliro, Athens, Greece
Athens Olympic Stadium 120400.00 71030 Maroussi, Athens, Greece
Ano Liossia 34000.00 12000 Ano Liosia, Athens, Greece
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_fetch_field
(PECL CUBRID >= 8.3.0)
cubrid_fetch_field - Get column information from a result and return as an
object
Description
object cubrid_fetch_field ( resource $result [, int $field_offset = 0 ] )
This function returns an object with certain properties of the specific
column. The properties of the object are:
name
column name
table
name of the table that the column belongs to
def
default value of the column
max_length
maximum length of the column
not_null
1 if the column cannot be NULL
unique_key
1 if the column is an unique key
multiple_key
1 if the column is a non-unique key
numeric
1 if the column is numeric
type
the type of the column
Parameters
result
result comes from a call to cubrid_execute()
field_offset
The numerical field offset. If the field offset is not specified,
the next field (that was not yet retrieved by this function) is
retrieved. The field_offset starts at 0.
Return Values
Object with certain properties of the specific column, when process is
successful.
FALSE on failure.
Examples
Example #1 cubrid_fetch_field() example
name);
printf("%-30s %s\n", "table:", $field->table);
printf("%-30s \"%s\"\n", "default value:", $field->def);
printf("%-30s %d\n", "max lenght:", $field->max_length);
printf("%-30s %d\n", "not null:", $field->not_null);
printf("%-30s %d\n", "unique key:", $field->unique_key);
printf("%-30s %d\n", "multiple key:", $field->multiple_key);
printf("%-30s %d\n", "numeric:", $field->numeric);
printf("%-30s %s\n", "type:", $field->type);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>
The above example will output:
array(4) {
[0]=>
string(5) "20001"
[1]=>
string(5) "16681"
[2]=>
string(3) "KOR"
[3]=>
string(9) "1988-9-30"
}
--- Field Properties ---
name: athlete_code
table: game
default value: ""
max lenght: 5
not null: 1
unique key: 1
multiple key: 0
numeric: 1
type: integer
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_fetch_lengths
(PECL CUBRID >= 8.3.0)
cubrid_fetch_lengths - Return an array with the lengths of the values of
each field from the current row
Description
array cubrid_fetch_lengths ( resource $result )
This function returns an numeric array with the lengths of the values of
each field from the current row of the result set or it returns FALSE on
failure.
Note:
If field data type is BLOB/CLOB, you should get its length by using
cubrid_lob_size().
Parameters
result
result comes from a call to cubrid_execute()
Return Values
An numeric array, when process is successful.
FALSE on failure.
Examples
Example #1 cubrid_fetch_lengths() example
The above example will output:
Array
(
[0] => 2004
[1] => 20085
[2] => 15118
[3] => 30134
[4] => AUS
[5] => G
[6] => 2004-8-20
)
Array
(
[0] => 4
[1] => 5
[2] => 5
[3] => 5
[4] => 3
[5] => 1
[6] => 9
)
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_fetch_object
(PECL CUBRID >= 8.3.0)
cubrid_fetch_object - Fetche the next row and returns it as an object
Description
object cubrid_fetch_object ( resource $result [, string $class_name [,
array $params ]] )
This function returns an object with the column names of the result set as
properties. The values of these properties are extracted from the current
row of the result.
Parameters
result
result comes from a call to cubrid_execute()
class_name
The name of the class to instantiate. If not specified, a stdClass
(stdClass is PHP's generic empty class that's used when casting
other types to objects) object is returned.
params
An optional array of parameters to pass to the constructor for
class_name objects.
Return Values
An object, when process is successful.
FALSE on failure.
Examples
Example #1 cubrid_fetch_object() example
s_name = $s;
$this->f_name = $f;
}
}
var_dump(cubrid_fetch_object($res, 'demodb_code_construct', array('s_name', 'f_name')));
var_dump(cubrid_fetch_object($res));
cubrid_close_request($res);
cubrid_disconnect($conn);
?>
The above example will output:
object(stdClass)#1 (2) {
["s_name"]=>
string(1) "X"
["f_name"]=>
string(5) "Mixed"
}
object(demodb_code)#1 (2) {
["s_name"]=>
string(1) "W"
["f_name"]=>
string(5) "Woman"
}
object(demodb_code_construct)#1 (2) {
["s_name"]=>
string(6) "s_name"
["f_name"]=>
string(6) "f_name"
}
object(stdClass)#1 (2) {
["s_name"]=>
string(1) "B"
["f_name"]=>
string(6) "Bronze"
}
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_fetch_row
(PECL CUBRID >= 8.3.0)
cubrid_fetch_row - Return a numerical array with the values of the current
row
Description
array cubrid_fetch_row ( resource $result )
This function returns a numerical array with the values of the current row
from the result set, starting from 0, and moves the internal data pointer
ahead.
Parameters
result
result comes from a call to cubrid_execute()
Return Values
A numerical array, when process is successful.
FALSE on failure.
Examples
Example #1 cubrid_fetch_row() example
10000");
printf("%-40s %-10s %-6s %-20s\n", "name", "area", "seats", "address");
while ($row = cubrid_fetch_row($req)) {
printf("%-40s %-10s %-6s %-20s\n", $row[0], $row[1], $row[2], $row[3]);
}
cubrid_close_request($req);
cubrid_disconnect($conn);
?>
The above example will output:
name area seats address
Panathinaiko Stadium 86300.00 50000 Athens, Greece
Olympic Stadium 54700.00 13000 Athens, Greece
Olympic Indoor Hall 34100.00 18800 Athens, Greece
Olympic Hall 52400.00 21000 Athens, Greece
Olympic Aquatic Centre 42500.00 11500 Athens, Greece
Markopoulo Olympic Equestrian Centre 64000.00 15000 Markopoulo, Athens, Greece
Faliro Coastal Zone Olympic Complex 34650.00 12171 Faliro, Athens, Greece
Athens Olympic Stadium 120400.00 71030 Maroussi, Athens, Greece
Ano Liossia 34000.00 12000 Ano Liosia, Athens, Greece
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_field_flags
(PECL CUBRID >= 8.3.0)
cubrid_field_flags - Return a string with the flags of the given field
offset
Description
string cubrid_field_flags ( resource $result , int $field_offset )
This function returns a string with the flags of the given field offset
separated by space. You can split the returned value using explode. The
possible flags could be: not_null, primary_key, unique_key, foreign_key,
auto_increment, shared, reverse_index, reverse_unique and timestamp.
Parameters
result
result comes from a call to cubrid_execute()
field_offset
The numerical field offset. The field_offset starts at 0. If
field_offset does not exist, an error of level E_WARNING is also
issued.
Return Values
A string with flags, when process is successful.
FALSE when invalid field_offset value.
-1 if SQL sentence is not SELECT.
Examples
Example #1 cubrid_field_flags() example
The above example will output:
Field Name Field Flags
host_year not_null primary_key unique_key
event_code not_null primary_key unique_key foreign_key
athlete_code not_null primary_key unique_key foreign_key
stadium_code not_null
nation_code
medal
game_date
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_field_len
(PECL CUBRID >= 8.3.0)
cubrid_field_len - Get the maximum length of the specified field
Description
int cubrid_field_len ( resource $result , int $field_offset )
This function returns the maximum length of the specified field on
success, or it returns FALSE on failure.
Parameters
result
result comes from a call to cubrid_execute()
field_offset
The numerical field offset. The field_offset starts at 0. If
field_offset does not exist, an error of level E_WARNING is also
issued.
Return Values
Maximum length, when process is successful.
FALSE on failure.
Examples
Example #1 cubrid_field_len() example
The above example will output:
Column Names Column Types Column Maxlen
host_year integer 11
event_code integer 11
athlete_code integer 11
stadium_code integer 11
nation_code char(3) 3
medal char(1) 1
game_date date 10
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_field_name
(PECL CUBRID >= 8.3.0)
cubrid_field_name - Return the name of the specified field index
Description
string cubrid_field_name ( resource $result , int $field_offset )
This function returns the name of the specified field index on success or
it returns FALSE on failure.
Parameters
result
result comes from a call to cubrid_execute()
field_offset
The numerical field offset. The field_offset starts at 0. If
field_offset does not exist, an error of level E_WARNING is also
issued.
Return Values
Name of specified field index, on success.
FALSE on failure.
Examples
Example #1 cubrid_field_name() example
The above example will output:
Field Name Field Flags
host_year not_null primary_key unique_key
event_code not_null primary_key unique_key foreign_key
athlete_code not_null primary_key unique_key foreign_key
stadium_code not_null
nation_code
medal
game_date
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_field_seek
(PECL CUBRID >= 8.3.0)
cubrid_field_seek - Move the result set cursor to the specified field
offset
Description
bool cubrid_field_seek ( resource $result [, int $field_offset = 0 ] )
This function moves the result set cursor to the specified field offset.
This offset is used by cubrid_fetch_field() if it doesn't include a field
offset. It returns TRUE on success or FALSE on failure.
Parameters
result
result comes from a call to cubrid_execute()
field_offset
The numerical field offset. The field_offset starts at 0. If
field_offset does not exist, an error of level E_WARNING is also
issued.
Return Values
TRUE on success.
FALSE on failure.
Examples
Example #1 cubrid_field_seek() example
name);
printf("%-30s %s\n", "table:", $field->table);
printf("%-30s \"%s\"\n", "default value:", $field->def);
printf("%-30s %d\n", "max lenght:", $field->max_length);
printf("%-30s %d\n", "not null:", $field->not_null);
printf("%-30s %d\n", "unique key:", $field->unique_key);
printf("%-30s %d\n", "multiple key:", $field->multiple_key);
printf("%-30s %d\n", "numeric:", $field->numeric);
printf("%-30s %s\n", "type:", $field->type);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>
The above example will output:
array(4) {
[0]=>
string(5) "20001"
[1]=>
string(5) "16681"
[2]=>
string(3) "KOR"
[3]=>
string(9) "1988-9-30"
}
--- Field Properties ---
name: athlete_code
table: game
default value: ""
max lenght: 5
not null: 1
unique key: 1
multiple key: 0
numeric: 1
type: integer
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_field_table
(PECL CUBRID >= 8.3.0)
cubrid_field_table - Return the name of the table of the specified field
Description
string cubrid_field_table ( resource $result , int $field_offset )
This function returns the name of the table of the specified field. This
is useful when using large select queries with JOINS.
Parameters
result
Array type of the fetched result CUBRID_NUM, CUBRID_ASSOC,
CUBRID_BOTH.
field_offset
The numerical field offset. The field_offset starts at 0. If
field_offset does not exist, an error of level E_WARNING is also
issued.
Return Values
Name of the table of the specified field, on success.
FALSE when invalid field_offset value.
-1 if SQL sentence is not SELECT.
Examples
Example #1 cubrid_field_table() example
The above example will output:
Field Table Field Name Field Type
code s_name char(1)
code f_name varchar(6)
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_field_type
(PECL CUBRID >= 8.3.0)
cubrid_field_type - Return the type of the column corresponding to the
given field offset
Description
string cubrid_field_type ( resource $result , int $field_offset )
This function returns the type of the column corresponding to the given
field offset. The returned field type could be one of the following:
"int", "real", "string", etc.
Parameters
result
Array type of the fetched result CUBRID_NUM, CUBRID_ASSOC,
CUBRID_BOTH.
field_offset
The numerical field offset. The field_offset starts at 0. If
field_offset does not exist, an error of level E_WARNING is also
issued.
Return Values
Type of the column, on success.
FALSE when invalid field_offset value.
-1 if SQL sentence is not SELECT.
Examples
Example #1 cubrid_field_type() example
The above example will output:
Field Table Field Name Field Type
code s_name char(1)
code f_name varchar(6)
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_list_dbs
(PECL CUBRID >= 8.3.0)
cubrid_list_dbs - Return an array with the list of all existing CUBRID
databases
Description
array cubrid_list_dbs ( resource $conn_identifier )
This function returns an array with the list of all existing Cubrid
databases.
Parameters
conn_identifier
The CUBRID connection.
Return Values
An numeric array with all existing Cubrid databases; on success.
FALSE on failure.
Examples
Example #1 cubrid_list_dbs() example
The above example will output:
array(1) {
[0]=>
string(6) "demodb"
}
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_num_fields
(PECL CUBRID >= 8.3.0)
cubrid_num_fields - Return the number of columns in the result set
Description
int cubrid_num_fields ( resource $result )
This function returns the number of columns in the result set, on success,
or it returns FALSE on failure.
Parameters
result
result comes from a call to cubrid_execute()
Return Values
Number of columns, on success.
-1 if SQL sentence is not SELECT.
Examples
Example #1 cubrid_num_fields() example
The above example will output:
Row Num: 6
Column Num: 2
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_ping
(PECL CUBRID >= 8.3.1)
cubrid_ping - Ping a server connection or reconnect if there is no
connection
Description
bool cubrid_ping ([ resource $conn_identifier ] )
Checks whether or not the connection to the server is working.
Parameters
conn_identifier
The CUBRID connection identifier. If the connection identifier is
not specified, the last connection opened by cubrid_connect() is
assumed.
Return Values
Returns TRUE if the connection to the server CUBRID server is working,
otherwise FALSE.
Examples
Example #1 cubrid_ping() example
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_query
(PECL CUBRID >= 8.3.1)
cubrid_query - Send a CUBRID query
Description
resource cubrid_query ( string $query [, resource $conn_identifier ] )
cubrid_query() sends a unique query (multiple queries are not supported)
to the currently active database on the server that's associated with the
specified conn_identifier.
Parameters
query
An SQL query
Data inside the query should be properly escaped.
conn_identifier
The CUBRID connection. If the connection identifier is not
specified, the last connection opened by cubrid_connect() is
assumed.
Return Values
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning
resultset, cubrid_query() returns a resource on success, or FALSE on
error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc,
cubrid_query() returns TRUE on success or FALSE on error.
The returned result resource should be passed to cubrid_fetch_array(), and
other functions for dealing with result tables, to access the returned
data.
Use cubrid_num_rows() to find out how many rows were returned for a SELECT
statement or cubrid_affected_rows() to find out how many rows were
affected by a DELETE, INSERT, REPLACE, or UPDATE statement.
cubrid_query() will also fail and return FALSE if the user does not have
permission to access the table(s) referenced by the query.
Examples
Example #1 Invalid Query
The following query is syntactically invalid, so cubrid_query() fails and
returns FALSE.
Example #2 Valid Query
The following query is valid, so cubrid_query() returns a resource.
See Also
* cubrid_connect() - Open a connection to a CUBRID Server
* cubrid_error() - Get the error message
* cubrid_real_escape_string() - Escape special characters in a string
for use in an SQL statement
* cubrid_result() - Return the value of a specific field in a specific
row
* cubrid_fetch_assoc() - Return the associative array that corresponds
to the fetched row
* cubrid_unbuffered_query() - Perform a query without fetching the
results into memory
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_real_escape_string
(PECL CUBRID >= 8.3.0)
cubrid_real_escape_string - Escape special characters in a string for use
in an SQL statement
Description
string cubrid_real_escape_string ( string $unescaped_string [, resource
$conn_identifier ] )
This function returns the escaped string version of the given string. It
will escape the following characters: '. In general, single quotations are
used to enclose character string. Double quotations may be used as well
depending on the value of ansi_quotes, which is a parameter related to SQL
statement. If the ansi_quotes value is set to no, character string
enclosed by double quotations is handled as character string, not as an
identifier. The default value is yes. If you want to include a single
quote as part of a character string, enter two single quotes in a row.
Parameters
unescaped_string
The string that is to be escaped.
conn_identifier
The CUBRID connection. If the connection identifier is not
specified, the last connection opened by cubrid_connect() is
assumed.
Return Values
Escaped string version of the given string, on success.
FALSE on failure.
Examples
Example #1 cubrid_real_escape_string() example
?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
$escaped_str = cubrid_real_escape_string($unescaped_str);
$len = strlen($unescaped_str);
@cubrid_execute($conn, "DROP TABLE cubrid_test");
cubrid_execute($conn, "CREATE TABLE cubrid_test (t char($len))");
cubrid_execute($conn, "INSERT INTO cubrid_test (t) VALUES('$escaped_str')");
$req = cubrid_execute($conn, "SELECT * FROM cubrid_test");
$row = cubrid_fetch_assoc($req);
var_dump($row);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>
The above example will output:
array(1) {
["t"]=>
string(95) " !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
}
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_result
(PECL CUBRID >= 8.3.0)
cubrid_result - Return the value of a specific field in a specific row
Description
string cubrid_result ( resource $result , int $row [, mixed $field = 0 ] )
This function returns the value of a specific field in a specific row from
a result set.
Parameters
result
result comes from a call to cubrid_execute()
row
The row number from the result that is being retrieved. Row
numbers start at 0.
field
The name or offset of the field being retrieved. It can be the
field's offset, the field's name, or the field's table dot field
name (tablename.fieldname). If the column name has been aliased
('select foo as bar from...'), use the alias instead of the column
name. If undefined, the first field is retrieved.
Return Values
Value of a specific field, on success (NULL if value if null).
FALSE on failure.
Examples
Example #1 cubrid_result() example
The above example will output:
string(1) "X"
string(5) "Mixed"
string(4) "Gold"
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_unbuffered_query
(PECL CUBRID >= 8.3.0)
cubrid_unbuffered_query - Perform a query without fetching the results
into memory
Description
resource cubrid_unbuffered_query ( string $query [, resource
$conn_identifier ] )
This function performs a query without waiting for that all query results
have been complete. It will return when the results are being generated.
Parameters
query
A SQL query.
conn_identifier
The CUBRID connection. If the connection identifier is not
specified, the last connection opened by cubrid_connect() is
assumed.
Return Values
For SELECT, SHOW, DESCRIBE or EXPLAIN statements returns a connection
identifier resource on success.
For other type of SQL statements, UPDATE, DELETE, DROP, etc, returns TRUE
on success.
FALSE on failure.
Notes
Note:
The benefits of cubrid_unbuffered_query() come at a cost: you cannot use
cubrid_num_rows() and cubrid_data_seek() on a result set returned from
cubrid_unbuffered_query().
Examples
Example #1 cubrid_unbuffered_query() example
----------------------------------------------------------------------
Table of Contents
* cubrid_client_encoding - Return the current CUBRID connection charset
* cubrid_close - Close CUBRID connection
* cubrid_data_seek - Move the internal row pointer of the CUBRID result
* cubrid_db_name - Get db name from results of cubrid_list_dbs
* cubrid_errno - Return the numerical value of the error message from
previous CUBRID operation
* cubrid_error - Get the error message
* cubrid_fetch_array - Fetch a result row as an associative array, a
numeric array, or both
* cubrid_fetch_assoc - Return the associative array that corresponds to
the fetched row
* cubrid_fetch_field - Get column information from a result and return
as an object
* cubrid_fetch_lengths - Return an array with the lengths of the values
of each field from the current row
* cubrid_fetch_object - Fetche the next row and returns it as an object
* cubrid_fetch_row - Return a numerical array with the values of the
current row
* cubrid_field_flags - Return a string with the flags of the given field
offset
* cubrid_field_len - Get the maximum length of the specified field
* cubrid_field_name - Return the name of the specified field index
* cubrid_field_seek - Move the result set cursor to the specified field
offset
* cubrid_field_table - Return the name of the table of the specified
field
* cubrid_field_type - Return the type of the column corresponding to the
given field offset
* cubrid_list_dbs - Return an array with the list of all existing CUBRID
databases
* cubrid_num_fields - Return the number of columns in the result set
* cubrid_ping - Ping a server connection or reconnect if there is no
connection
* cubrid_query - Send a CUBRID query
* cubrid_real_escape_string - Escape special characters in a string for
use in an SQL statement
* cubrid_result - Return the value of a specific field in a specific row
* cubrid_unbuffered_query - Perform a query without fetching the results
into memory
----------------------------------------------------------------------
----------------------------------------------------------------------
CUBRID Obsolete Aliases and Functions
----------------------------------------------------------------------
cubrid_load_from_glo
(PECL CUBRID >= 8.3.0)
cubrid_load_from_glo - Read data from a GLO instance and save it in a file
Description
int cubrid_load_from_glo ( resource $conn_identifier , string $oid ,
string $file_name )
The cubrid_load_from_glo() function is used to read a data from a glo
instance, and saves it in a designated file.
Parameters
conn_identifier
Connection identifier.
oid
Oid of the glo instance that you want to read the data from.
file_name
Name of the file where you want to save the data in.
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_load_from_glo() example
Notes
Note:
For backward compatibility, the following deprecated alias may be used:
cubrid_load_from_glo()
Note:
This function is removed from CUBRID 3.1.
See Also
* cubrid_new_glo() - Create a glo instance
* cubrid_save_to_glo() - Save requested file in a GLO instance
* cubrid_send_glo() - Read data from glo and send it to std output
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_new_glo
(PECL CUBRID >= 8.3.0)
cubrid_new_glo - Create a glo instance
Description
string cubrid_new_glo ( resource $conn_identifier , string $class_name ,
string $file_name )
The cubrid_new_glo() function is used to create a glo instance in the
requested class (glo class). The glo created is a LO type, and is stored
in the file_name file.
Parameters
conn_identifier
Connection identifier.
class_name
Name of the class that you want to create a glo in.
file_name
The file name that you want to save in the newly created glo.
Return Values
Oid of the instance created, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_new_glo() example
Notes
Note:
For backward compatibility, the following deprecated alias may be used:
cubrid_new_glo()
Note:
This function is removed from CUBRID 3.1.
See Also
* cubrid_save_to_glo() - Save requested file in a GLO instance
* cubrid_load_from_glo() - Read data from a GLO instance and save it in
a file
* cubrid_send_glo() - Read data from glo and send it to std output
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_save_to_glo
(PECL CUBRID >= 8.3.0)
cubrid_save_to_glo - Save requested file in a GLO instance
Description
int cubrid_save_to_glo ( resource $conn_identifier , string $oid , string
$file_name )
The cubrid_save_to_glo() function is used to save requested file in a glo
instance.
Parameters
conn_identifier
Connection identifier.
oid
Oid of the glo instance that you want to save a file in.
file_name
The name of the file that you want to save.
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_save_to_glo() example
Notes
Note:
For backward compatibility, the following deprecated alias may be used:
cubrid_save_to_glo()
Note:
This function is removed from CUBRID 3.1.
See Also
* cubrid_new_glo() - Create a glo instance
* cubrid_load_from_glo() - Read data from a GLO instance and save it in
a file
* cubrid_send_glo() - Read data from glo and send it to std output
----------------------------------------------------------------------
----------------------------------------------------------------------
cubrid_send_glo
(PECL CUBRID >= 8.3.0)
cubrid_send_glo - Read data from glo and send it to std output
Description
int cubrid_send_glo ( resource $conn_identifier , string $oid )
The cubrid_send_glo() function is used to read data from glo instance and
sends it to the PHP standard output.
Parameters
conn_identifier
Connection identifier.
oid
Oid of the glo instance that you want to read data from.
Return Values
TRUE, when process is successful.
FALSE, when process is unsuccessful.
Examples
Example #1 cubrid_send_glo() example
Notes
Note:
For backward compatibility, the following deprecated alias may be used:
cubrid_send_glo()
Note:
This function is removed from CUBRID 3.1.
See Also
* cubrid_new_glo() - Create a glo instance
* cubrid_save_to_glo() - Save requested file in a GLO instance
* cubrid_load_from_glo() - Read data from a GLO instance and save it in
a file
----------------------------------------------------------------------
Table of Contents
* cubrid_load_from_glo - Read data from a GLO instance and save it in a
file
* cubrid_new_glo - Create a glo instance
* cubrid_save_to_glo - Save requested file in a GLO instance
* cubrid_send_glo - Read data from glo and send it to std output
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* CUBRID Functions
* cubrid_affected_rows - Return the number of rows affected by the
last SQL statement
* cubrid_bind - Bind variables to a prepared statement as
parameters
* cubrid_close_prepare - Close the request handle
* cubrid_close_request - Close the request handle
* cubrid_col_get - Get contents of collection type column using OID
* cubrid_col_size - Get the number of elements in collection type
column using OID
* cubrid_column_names - Get the column names in result
* cubrid_column_types - Get column types in result
* cubrid_commit - Commit a transaction
* cubrid_connect_with_url - Establish the environment for
connecting to CUBRID server
* cubrid_connect - Open a connection to a CUBRID Server
* cubrid_current_oid - Get OID of the current cursor location
* cubrid_disconnect - Close a database connection
* cubrid_drop - Delete an instance using OID
* cubrid_error_code_facility - Get the facility code of error
* cubrid_error_code - Get error code for the most recent function
call
* cubrid_error_msg - Get last error message for the most recent
function call
* cubrid_execute - Execute a prepared SQL statement
* cubrid_fetch - Fetch the next row from a result set
* cubrid_free_result - Free the memory occupied by the result data
* cubrid_get_autocommit - Get auto-commit mode of the connection
* cubrid_get_charset - Return the current CUBRID connection charset
* cubrid_get_class_name - Get the class name using OID
* cubrid_get_client_info - Return the client library version
* cubrid_get_db_parameter - Returns the CUBRID database parameters
* cubrid_get_server_info - Return the CUBRID server version
* cubrid_get - Get a column using OID
* cubrid_insert_id - Return the ID generated for the lastest
updated AUTO_INCREMENT column
* cubrid_is_instance - Check whether the instance pointed by OID
exists
* cubrid_lob_close - Close BLOB/CLOB data
* cubrid_lob_export - Export BLOB/CLOB data to file
* cubrid_lob_get - Get BLOB/CLOB data
* cubrid_lob_send - Read BLOB/CLOB data and send straight to
browser
* cubrid_lob_size - Get BLOB/CLOB data size
* cubrid_lock_read - Set a read lock on the given OID
* cubrid_lock_write - Set a write lock on the given OID
* cubrid_move_cursor - Move the cursor in the result
* cubrid_next_result - Get result of next query when executing
multiple SQL statements
* cubrid_num_cols - Return the number of columns in the result set
* cubrid_num_rows - Get the number of rows in the result set
* cubrid_prepare - Prepare an SQL statement for execution
* cubrid_put - Update a column using OID
* cubrid_rollback - Roll back a transaction
* cubrid_schema - Get the requested schema information
* cubrid_seq_drop - Delete an element from sequence type column
using OID
* cubrid_seq_insert - Insert an element to a sequence type column
using OID
* cubrid_seq_put - Update the element value of sequence type column
using OID
* cubrid_set_add - Insert a single element to set type column using
OID
* cubrid_set_autocommit - Set autocommit mode of the connection
* cubrid_set_db_parameter - Sets the CUBRID database parameters
* cubrid_set_drop - Delete an element from set type column using
OID
* cubrid_version - Get the CUBRID PHP module's version
* CUBRID MySQL Compatibility Functions
* cubrid_client_encoding - Return the current CUBRID connection
charset
* cubrid_close - Close CUBRID connection
* cubrid_data_seek - Move the internal row pointer of the CUBRID
result
* cubrid_db_name - Get db name from results of cubrid_list_dbs
* cubrid_errno - Return the numerical value of the error message
from previous CUBRID operation
* cubrid_error - Get the error message
* cubrid_fetch_array - Fetch a result row as an associative array,
a numeric array, or both
* cubrid_fetch_assoc - Return the associative array that
corresponds to the fetched row
* cubrid_fetch_field - Get column information from a result and
return as an object
* cubrid_fetch_lengths - Return an array with the lengths of the
values of each field from the current row
* cubrid_fetch_object - Fetche the next row and returns it as an
object
* cubrid_fetch_row - Return a numerical array with the values of
the current row
* cubrid_field_flags - Return a string with the flags of the given
field offset
* cubrid_field_len - Get the maximum length of the specified field
* cubrid_field_name - Return the name of the specified field index
* cubrid_field_seek - Move the result set cursor to the specified
field offset
* cubrid_field_table - Return the name of the table of the
specified field
* cubrid_field_type - Return the type of the column corresponding
to the given field offset
* cubrid_list_dbs - Return an array with the list of all existing
CUBRID databases
* cubrid_num_fields - Return the number of columns in the result
set
* cubrid_ping - Ping a server connection or reconnect if there is
no connection
* cubrid_query - Send a CUBRID query
* cubrid_real_escape_string - Escape special characters in a string
for use in an SQL statement
* cubrid_result - Return the value of a specific field in a
specific row
* cubrid_unbuffered_query - Perform a query without fetching the
results into memory
* CUBRID Obsolete Aliases and Functions
* cubrid_load_from_glo - Read data from a GLO instance and save it
in a file
* cubrid_new_glo - Create a glo instance
* cubrid_save_to_glo - Save requested file in a GLO instance
* cubrid_send_glo - Read data from glo and send it to std output
----------------------------------------------------------------------
----------------------------------------------------------------------
dBase
----------------------------------------------------------------------
Introduction
These functions allow you to access records stored in dBase-format (dbf)
databases.
dBase files are simple sequential files of fixed length records. Records
are appended to the end of the file and delete records are kept until you
call dbase_pack().
The types of dBase fields available are:
Available types of fields
Field dBase Type Format Additional information
M Memo n/a This type is not supported by PHP,
such field will be ignored
D Date YYYYMMDD The field length is limited to 8
You must declare a length and a
N Number A number precision (the number of digits after
the decimal point)
You must declare a length. When
C String A string retrieving data, the string will be
right-padded with spaces to fit the
declared length.
L Boolean T or Y for TRUE, F Stored and returned as an integer (1
or N for FALSE or 0)
F Float A float number Support for this type of field was
added in PHP 5.2.0
Note:
This extension has been moved to the >> PECL repository and is no longer
bundled with PHP as of PHP 5.3.0.
Warning
There is no support for indexes or memo fields. There is no support for
locking, too. Two concurrent web server processes modifying the same dBase
file will very likely ruin your database.
We recommend that you do not use dBase files as your production database.
Choose any real SQL server instead; >> MySQL or >> Postgres are common
choices with PHP. dBase support is here to allow you to import and export
data to and from your web database, because the file format is commonly
understood by Windows spreadsheets and organizers.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
In order to enable the bundled dbase library and to use these functions,
you must compile PHP with the --enable-dbase option.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
This extension has no constants defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
dBase Functions
Examples
Many examples in this reference require a dBase database. We will use
/tmp/test.dbf that will be created in the example of dbase_create().
----------------------------------------------------------------------
dbase_add_record
(PHP 4, PHP 5)
dbase_add_record - Adds a record to a database
Description
bool dbase_add_record ( int $dbase_identifier , array $record )
Adds the given data to the database.
Parameters
dbase_identifier
The database link identifier, returned by dbase_open() or
dbase_create().
record
An indexed array of data. The number of items must be equal to the
number of fields in the database, otherwise dbase_add_record()
will fail.
Note:
If you're using dbase_get_record() return value for this
parameter, remember to reset the key named deleted.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Inserting a record in a dBase database
See Also
* dbase_delete_record() - Deletes a record from a database
* dbase_replace_record() - Replaces a record in a database
----------------------------------------------------------------------
----------------------------------------------------------------------
dbase_close
(PHP 4, PHP 5)
dbase_close - Closes a database
Description
bool dbase_close ( int $dbase_identifier )
Closes the given database link identifier.
Parameters
dbase_identifier
The database link identifier, returned by dbase_open() or
dbase_create().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Closing a dBase database file
See Also
* dbase_open() - Opens a database
* dbase_create() - Creates a database
----------------------------------------------------------------------
----------------------------------------------------------------------
dbase_create
(PHP 4, PHP 5)
dbase_create - Creates a database
Description
int dbase_create ( string $filename , array $fields )
dbase_create() creates a dBase database with the given definition.
Note: When safe mode is enabled, PHP checks whether the files or
directories being operated upon have the same UID (owner) as the script
that is being executed.
Note:
This function is affected by open_basedir.
Parameters
filename
The name of the database. It can be a relative or absolute path to
the file where dBase will store your data.
fields
An array of arrays, each array describing the format of one field
of the database. Each field consists of a name, a character
indicating the field type, and optionally, a length, and a
precision.
Note:
The fieldnames are limited in length and must not exceed 10
chars.
Return Values
Returns a database link identifier if the database is successfully
created, or FALSE if an error occurred.
Examples
Example #1 Creating a dBase database file
See Also
* dbase_open() - Opens a database
* dbase_close() - Closes a database
----------------------------------------------------------------------
----------------------------------------------------------------------
dbase_delete_record
(PHP 4, PHP 5)
dbase_delete_record - Deletes a record from a database
Description
bool dbase_delete_record ( int $dbase_identifier , int $record_number )
Marks the given record to be deleted from the database.
Note:
To actually remove the record from the database, you must also call
dbase_pack().
Parameters
dbase_identifier
The database link identifier, returned by dbase_open() or
dbase_create().
record_number
An integer which spans from 1 to the number of records in the
database (as returned by dbase_numrecords()).
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* dbase_add_record() - Adds a record to a database
* dbase_replace_record() - Replaces a record in a database
----------------------------------------------------------------------
----------------------------------------------------------------------
dbase_get_header_info
(PHP 5)
dbase_get_header_info - Gets the header info of a database
Description
array dbase_get_header_info ( int $dbase_identifier )
Returns information on the column structure of the given database link
identifier.
Parameters
dbase_identifier
The database link identifier, returned by dbase_open() or
dbase_create().
Return Values
An indexed array with an entry for each column in the database. The array
index starts at 0.
Each array element contains an associative array of column information, as
described here:
name
The name of the column
type
The human-readable name for the dbase type of the column (i.e.
date, boolean, etc.)
length
The number of bytes this column can hold
precision
The number of digits of decimal precision for the column
format
A suggested printf() format specifier for the column
offset
The byte offset of the column from the start of the row
If the database header information cannot be read, FALSE is returned.
Examples
Example #1 Showing header information for a dBase database file
----------------------------------------------------------------------
----------------------------------------------------------------------
dbase_get_record_with_names
(PHP 4, PHP 5)
dbase_get_record_with_names - Gets a record from a database as an
associative array
Description
array dbase_get_record_with_names ( int $dbase_identifier , int
$record_number )
Gets a record from a dBase database as an associative array.
Parameters
dbase_identifier
The database link identifier, returned by dbase_open() or
dbase_create().
record_number
The index of the record.
Return Values
An associative array with the record. This will also include a key named
deleted which is set to 1 if the record has been marked for deletion (see
dbase_delete_record()).
Each field is converted to the appropriate PHP type, except:
* Dates are left as strings.
* Integers that would have caused an overflow (> 32 bits) are returned
as strings.
On error, dbase_get_record_with_names() will return FALSE.
Examples
Example #1 Listing all the registered members in the database
See Also
* dbase_get_record() - Gets a record from a database as an indexed array
----------------------------------------------------------------------
----------------------------------------------------------------------
dbase_get_record
(PHP 4, PHP 5)
dbase_get_record - Gets a record from a database as an indexed array
Description
array dbase_get_record ( int $dbase_identifier , int $record_number )
Gets a record from a database as an indexed array.
Parameters
dbase_identifier
The database link identifier, returned by dbase_open() or
dbase_create().
record_number
The index of the record.
Return Values
An indexed array with the record. This array will also include an
associative key named deleted which is set to 1 if the record has been
marked for deletion (see dbase_delete_record()).
Each field is converted to the appropriate PHP type, except:
* Dates are left as strings.
* Integers that would have caused an overflow (> 32 bits) are returned
as strings.
On error, dbase_get_record() will return FALSE.
See Also
* dbase_get_record_with_names() - Gets a record from a database as an
associative array
----------------------------------------------------------------------
----------------------------------------------------------------------
dbase_numfields
(PHP 4, PHP 5)
dbase_numfields - Gets the number of fields of a database
Description
int dbase_numfields ( int $dbase_identifier )
Gets the number of fields (columns) in the specified database.
Note:
Field numbers are between 0 and dbase_numfields($db)-1, while record
numbers are between 1 and dbase_numrecords($db).
Parameters
dbase_identifier
The database link identifier, returned by dbase_open() or
dbase_create().
Return Values
The number of fields in the database, or FALSE if an error occurs.
Examples
Example #1 dbase_numfields() Example
See Also
* dbase_numrecords() - Gets the number of records in a database
----------------------------------------------------------------------
----------------------------------------------------------------------
dbase_numrecords
(PHP 4, PHP 5)
dbase_numrecords - Gets the number of records in a database
Description
int dbase_numrecords ( int $dbase_identifier )
Gets the number of records (rows) in the specified database.
Note:
Record numbers are between 1 and dbase_numrecords($db), while field
numbers are between 0 and dbase_numfields($db)-1.
Parameters
dbase_identifier
The database link identifier, returned by dbase_open() or
dbase_create().
Return Values
The number of records in the database, or FALSE if an error occurs.
Examples
Example #1 Looping over all the records of the database
See Also
* dbase_numfields() - Gets the number of fields of a database
----------------------------------------------------------------------
----------------------------------------------------------------------
dbase_open
(PHP 4, PHP 5)
dbase_open - Opens a database
Description
int dbase_open ( string $filename , int $mode )
dbase_open() opens a dBase database with the given access mode.
Note: When safe mode is enabled, PHP checks whether the files or
directories being operated upon have the same UID (owner) as the script
that is being executed.
Note:
This function is affected by open_basedir.
Parameters
filename
The name of the database. It can be a relative or absolute path to
the file where dBase will store your data.
mode
An integer which correspond to those for the open() system call
(Typically 0 means read-only, 1 means write-only, and 2 means read
and write).
Note:
You can't open a dBase file in write-only mode as the function
will fail to read the headers information and thus you can't use
1 as mode.
Examples
Example #1 Opening a dBase database file
Return Values
Returns a database link identifier if the database is successfully opened,
or FALSE if an error occurred.
See Also
* dbase_create() - Creates a database
* dbase_close() - Closes a database
----------------------------------------------------------------------
----------------------------------------------------------------------
dbase_pack
(PHP 4, PHP 5)
dbase_pack - Packs a database
Description
bool dbase_pack ( int $dbase_identifier )
Packs the specified database by permanently deleting all records marked
for deletion using dbase_delete_record().
Parameters
dbase_identifier
The database link identifier, returned by dbase_open() or
dbase_create().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Emptying a dBase database
See Also
* dbase_delete_record() - Deletes a record from a database
----------------------------------------------------------------------
----------------------------------------------------------------------
dbase_replace_record
(PHP 4, PHP 5)
dbase_replace_record - Replaces a record in a database
Description
bool dbase_replace_record ( int $dbase_identifier , array $record , int
$record_number )
Replaces the given record in the database with the given data.
Parameters
dbase_identifier
The database link identifier, returned by dbase_open() or
dbase_create().
record
An indexed array of data. The number of items must be equal to the
number of fields in the database, otherwise dbase_replace_record()
will fail.
Note:
If you're using dbase_get_record() return value for this
parameter, remember to reset the key named deleted.
record_number
An integer which spans from 1 to the number of records in the
database (as returned by dbase_numrecords()).
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Updating a record in the database
See Also
* dbase_add_record() - Adds a record to a database
* dbase_delete_record() - Deletes a record from a database
----------------------------------------------------------------------
Table of Contents
* dbase_add_record - Adds a record to a database
* dbase_close - Closes a database
* dbase_create - Creates a database
* dbase_delete_record - Deletes a record from a database
* dbase_get_header_info - Gets the header info of a database
* dbase_get_record_with_names - Gets a record from a database as an
associative array
* dbase_get_record - Gets a record from a database as an indexed array
* dbase_numfields - Gets the number of fields of a database
* dbase_numrecords - Gets the number of records in a database
* dbase_open - Opens a database
* dbase_pack - Packs a database
* dbase_replace_record - Replaces a record in a database
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* dBase Functions
* dbase_add_record - Adds a record to a database
* dbase_close - Closes a database
* dbase_create - Creates a database
* dbase_delete_record - Deletes a record from a database
* dbase_get_header_info - Gets the header info of a database
* dbase_get_record_with_names - Gets a record from a database as an
associative array
* dbase_get_record - Gets a record from a database as an indexed
array
* dbase_numfields - Gets the number of fields of a database
* dbase_numrecords - Gets the number of records in a database
* dbase_open - Opens a database
* dbase_pack - Packs a database
* dbase_replace_record - Replaces a record in a database
----------------------------------------------------------------------
----------------------------------------------------------------------
DB++
----------------------------------------------------------------------
Introduction
db++, made by the German company >> Concept asa, is a relational database
system with high performance and low memory and disk usage in mind. While
providing SQL as an additional language interface, it is not really an SQL
database in the first place but provides its own AQL query language which
is much more influenced by the relational algebra than SQL is.
Concept asa always had an interest in supporting open source languages,
db++ has had Perl and Tcl call interfaces for years now and uses Tcl as
its internal stored procedure language.
Warning
This extension is EXPERIMENTAL. The behaviour of this extension including
the names of its functions and any other documentation surrounding this
extension may change without notice in a future release of PHP. This
extension should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
This extension relies on external client libraries so you have to have a
db++ client installed on the system you want to use this extension on.
>> Concept asa provides >> db++ Demo versions and >> documentation for
Linux, some other Unix versions. There is also a Windows version of db++,
but this extension doesn't support it (yet).
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
In order to build this extension yourself you need the db++ client
libraries and header files to be installed on your system (these are
included in the db++ installation archives by default). You have to run
configure with option --with-dbplus to build this extension.
configure looks for the client libraries and header files under the
default paths /usr/dbplus, /usr/local/dbplus and /opt/dblus. If you have
installed db++ in a different place you have add the installation path to
the configure option like this: --with-dbplus=/your/installation/path .
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
dbplus_relation
Most db++ functions operate on or return dbplus_relation resources. A
dbplus_relation is a handle to a stored relation or a relation generated
as the result of a query.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
Table of Contents
* db++ error codes
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
----------------------------------------------------------------------
db++ error codes
DB++ Error Codes
PHP Constant db++ constant meaning
DBPLUS_ERR_NOERR (integer) ERR_NOERR Null error condition
DBPLUS_ERR_DUPLICATE (integer) ERR_DUPLICATE Tried to insert a
duplicate tuple
DBPLUS_ERR_EOSCAN (integer) ERR_EOSCAN End of scan from rget()
DBPLUS_ERR_EMPTY (integer) ERR_EMPTY Relation is empty
(server)
DBPLUS_ERR_CLOSE (integer) ERR_CLOSE The server can't close
DBPLUS_ERR_WLOCKED (integer) ERR_WLOCKED The record is write
locked
DBPLUS_ERR_LOCKED (integer) ERR_LOCKED Relation was already
locked
DBPLUS_ERR_NOLOCK (integer) ERR_NOLOCK Relation cannot be
locked
DBPLUS_ERR_READ (integer) ERR_READ Read error on relation
DBPLUS_ERR_WRITE (integer) ERR_WRITE Write error on relation
DBPLUS_ERR_CREATE (integer) ERR_CREATE Create() system call
failed
DBPLUS_ERR_LSEEK (integer) ERR_LSEEK Lseek() system call
failed
DBPLUS_ERR_LENGTH (integer) ERR_LENGTH Tuple exceeds maximum
length
DBPLUS_ERR_OPEN (integer) ERR_OPEN Open() system call
failed
DBPLUS_ERR_WOPEN (integer) ERR_WOPEN Relation already opened
for writing
DBPLUS_ERR_MAGIC (integer) ERR_MAGIC File is not a relation
DBPLUS_ERR_VERSION (integer) ERR_VERSION File is a very old
relation
DBPLUS_ERR_PGSIZE (integer) ERR_PGSIZE Relation uses a
different page size
DBPLUS_ERR_CRC (integer) ERR_CRC Invalid crc in the
superpage
DBPLUS_ERR_PIPE (integer) ERR_PIPE Piped relation requires
lseek()
DBPLUS_ERR_NIDX (integer) ERR_NIDX Too many secondary
indices
DBPLUS_ERR_MALLOC (integer) ERR_MALLOC Malloc() call failed
DBPLUS_ERR_NUSERS (integer) ERR_NUSERS Error use of max users
DBPLUS_ERR_PREEXIT (integer) ERR_PREEXIT Caused by invalid usage
DBPLUS_ERR_ONTRAP (integer) ERR_ONTRAP Caused by a signal
DBPLUS_ERR_PREPROC (integer) ERR_PREPROC Error in the
preprocessor
DBPLUS_ERR_DBPARSE (integer) ERR_DBPARSE Error in the parser
DBPLUS_ERR_DBRUNERR (integer) ERR_DBRUNERR Run error in db
DBPLUS_ERR_DBPREEXIT (integer) ERR_DBPREEXIT Exit condition caused by
prexit() * procedure
DBPLUS_ERR_WAIT (integer) ERR_WAIT Wait a little (Simple
only)
DBPLUS_ERR_CORRUPT_TUPLE ERR_CORRUPT_TUPLE A client sent a corrupt
(integer) tuple
The Simple routines
DBPLUS_ERR_WARNING0 (integer) ERR_WARNING0 encountered a non fatal
error which was
corrected
The server should not
DBPLUS_ERR_PANIC (integer) ERR_PANIC really die but after a
disaster send ERR_PANIC
to all its clients
DBPLUS_ERR_FIFO (integer) ERR_FIFO Can't create a fifo
DBPLUS_ERR_PERM (integer) ERR_PERM Permission denied
DBPLUS_ERR_TCL (integer) ERR_TCL TCL_error
DBPLUS_ERR_RESTRICTED (integer) ERR_RESTRICTED Only two users
An error in the use of
DBPLUS_ERR_USER (integer) ERR_USER the library by an
application programmer
DBPLUS_ERR_UNKNOWN (integer) ERR_UNKNOWN
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
DB++ Functions
----------------------------------------------------------------------
dbplus_add
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_add - Add a tuple to a relation
Description
int dbplus_add ( resource $relation , array $tuple )
Adds a tuple to a relation.
Parameters
relation
tuple
An array of attribute/value pairs to be inserted into the given
relation.
After successful execution this array will contain the complete
data of the newly created tuple, including all implicitly set
domain fields like sequences.
Return Values
The function will return DBPLUS_ERR_NOERR on success or a db++ error code
on failure.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* dbplus_errcode() - Get error string for given errorcode or last error
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_aql
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_aql - Perform AQL query
Description
resource dbplus_aql ( string $query [, string $server [, string $dbpath ]]
)
Executes an AQL query on the given server and dbpath.
Parameters
query
The AQL query to be executed. Further information on the AQL
(Algebraic Query Language) is provided in the original db++
manual.
server
dbpath
Return Values
Returns a relation handle on success. The result data may be fetched from
this relation by calling dbplus_next() and dbplus_curr(). Other relation
access functions will not work on a result relation.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_chdir
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_chdir - Get/Set database virtual current directory
Description
string dbplus_chdir ([ string $newdir ] )
Changes the virtual current directory where relation files will be looked
for by dbplus_open().
Parameters
newdir
The new directory for relation files. You can omit this parameter
to query the current working directory.
Return Values
Returns the absolute path of the current directory.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_close
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_close - Close a relation
Description
mixed dbplus_close ( resource $relation )
Closes a relation previously opened by dbplus_open().
Parameters
relation
A relation opened by dbplus_open().
Return Values
Returns TRUE on success or DBPLUS_ERR_UNKNOWN on failure.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_curr
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_curr - Get current tuple from relation
Description
int dbplus_curr ( resource $relation , array &$tuple )
Reads the data for the current tuple for the given relation.
Parameters
relation
A relation opened by dbplus_open().
tuple
The data will be passed back in this parameter, as an associative
array.
Return Values
The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++
error code on failure.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* dbplus_first() - Get first tuple from relation
* dbplus_prev() - Get previous tuple from relation
* dbplus_next() - Get next tuple from relation
* dbplus_last() - Get last tuple from relation
* dbplus_errcode() - Get error string for given errorcode or last error
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_errcode
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_errcode - Get error string for given errorcode or last error
Description
string dbplus_errcode ([ int $errno ] )
Returns a clear error string for the given error code.
Parameters
errno
The error code. If not provided, the result code of the last db++
operation is assumed.
Return Values
Returns the error message.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_errno
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_errno - Get error code for last operation
Description
int dbplus_errno ( void )
Returns the error code returned by the last db++ operation.
Return Values
Returns the error code, as an integer.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* dbplus_errcode() - Get error string for given errorcode or last error
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_find
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_find - Set a constraint on a relation
Description
int dbplus_find ( resource $relation , array $constraints , mixed $tuple )
Places a constraint on the given relation.
Further calls to functions like dbplus_curr() or dbplus_next() will only
return tuples matching the given constraints.
Parameters
relation
A relation opened by dbplus_open().
constraints
Constraints are triplets of strings containing of a domain name, a
comparison operator and a comparison value. The constraints
parameter array may consist of a collection of string arrays, each
of which contains a domain, an operator and a value, or of a
single string array containing a multiple of three elements.
The comparison operator may be one of the following strings: '==',
'>', '>=', '<', '<=', '!=', '~' for a regular expression match and
'BAND' or 'BOR' for bitwise operations.
tuple
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* dbplus_unselect() - Remove a constraint from relation
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_first
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_first - Get first tuple from relation
Description
int dbplus_first ( resource $relation , array &$tuple )
Reads the data for the first tuple for the given relation, makes it the
current tuple and pass it back as an associative array in tuple.
Parameters
relation
A relation opened by dbplus_open().
tuple
Return Values
Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* dbplus_curr() - Get current tuple from relation
* dbplus_prev() - Get previous tuple from relation
* dbplus_next() - Get next tuple from relation
* dbplus_last() - Get last tuple from relation
* dbplus_errcode() - Get error string for given errorcode or last error
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_flush
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_flush - Flush all changes made on a relation
Description
int dbplus_flush ( resource $relation )
Writes all changes applied to relation since the last flush to disk.
Parameters
relation
A relation opened by dbplus_open().
Return Values
Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* dbplus_errcode() - Get error string for given errorcode or last error
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_freealllocks
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_freealllocks - Free all locks held by this client
Description
int dbplus_freealllocks ( void )
Frees all tuple locks held by this client.
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* dbplus_getlock() - Get a write lock on a tuple
* dbplus_freelock() - Release write lock on tuple
* dbplus_freerlocks() - Free all tuple locks on given relation
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_freelock
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_freelock - Release write lock on tuple
Description
int dbplus_freelock ( resource $relation , string $tuple )
Releases a write lock on the given tuple previously obtained by
dbplus_getlock().
Parameters
relation
A relation opened by dbplus_open().
tuple
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* dbplus_getlock() - Get a write lock on a tuple
* dbplus_freerlocks() - Free all tuple locks on given relation
* dbplus_freealllocks() - Free all locks held by this client
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_freerlocks
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_freerlocks - Free all tuple locks on given relation
Description
int dbplus_freerlocks ( resource $relation )
Frees all tuple locks held on the given relation.
Parameters
relation
A relation opened by dbplus_open().
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* dbplus_getlock() - Get a write lock on a tuple
* dbplus_freelock() - Release write lock on tuple
* dbplus_freealllocks() - Free all locks held by this client
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_getlock
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_getlock - Get a write lock on a tuple
Description
int dbplus_getlock ( resource $relation , string $tuple )
Requests a write lock on the specified tuple.
Parameters
relation
A relation opened by dbplus_open().
tuple
Return Values
Returns zero on success or a non-zero error code, especially
DBPLUS_ERR_WLOCKED on failure.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* dbplus_freelock() - Release write lock on tuple
* dbplus_freerlocks() - Free all tuple locks on given relation
* dbplus_freealllocks() - Free all locks held by this client
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_getunique
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_getunique - Get an id number unique to a relation
Description
int dbplus_getunique ( resource $relation , int $uniqueid )
Obtains a number guaranteed to be unique for the given relation and will
pass it back in the variable given as uniqueid.
Parameters
relation
A relation opened by dbplus_open().
uniqueid
Return Values
Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_info
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_info - Get information about a relation
Description
int dbplus_info ( resource $relation , string $key , array &$result )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
relation
A relation opened by dbplus_open().
key
result
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_last
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_last - Get last tuple from relation
Description
int dbplus_last ( resource $relation , array &$tuple )
Reads the data for the last tuple for the given relation, makes it the
current tuple and pass it back as an associative array in tuple.
Parameters
relation
A relation opened by dbplus_open().
tuple
Return Values
Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* dbplus_first() - Get first tuple from relation
* dbplus_curr() - Get current tuple from relation
* dbplus_prev() - Get previous tuple from relation
* dbplus_next() - Get next tuple from relation
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_lockrel
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_lockrel - Request write lock on relation
Description
int dbplus_lockrel ( resource $relation )
Requests a write lock on the given relation.
Other clients may still query the relation, but can't alter it while it is
locked.
Parameters
relation
A relation opened by dbplus_open().
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_next
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_next - Get next tuple from relation
Description
int dbplus_next ( resource $relation , array &$tuple )
Reads the data for the next tuple for the given relation, makes it the
current tuple and will pass it back as an associative array in tuple.
Parameters
relation
A relation opened by dbplus_open().
tuple
Return Values
Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* dbplus_first() - Get first tuple from relation
* dbplus_curr() - Get current tuple from relation
* dbplus_prev() - Get previous tuple from relation
* dbplus_last() - Get last tuple from relation
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_open
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_open - Open relation file
Description
resource dbplus_open ( string $name )
Opens the given relation file.
Parameters
name
Can be either a file name or a relative or absolute path name.
This will be mapped in any case to an absolute relation file path
on a specific host machine and server.
Return Values
On success a relation file resource (cursor) is returned which must be
used in any subsequent commands referencing the relation. Failure leads to
a zero return value, the actual error code may be asked for by calling
dbplus_errno().
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_prev
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_prev - Get previous tuple from relation
Description
int dbplus_prev ( resource $relation , array &$tuple )
Reads the data for the previous tuple for the given relation, makes it the
current tuple and will pass it back as an associative array in tuple.
Parameters
relation
A relation opened by dbplus_open().
tuple
Return Values
Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* dbplus_first() - Get first tuple from relation
* dbplus_curr() - Get current tuple from relation
* dbplus_next() - Get next tuple from relation
* dbplus_last() - Get last tuple from relation
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_rchperm
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_rchperm - Change relation permissions
Description
int dbplus_rchperm ( resource $relation , int $mask , string $user ,
string $group )
Changes access permissions as specified by mask, user and group. The
values for these are operating system specific.
Parameters
relation
A relation opened by dbplus_open().
mask
user
group
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_rcreate
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_rcreate - Creates a new DB++ relation
Description
resource dbplus_rcreate ( string $name , mixed $domlist [, bool $overwrite
] )
Creates a new relation. Any existing relation sharing the same name will
be overwritten if the relation is currently not in use and overwrite is
set to TRUE.
Parameters
name
domlist
A combination of domains. May be passed as a single domain name
string or as an array of domain names.
This parameter should contain the domain specification for the new
relation within an array of domain description strings. A domain
description string consists of a domain name unique to this
relation, a slash and a type specification character. See the db++
documentation, especially the dbcreate(1) manpage, for a
description of available type specifiers and their meanings.
Note:
This function will also accept a string with space delimited
domain description strings, but it is recommended to use an
array
overwrite
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_rcrtexact
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_rcrtexact - Creates an exact but empty copy of a relation including
indices
Description
mixed dbplus_rcrtexact ( string $name , resource $relation [, bool
$overwrite ] )
dbplus_rcrtexact() will create an exact but empty copy of the given
relation under a new name.
Parameters
name
relation
The copied relation, opened by dbplus_open().
overwrite
An existing relation by the same name will only be overwritten if
this parameter is set to TRUE and no other process is currently
using the relation.
Return Values
Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_rcrtlike
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_rcrtlike - Creates an empty copy of a relation with default indices
Description
mixed dbplus_rcrtlike ( string $name , resource $relation [, int
$overwrite ] )
dbplus_rcrtexact() will create an empty copy of the given relation under a
new name, but with default indices.
Parameters
name
relation
The copied relation, opened by dbplus_open().
overwrite
An existing relation by the same name will only be overwritten if
this parameter is set to TRUE and no other process is currently
using the relation.
Return Values
Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_resolve
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_resolve - Resolve host information for relation
Description
array dbplus_resolve ( string $relation_name )
dbplus_resolve() will try to resolve the given relation_name and find out
internal server id, real hostname and the database path on this host.
Parameters
relation_name
The relation name.
Return Values
Returns an array containing these values under the keys sid, host and
host_path or FALSE on error.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* dbplus_tcl() - Execute TCL code on server side
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_restorepos
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_restorepos - Restore position
Description
int dbplus_restorepos ( resource $relation , array $tuple )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
relation
A relation opened by dbplus_open().
tuple
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_rkeys
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_rkeys - Specify new primary key for a relation
Description
mixed dbplus_rkeys ( resource $relation , mixed $domlist )
dbplus_rkeys() will replace the current primary key for relation with the
combination of domains specified by domlist.
Parameters
relation
A relation opened by dbplus_open().
domlist
A combination of domains. May be passed as a single domain name
string or as an array of domain names.
Return Values
Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_ropen
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_ropen - Open relation file local
Description
resource dbplus_ropen ( string $name )
dbplus_ropen() will open the relation file locally for quick access
without any client/server overhead. Access is read only and only
dbplus_curr() and dbplus_next() may be applied to the returned relation.
Parameters
name
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_rquery
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_rquery - Perform local (raw) AQL query
Description
resource dbplus_rquery ( string $query [, string $dbpath ] )
dbplus_rquery() performs a local (raw) AQL query using an AQL interpreter
embedded into the db++ client library. dbplus_rquery() is faster than
dbplus_aql() but will work on local data only.
Parameters
query
dbpath
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_rrename
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_rrename - Rename a relation
Description
int dbplus_rrename ( resource $relation , string $name )
dbplus_rrename() will change the name of relation to name.
Parameters
relation
A relation opened by dbplus_open().
name
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_rsecindex
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_rsecindex - Create a new secondary index for a relation
Description
mixed dbplus_rsecindex ( resource $relation , mixed $domlist , int $type )
dbplus_rsecindex() will create a new secondary index for relation with
consists of the domains specified by domlist and is of type type
Parameters
relation
A relation opened by dbplus_open().
domlist
A combination of domains. May be passed as a single domain name
string or as an array of domain names.
type
Return Values
Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_runlink
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_runlink - Remove relation from filesystem
Description
int dbplus_runlink ( resource $relation )
dbplus_runlink() will close and remove the relation.
Parameters
relation
A relation opened by dbplus_open().
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_rzap
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_rzap - Remove all tuples from relation
Description
int dbplus_rzap ( resource $relation )
dbplus_rzap() will remove all tuples from relation.
Parameters
relation
A relation opened by dbplus_open().
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_savepos
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_savepos - Save position
Description
int dbplus_savepos ( resource $relation )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
relation
A relation opened by dbplus_open().
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_setindex
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_setindex - Set index
Description
int dbplus_setindex ( resource $relation , string $idx_name )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
relation
A relation opened by dbplus_open().
idx_name
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_setindexbynumber
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_setindexbynumber - Set index by number
Description
int dbplus_setindexbynumber ( resource $relation , int $idx_number )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
relation
A relation opened by dbplus_open().
idx_number
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_sql
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_sql - Perform SQL query
Description
resource dbplus_sql ( string $query [, string $server [, string $dbpath ]]
)
Warning
This function is currently not documented; only its argument list is
available.
Parameters
query
server
dbpath
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_tcl
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_tcl - Execute TCL code on server side
Description
string dbplus_tcl ( int $sid , string $script )
A db++ server will prepare a TCL interpreter for each client connection.
This interpreter will enable the server to execute TCL code provided by
the client as a sort of stored procedures to improve the performance of
database operations by avoiding client/server data transfers and context
switches.
dbplus_tcl() needs to pass the client connection id the TCL script code
should be executed by. dbplus_resolve() will provide this connection id.
The function will return whatever the TCL code returns or a TCL error
message if the TCL code fails.
Parameters
sid
script
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* dbplus_resolve() - Resolve host information for relation
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_tremove
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_tremove - Remove tuple and return new current tuple
Description
int dbplus_tremove ( resource $relation , array $tuple [, array &$current
] )
dbplus_tremove() removes tuple from relation if it perfectly matches a
tuple within the relation. current, if given, will contain the data of the
new current tuple after calling dbplus_tremove().
Parameters
relation
A relation opened by dbplus_open().
tuple
current
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_undo
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_undo - Undo
Description
int dbplus_undo ( resource $relation )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
relation
A relation opened by dbplus_open().
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_undoprepare
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_undoprepare - Prepare undo
Description
int dbplus_undoprepare ( resource $relation )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
relation
A relation opened by dbplus_open().
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_unlockrel
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_unlockrel - Give up write lock on relation
Description
int dbplus_unlockrel ( resource $relation )
Release a write lock previously obtained by dbplus_lockrel().
Parameters
relation
A relation opened by dbplus_open().
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_unselect
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_unselect - Remove a constraint from relation
Description
int dbplus_unselect ( resource $relation )
Calling dbplus_unselect() will remove a constraint previously set by
dbplus_find() on relation.
Parameters
relation
A relation opened by dbplus_open().
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_update
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_update - Update specified tuple in relation
Description
int dbplus_update ( resource $relation , array $old , array $new )
dbplus_update() replaces the old tuple with the data from the new one,
only if the old completely matches a tuple within relation.
Parameters
relation
A relation opened by dbplus_open().
old
The old tuple.
new
The new tuple.
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_xlockrel
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_xlockrel - Request exclusive lock on relation
Description
int dbplus_xlockrel ( resource $relation )
Request an exclusive lock on relation preventing even read access from
other clients.
Parameters
relation
A relation opened by dbplus_open().
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* dbplus_xunlockrel() - Free exclusive lock on relation
----------------------------------------------------------------------
----------------------------------------------------------------------
dbplus_xunlockrel
(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)
dbplus_xunlockrel - Free exclusive lock on relation
Description
int dbplus_xunlockrel ( resource $relation )
Releases an exclusive lock previously obtained by dbplus_xlockrel().
Parameters
relation
A relation opened by dbplus_open().
Return Values
Notes
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
----------------------------------------------------------------------
Table of Contents
* dbplus_add - Add a tuple to a relation
* dbplus_aql - Perform AQL query
* dbplus_chdir - Get/Set database virtual current directory
* dbplus_close - Close a relation
* dbplus_curr - Get current tuple from relation
* dbplus_errcode - Get error string for given errorcode or last error
* dbplus_errno - Get error code for last operation
* dbplus_find - Set a constraint on a relation
* dbplus_first - Get first tuple from relation
* dbplus_flush - Flush all changes made on a relation
* dbplus_freealllocks - Free all locks held by this client
* dbplus_freelock - Release write lock on tuple
* dbplus_freerlocks - Free all tuple locks on given relation
* dbplus_getlock - Get a write lock on a tuple
* dbplus_getunique - Get an id number unique to a relation
* dbplus_info - Get information about a relation
* dbplus_last - Get last tuple from relation
* dbplus_lockrel - Request write lock on relation
* dbplus_next - Get next tuple from relation
* dbplus_open - Open relation file
* dbplus_prev - Get previous tuple from relation
* dbplus_rchperm - Change relation permissions
* dbplus_rcreate - Creates a new DB++ relation
* dbplus_rcrtexact - Creates an exact but empty copy of a relation
including indices
* dbplus_rcrtlike - Creates an empty copy of a relation with default
indices
* dbplus_resolve - Resolve host information for relation
* dbplus_restorepos - Restore position
* dbplus_rkeys - Specify new primary key for a relation
* dbplus_ropen - Open relation file local
* dbplus_rquery - Perform local (raw) AQL query
* dbplus_rrename - Rename a relation
* dbplus_rsecindex - Create a new secondary index for a relation
* dbplus_runlink - Remove relation from filesystem
* dbplus_rzap - Remove all tuples from relation
* dbplus_savepos - Save position
* dbplus_setindex - Set index
* dbplus_setindexbynumber - Set index by number
* dbplus_sql - Perform SQL query
* dbplus_tcl - Execute TCL code on server side
* dbplus_tremove - Remove tuple and return new current tuple
* dbplus_undo - Undo
* dbplus_undoprepare - Prepare undo
* dbplus_unlockrel - Give up write lock on relation
* dbplus_unselect - Remove a constraint from relation
* dbplus_update - Update specified tuple in relation
* dbplus_xlockrel - Request exclusive lock on relation
* dbplus_xunlockrel - Free exclusive lock on relation
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* db++ error codes
* DB++ Functions
* dbplus_add - Add a tuple to a relation
* dbplus_aql - Perform AQL query
* dbplus_chdir - Get/Set database virtual current directory
* dbplus_close - Close a relation
* dbplus_curr - Get current tuple from relation
* dbplus_errcode - Get error string for given errorcode or last
error
* dbplus_errno - Get error code for last operation
* dbplus_find - Set a constraint on a relation
* dbplus_first - Get first tuple from relation
* dbplus_flush - Flush all changes made on a relation
* dbplus_freealllocks - Free all locks held by this client
* dbplus_freelock - Release write lock on tuple
* dbplus_freerlocks - Free all tuple locks on given relation
* dbplus_getlock - Get a write lock on a tuple
* dbplus_getunique - Get an id number unique to a relation
* dbplus_info - Get information about a relation
* dbplus_last - Get last tuple from relation
* dbplus_lockrel - Request write lock on relation
* dbplus_next - Get next tuple from relation
* dbplus_open - Open relation file
* dbplus_prev - Get previous tuple from relation
* dbplus_rchperm - Change relation permissions
* dbplus_rcreate - Creates a new DB++ relation
* dbplus_rcrtexact - Creates an exact but empty copy of a relation
including indices
* dbplus_rcrtlike - Creates an empty copy of a relation with
default indices
* dbplus_resolve - Resolve host information for relation
* dbplus_restorepos - Restore position
* dbplus_rkeys - Specify new primary key for a relation
* dbplus_ropen - Open relation file local
* dbplus_rquery - Perform local (raw) AQL query
* dbplus_rrename - Rename a relation
* dbplus_rsecindex - Create a new secondary index for a relation
* dbplus_runlink - Remove relation from filesystem
* dbplus_rzap - Remove all tuples from relation
* dbplus_savepos - Save position
* dbplus_setindex - Set index
* dbplus_setindexbynumber - Set index by number
* dbplus_sql - Perform SQL query
* dbplus_tcl - Execute TCL code on server side
* dbplus_tremove - Remove tuple and return new current tuple
* dbplus_undo - Undo
* dbplus_undoprepare - Prepare undo
* dbplus_unlockrel - Give up write lock on relation
* dbplus_unselect - Remove a constraint from relation
* dbplus_update - Update specified tuple in relation
* dbplus_xlockrel - Request exclusive lock on relation
* dbplus_xunlockrel - Free exclusive lock on relation
----------------------------------------------------------------------
----------------------------------------------------------------------
FrontBase
----------------------------------------------------------------------
Introduction
These functions allow you to access FrontBase database servers. More
information about FrontBase can be found at >> http://www.frontbase.com/.
Documentation for FrontBase can be found at
>> http://www.frontbase.com/cgi-bin/WebObjects/FBWebSite.woa.
Frontbase support has been added to PHP 4.0.6.
Note:
This extension has been moved to the >> PECL repository and is no longer
bundled with PHP as of PHP 5.3.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
You must install the FrontBase database server or at least the fbsql
client libraries to use this functions. You can get FrontBase from
>> http://www.frontbase.com/.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
In order to have these functions available, you must compile PHP with
fbsql support by using the --with-fbsql[=DIR] option. If you use this
option without specifying the path to fbsql, PHP will search for the fbsql
client libraries in the default installation location for the platform.
Users who installed FrontBase in a non standard directory should always
specify the path to fbsql: --with-fbsql=/path/to/fbsql . This will force
PHP to use the client libraries installed by FrontBase, avoiding any
conflicts.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
FrontBase configuration options
Name Default Changeable Changelog
fbsql.allow_persistent "1" PHP_INI_SYSTEM Available since
PHP 4.2.0.
fbsql.generate_warnings "0" PHP_INI_SYSTEM Available since
PHP 4.0.6.
fbsql.autocommit "1" PHP_INI_SYSTEM Available since
PHP 4.0.6.
fbsql.max_persistent "-1" PHP_INI_SYSTEM Available since
PHP 4.0.6.
fbsql.max_links "128" PHP_INI_SYSTEM Available since
PHP 4.0.6.
fbsql.max_connections "128" PHP_INI_SYSTEM Available since
PHP 4.0.6.
fbsql.max_results "128" PHP_INI_SYSTEM Available since
PHP 4.0.6.
Available since
fbsql.batchSize "1000" PHP_INI_SYSTEM PHP 4.2.0.
Removed in PHP
5.1.0.
fbsql.default_host NULL PHP_INI_SYSTEM Available since
PHP 4.0.6.
fbsql.default_user "_SYSTEM" PHP_INI_SYSTEM Available since
PHP 4.0.6.
fbsql.default_password "" PHP_INI_SYSTEM Available since
PHP 4.0.6.
fbsql.default_database "" PHP_INI_SYSTEM Available since
PHP 4.0.6.
fbsql.default_database_password "" PHP_INI_SYSTEM Available since
PHP 4.0.6.
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
FBSQL_ASSOC (integer)
FBSQL_NUM (integer)
FBSQL_BOTH (integer)
FBSQL_LOCK_DEFERRED (integer)
FBSQL_LOCK_OPTIMISTIC (integer)
FBSQL_LOCK_PESSIMISTIC (integer)
FBSQL_ISO_READ_UNCOMMITTED (integer)
FBSQL_ISO_READ_COMMITTED (integer)
FBSQL_ISO_REPEATABLE_READ (integer)
FBSQL_ISO_SERIALIZABLE (integer)
FBSQL_ISO_VERSIONED (integer)
FBSQL_UNKNOWN (integer)
FBSQL_STOPPED (integer)
FBSQL_STARTING (integer)
FBSQL_RUNNING (integer)
FBSQL_STOPPING (integer)
FBSQL_NOEXEC (integer)
FBSQL_LOB_DIRECT (integer)
FBSQL_LOB_HANDLE (integer)
----------------------------------------------------------------------
----------------------------------------------------------------------
FrontBase Functions
----------------------------------------------------------------------
fbsql_affected_rows
(PHP 4 >= 4.0.6, PHP 5)
fbsql_affected_rows - Get number of affected rows in previous FrontBase
operation
Description
int fbsql_affected_rows ([ resource $link_identifier ] )
fbsql_affected_rows() returns the number of rows affected by the last
INSERT, UPDATE or DELETE query associated with link_identifier.
Note:
If you are using transactions, you need to call fbsql_affected_rows()
after your INSERT, UPDATE, or DELETE query, not after the commit.
If the last query was a DELETE query with no WHERE clause, all of the
records will have been deleted from the table but this function will
return zero.
Note:
When using UPDATE, FrontBase will not update columns where the new value
is the same as the old value. This creates the possibility that
fbsql_affected_rows() may not actually equal the number of rows matched,
only the number of rows that were literally affected by the query.
Parameters
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
Return Values
If the last query failed, this function will return -1.
See Also
* fbsql_num_rows() - Get number of rows in result
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_autocommit
(PHP 4 >= 4.0.6, PHP 5)
fbsql_autocommit - Enable or disable autocommit
Description
bool fbsql_autocommit ( resource $link_identifier [, bool $OnOff ] )
Returns the current autocommit status.
Parameters
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
OnOff
If this optional parameter is given the auto commit status will be
changed.
With OnOff set to TRUE each statement will be committed
automatically, if no errors was found.
With OnOff set to FALSE the user must commit or rollback the
transaction using either fbsql_commit() or fbsql_rollback().
Return Values
Returns the current autocommit status, as a boolean.
See Also
* fbsql_commit() - Commits a transaction to the database
* fbsql_rollback() - Rollback a transaction to the database
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_blob_size
(PHP 4 >= 4.2.0, PHP 5)
fbsql_blob_size - Get the size of a BLOB
Description
int fbsql_blob_size ( string $blob_handle [, resource $link_identifier ] )
Returns the size of the given BLOB.
Parameters
blob_handle
A BLOB handle, returned by fbsql_create_blob().
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
Return Values
Returns the BLOB size as an integer, or FALSE on error.
See Also
* fbsql_clob_size() - Get the size of a CLOB
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_change_user
(PHP 4 >= 4.0.6, PHP 5)
fbsql_change_user - Change logged in user of the active connection
Description
bool fbsql_change_user ( string $user , string $password [, string
$database [, resource $link_identifier ]] )
fbsql_change_user() changes the logged in user of the specified
connection. If the new user and password authorization fails, the current
connected user stays active.
Parameters
user
The new user name.
password
The new user password.
database
If specified, this will be the default or current database after
the user has been changed.
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_clob_size
(PHP 4 >= 4.2.0, PHP 5)
fbsql_clob_size - Get the size of a CLOB
Description
int fbsql_clob_size ( string $clob_handle [, resource $link_identifier ] )
Returns the size of the given CLOB.
Parameters
clob_handle
A CLOB handle, returned by fbsql_create_clob().
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
Return Values
Returns the CLOB size as an integer, or FALSE on error.
See Also
* fbsql_blob_size() - Get the size of a BLOB
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_close
(PHP 4 >= 4.0.6, PHP 5)
fbsql_close - Close FrontBase connection
Description
bool fbsql_close ([ resource $link_identifier ] )
Closes the connection to the FrontBase server that's associated with the
specified link identifier.
Using fbsql_close() isn't usually necessary, as non-persistent open links
are automatically closed at the end of the script's execution.
Parameters
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 fbsql_close() example
See Also
* fbsql_connect() - Open a connection to a FrontBase Server
* fbsql_pconnect() - Open a persistent connection to a FrontBase Server
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_commit
(PHP 4 >= 4.0.6, PHP 5)
fbsql_commit - Commits a transaction to the database
Description
bool fbsql_commit ([ resource $link_identifier ] )
Ends the current transaction by writing all inserts, updates and deletes
to the disk and unlocking all row and table locks held by the transaction.
This command is only needed if autocommit is set to false.
Parameters
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* fbsql_autocommit() - Enable or disable autocommit
* fbsql_rollback() - Rollback a transaction to the database
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_connect
(PHP 4 >= 4.0.6, PHP 5)
fbsql_connect - Open a connection to a FrontBase Server
Description
resource fbsql_connect ([ string $hostname = ini_get("fbsql.default_host")
[, string $username = ini_get("fbsql.default_user") [, string $password =
ini_get("fbsql.default_password") ]]] )
fbsql_connect() establishes a connection to a FrontBase server.
If a second call is made to fbsql_connect() with the same arguments, no
new link will be established, but instead, the link identifier of the
already opened link will be returned.
The link to the server will be closed as soon as the execution of the
script ends, unless it's closed earlier by explicitly calling
fbsql_close().
Parameters
hostname
The server host name.
username
The user name for the connection.
password
The password for the connection.
Return Values
Returns a positive FrontBase link identifier on success, or FALSE on
errors.
Examples
Example #1 fbsql_connect() example
See Also
* fbsql_pconnect() - Open a persistent connection to a FrontBase Server
* fbsql_close() - Close FrontBase connection
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_create_blob
(PHP 4 >= 4.2.0, PHP 5)
fbsql_create_blob - Create a BLOB
Description
string fbsql_create_blob ( string $blob_data [, resource $link_identifier
] )
Creates a BLOB from the given data.
Parameters
blob_data
The BLOB data.
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
Return Values
Returns a resource handle to the newly created BLOB, which can be used
with insert and update commands to store the BLOB in the database.
Examples
Example #1 fbsql_create_blob() example
See Also
* fbsql_create_clob() - Create a CLOB
* fbsql_read_blob() - Read a BLOB from the database
* fbsql_read_clob() - Read a CLOB from the database
* fbsql_set_lob_mode() - Set the LOB retrieve mode for a FrontBase
result set
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_create_clob
(PHP 4 >= 4.2.0, PHP 5)
fbsql_create_clob - Create a CLOB
Description
string fbsql_create_clob ( string $clob_data [, resource $link_identifier
] )
Creates a CLOB from the given data.
Parameters
clob_data
The CLOB data.
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
Return Values
Returns a resource handle to the newly created CLOB, which can be used
with insert and update commands to store the CLOB in the database.
Examples
Example #1 fbsql_create_clob() example
See Also
* fbsql_create_blob() - Create a BLOB
* fbsql_read_blob() - Read a BLOB from the database
* fbsql_read_clob() - Read a CLOB from the database
* fbsql_set_lob_mode() - Set the LOB retrieve mode for a FrontBase
result set
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_create_db
(PHP 4 >= 4.0.6, PHP 5)
fbsql_create_db - Create a FrontBase database
Description
bool fbsql_create_db ( string $database_name [, resource $link_identifier
[, string $database_options ]] )
Attempts to create a new database on the specified server.
Parameters
database_name
The database name, as a string.
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
database_options
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 fbsql_create_db() example
See Also
* fbsql_drop_db() - Drop (delete) a FrontBase database
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_data_seek
(PHP 4 >= 4.0.6, PHP 5)
fbsql_data_seek - Move internal result pointer
Description
bool fbsql_data_seek ( resource $result , int $row_number )
Moves the internal row pointer of the FrontBase result associated with the
specified result identifier to point to the specified row number.
The next call to fbsql_fetch_row() would return that row.
Parameters
result
A result identifier returned by fbsql_query() or fbsql_db_query().
row_number
The row number. Starts at 0.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 fbsql_data_seek() example
=0; $i--) {
if (!fbsql_data_seek($result, $i)) {
printf("Cannot seek to row %d\n", $i);
continue;
}
if (!($row = fbsql_fetch_object($result)))
continue;
echo $row->last_name . $row->first_name . " \n";
}
fbsql_free_result($result);
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_database_password
(PHP 4 >= 4.0.6, PHP 5)
fbsql_database_password - Sets or retrieves the password for a FrontBase
database
Description
string fbsql_database_password ( resource $link_identifier [, string
$database_password ] )
Sets and retrieves the database password used by the connection. If a
database is protected by a database password, the user must call this
function before calling fbsql_select_db().
If no link is open, the function will try to establish a link as if
fbsql_connect() was called, and use it.
This function does not change the database password in the database nor
can it be used to retrieve the database password for a database.
Parameters
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
database_password
The database password, as a string. If given, the function sets
the database password for the specified link identifier.
Return Values
Returns the database password associated with the link identifier.
Examples
Example #1 fbsql_create_clob() example
See Also
* fbsql_connect() - Open a connection to a FrontBase Server
* fbsql_pconnect() - Open a persistent connection to a FrontBase Server
* fbsql_select_db() - Select a FrontBase database
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_database
(PHP 4 >= 4.0.6, PHP 5)
fbsql_database - Get or set the database name used with a connection
Description
string fbsql_database ( resource $link_identifier [, string $database ] )
Get or set the database name used with the connection.
Parameters
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
database
The database name. If given, the default database of the connexion
will be changed to database.
Return Values
Returns the name of the database used with this connection.
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_db_query
(PHP 4 >= 4.0.6, PHP 5)
fbsql_db_query - Send a FrontBase query
Description
resource fbsql_db_query ( string $database , string $query [, resource
$link_identifier ] )
Selects a database and executes a query on it.
Parameters
database
The database to be selected.
query
The SQL query to be executed.
Note:
The query string shall always end with a semicolon.
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
Return Values
Returns a positive FrontBase result identifier to the query result, or
FALSE on error.
See Also
* fbsql_query() - Send a FrontBase query
* fbsql_connect() - Open a connection to a FrontBase Server
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_db_status
(PHP 4 >= 4.0.7, PHP 5)
fbsql_db_status - Get the status for a given database
Description
int fbsql_db_status ( string $database_name [, resource $link_identifier ]
)
Gets the current status of the specified database.
Parameters
database_name
The database name.
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
Return Values
Returns an integer value with the current status. This can be one of the
following constants:
* FALSE - The exec handler for the host was invalid. This error will
occur when the link_identifier connects directly to a database by
using a port number. FBExec can be available on the server but no
connection has been made for it.
* FBSQL_UNKNOWN - The Status is unknown.
* FBSQL_STOPPED - The database is not running. Use fbsql_start_db() to
start the database.
* FBSQL_STARTING - The database is starting.
* FBSQL_RUNNING - The database is running and can be used to perform SQL
operations.
* FBSQL_STOPPING - The database is stopping.
* FBSQL_NOEXEC - FBExec is not running on the server and it is not
possible to get the status of the database.
See Also
* fbsql_start_db() - Start a database on local or remote server
* fbsql_stop_db() - Stop a database on local or remote server
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_drop_db
(PHP 4 >= 4.0.6, PHP 5)
fbsql_drop_db - Drop (delete) a FrontBase database
Description
bool fbsql_drop_db ( string $database_name [, resource $link_identifier ]
)
fbsql_drop_db() attempts to drop (remove) an entire database from the
server associated with the specified link identifier.
Parameters
database_name
The database name, as a string.
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* fbsql_create_db() - Create a FrontBase database
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_errno
(PHP 4 >= 4.0.6, PHP 5)
fbsql_errno - Returns the error number from previous operation
Description
int fbsql_errno ([ resource $link_identifier ] )
Returns the numerical value of the error message from previous FrontBase
operation.
Errors coming back from the fbsql database backend don't issue warnings.
Instead, use fbsql_errno() to retrieve the error code. Note that this
function only returns the error code from the most recently executed fbsql
function (not including fbsql_error() and fbsql_errno()), so if you want
to use it, make sure you check the value before calling another fbsql
function.
Parameters
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
Return Values
Returns the error number from the last fbsql function, or 0 (zero) if no
error occurred.
Examples
Example #1 fbsql_errno() Example
";
fbsql_select_db("nonexistentdb");
echo fbsql_errno() . ": " . fbsql_error() . " ";
$conn = fbsql_query("SELECT * FROM nonexistenttable;");
echo fbsql_errno() . ": " . fbsql_error() . " ";
?>
See Also
* fbsql_error() - Returns the error message from previous operation
* fbsql_warnings() - Enable or disable FrontBase warnings
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_error
(PHP 4 >= 4.0.6, PHP 5)
fbsql_error - Returns the error message from previous operation
Description
string fbsql_error ([ resource $link_identifier ] )
Returns the error message from previous FrontBase operation.
Errors coming back from the fbsql database backend don't issue warnings.
Instead, use fbsql_error() to retrieve the error text. Note that this
function only returns the error code from the most recently executed fbsql
function (not including fbsql_error() and fbsql_errno()), so if you want
to use it, make sure you check the value before calling another fbsql
function.
Parameters
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
Return Values
Returns the error text from the last fbsql function, or '' (the empty
string) if no error occurred.
Examples
Example #1 fbsql_error() Example
";
fbsql_select_db("nonexistentdb");
echo fbsql_errno() . ": " . fbsql_error() . " ";
$conn = fbsql_query("SELECT * FROM nonexistenttable;");
echo fbsql_errno() . ": " . fbsql_error() . " ";
?>
See Also
* fbsql_errno() - Returns the error number from previous operation
* fbsql_warnings() - Enable or disable FrontBase warnings
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_fetch_array
(PHP 4 >= 4.0.6, PHP 5)
fbsql_fetch_array - Fetch a result row as an associative array, a numeric
array, or both
Description
array fbsql_fetch_array ( resource $result [, int $result_type ] )
fbsql_fetch_array() is a combination of fbsql_fetch_row() and
fbsql_fetch_assoc().
An important thing to note is that using fbsql_fetch_array() is NOT
significantly slower than using fbsql_fetch_row(), while it provides a
significant added value.
Parameters
result
A result identifier returned by fbsql_query() or fbsql_db_query().
result_type
A constant and can take the following values: FBSQL_ASSOC,
FBSQL_NUM, or FBSQL_BOTH.
When using FBSQL_BOTH, in addition to storing the data in the
numeric indices of the result array, it also stores the data in
associative indices, using the field names as keys.
Return Values
Returns an array that corresponds to the fetched row, or FALSE if there
are no more rows.
If two or more columns of the result have the same field names, the last
column will take precedence. To access the other column(s) of the same
name, you must the numeric index of the column or make an alias for the
column.
select t1.f1 as foo t2.f1 as bar from t1, t2
Examples
Example #1 fbsql_fetch_array() example
\n";
echo "user_id: " . $row[0] . " \n";
echo "fullname: " . $row["fullname"] . " \n";
echo "fullname: " . $row[1] . " \n";
}
fbsql_free_result($result);
?>
See Also
* fbsql_fetch_row() - Get a result row as an enumerated array
* fbsql_fetch_assoc() - Fetch a result row as an associative array
* fbsql_fetch_object() - Fetch a result row as an object
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_fetch_assoc
(PHP 4 >= 4.0.6, PHP 5)
fbsql_fetch_assoc - Fetch a result row as an associative array
Description
array fbsql_fetch_assoc ( resource $result )
Calling fbsql_fetch_assoc() is equivalent to calling fbsql_fetch_array()
with FBSQL_ASSOC as second parameter. It only returns an associative
array.
This is the way fbsql_fetch_array() originally worked. If you need the
numeric indices as well as the associative, use fbsql_fetch_array().
An important thing to note is that using fbsql_fetch_assoc() is NOT
significantly slower than using fbsql_fetch_row(), while it provides a
significant added value.
Parameters
result
A result identifier returned by fbsql_query() or fbsql_db_query().
Return Values
Returns an associative array that corresponds to the fetched row, or FALSE
if there are no more rows.
If two or more columns of the result have the same field names, the last
column will take precedence. To access the other column(s) of the same
name, you must use fbsql_fetch_array() and have it return the numeric
indices as well.
Examples
Example #1 fbsql_fetch_assoc() example
See Also
* fbsql_fetch_row() - Get a result row as an enumerated array
* fbsql_fetch_array() - Fetch a result row as an associative array, a
numeric array, or both
* fbsql_fetch_object() - Fetch a result row as an object
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_fetch_field
(PHP 4 >= 4.0.6, PHP 5)
fbsql_fetch_field - Get column information from a result and return as an
object
Description
object fbsql_fetch_field ( resource $result [, int $field_offset ] )
Used in order to obtain information about fields in a certain query
result.
Parameters
result
A result identifier returned by fbsql_query() or fbsql_db_query().
field_offset
The numerical offset of the field. The field index starts at 0. If
not specified, the next field that wasn't yet retrieved by
fbsql_fetch_field() is retrieved.
Return Values
Returns an object containing field information, or FALSE on errors.
The properties of the object are:
* name - column name
* table - name of the table the column belongs to
* max_length - maximum length of the column
* not_null - 1 if the column cannot be NULL
* type - the type of the column
Examples
Example #1 fbsql_fetch_field() example
\n";
$meta = fbsql_fetch_field($result);
if (!$meta) {
echo "No information available \n";
}
echo "
max_length: $meta->max_length
name: $meta->name
not_null: $meta->not_null
table: $meta->table
type: $meta->type
";
$i++;
}
fbsql_free_result($result);
?>
See Also
* fbsql_field_seek() - Set result pointer to a specified field offset
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_fetch_lengths
(PHP 4 >= 4.0.6, PHP 5)
fbsql_fetch_lengths - Get the length of each output in a result
Description
array fbsql_fetch_lengths ( resource $result )
Stores the lengths of each result column in the last row returned by
fbsql_fetch_row(), fbsql_fetch_array() and fbsql_fetch_object() in an
array.
Parameters
result
A result identifier returned by fbsql_query() or fbsql_db_query().
Return Values
Returns an array, starting at offset 0, that corresponds to the lengths of
each field in the last row fetched by fbsql_fetch_row(), or FALSE on
error.
See Also
* fbsql_fetch_row() - Get a result row as an enumerated array
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_fetch_object
(PHP 4 >= 4.0.6, PHP 5)
fbsql_fetch_object - Fetch a result row as an object
Description
object fbsql_fetch_object ( resource $result )
fbsql_fetch_object() is similar to fbsql_fetch_array(), with one
difference - an object is returned, instead of an array. Indirectly, that
means that you can only access the data by the field names, and not by
their offsets (numbers are illegal property names).
Speed-wise, the function is identical to fbsql_fetch_array(), and almost
as quick as fbsql_fetch_row() (the difference is insignificant).
Parameters
result
A result identifier returned by fbsql_query() or fbsql_db_query().
Return Values
Returns an object with properties that correspond to the fetched row, or
FALSE if there are no more rows.
Examples
Example #1 fbsql_fetch_object() example
user_id;
echo $row->fullname;
}
fbsql_free_result($result);
?>
See Also
* fbsql_fetch_array() - Fetch a result row as an associative array, a
numeric array, or both
* fbsql_fetch_row() - Get a result row as an enumerated array
* fbsql_fetch_assoc() - Fetch a result row as an associative array
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_fetch_row
(PHP 4 >= 4.0.6, PHP 5)
fbsql_fetch_row - Get a result row as an enumerated array
Description
array fbsql_fetch_row ( resource $result )
fbsql_fetch_row() fetches one row of data from the result associated with
the specified result identifier.
Subsequent call to fbsql_fetch_row() would return the next row in the
result set, or FALSE if there are no more rows.
Parameters
result
A result identifier returned by fbsql_query() or fbsql_db_query().
Return Values
Returns an array that corresponds to the fetched row where each result
column is stored in an offset, starting at offset 0, or FALSE if there are
no more rows.
See Also
* fbsql_fetch_array() - Fetch a result row as an associative array, a
numeric array, or both
* fbsql_fetch_assoc() - Fetch a result row as an associative array
* fbsql_fetch_object() - Fetch a result row as an object
* fbsql_data_seek() - Move internal result pointer
* fbsql_fetch_lengths() - Get the length of each output in a result
* fbsql_result() - Get result data
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_field_flags
(PHP 4 >= 4.0.6, PHP 5)
fbsql_field_flags - Get the flags associated with the specified field in a
result
Description
string fbsql_field_flags ( resource $result [, int $field_offset ] )
Gets the flags associated with the specified field in a result.
Parameters
result
A result pointer returned by fbsql_list_fields().
field_offset
The numerical offset of the field. The field index starts at 0.
Return Values
Returns the field flags of the specified field as a single word per flag
separated by a single space, so that you can split the returned value
using explode().
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_field_len
(PHP 4 >= 4.0.6, PHP 5)
fbsql_field_len - Returns the length of the specified field
Description
int fbsql_field_len ( resource $result [, int $field_offset ] )
Returns the length of the specified field.
Parameters
result
A result pointer returned by fbsql_list_fields().
field_offset
The numerical offset of the field. The field index starts at 0.
Return Values
Returns the length of the specified field.
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_field_name
(PHP 4 >= 4.0.6, PHP 5)
fbsql_field_name - Get the name of the specified field in a result
Description
string fbsql_field_name ( resource $result [, int $field_index ] )
Returns the name of the specified field index.
Parameters
result
A result pointer returned by fbsql_list_fields().
field_index
The numerical offset of the field. The field index starts at 0.
Return Values
Returns the name as a string, or FALSE if the field doesn't exist.
Examples
Example #1 fbsql_field_name() example
The above example will output:
user_id
password
See Also
* fbsql_field_type() - Get the type of the specified field in a result
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_field_seek
(PHP 4 >= 4.0.6, PHP 5)
fbsql_field_seek - Set result pointer to a specified field offset
Description
bool fbsql_field_seek ( resource $result [, int $field_offset ] )
Seeks to the specified field offset. If the next call to
fbsql_fetch_field() doesn't include a field offset, the field offset
specified in fbsql_field_seek() will be returned.
Parameters
result
A result identifier returned by fbsql_query() or fbsql_db_query().
field_offset
The numerical offset of the field. The field index starts at 0.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* fbsql_fetch_field() - Get column information from a result and return
as an object
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_field_table
(PHP 4 >= 4.0.6, PHP 5)
fbsql_field_table - Get name of the table the specified field is in
Description
string fbsql_field_table ( resource $result [, int $field_offset ] )
Returns the name of the table that the specified field is in.
Parameters
result
A result identifier returned by fbsql_query() or fbsql_db_query().
field_offset
The numerical offset of the field. The field index starts at 0.
Return Values
Returns the name of the table, as a string.
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_field_type
(PHP 4 >= 4.0.6, PHP 5)
fbsql_field_type - Get the type of the specified field in a result
Description
string fbsql_field_type ( resource $result [, int $field_offset ] )
fbsql_field_type() is similar to the fbsql_field_name() function, but the
field type is returned instead.
Parameters
result
A result identifier returned by fbsql_query() or fbsql_db_query().
field_offset
The numerical offset of the field. The field index starts at 0.
Return Values
Returns the field type, as a string.
This can be one of int, real, string, blob, and others as detailed in the
>> FrontBase documentation.
Examples
Example #1 fbsql_field_type() example
";
echo "The table has the following fields ";
while ($i < $fields) {
$type = fbsql_field_type($result, $i);
$name = fbsql_field_name($result, $i);
$len = fbsql_field_len($result, $i);
$flags = fbsql_field_flags($result, $i);
echo $type . " " . $name . " " . $len . " " . $flags . " ";
$i++;
}
fbsql_close();
?>
See Also
* fbsql_field_name() - Get the name of the specified field in a result
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_free_result
(PHP 4 >= 4.0.6, PHP 5)
fbsql_free_result - Free result memory
Description
bool fbsql_free_result ( resource $result )
Frees all memory associated with the given result identifier.
fbsql_free_result() only needs to be called if you are concerned about how
much memory is being used for queries that return large result sets. All
associated result memory is automatically freed at the end of the script's
execution.
Parameters
result
A result identifier returned by fbsql_query() or fbsql_db_query().
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_get_autostart_info
(PHP 4 >= 4.0.7, PHP 5)
fbsql_get_autostart_info -
Description
array fbsql_get_autostart_info ([ resource $link_identifier ] )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_hostname
(PHP 4 >= 4.0.6, PHP 5)
fbsql_hostname - Get or set the host name used with a connection
Description
string fbsql_hostname ( resource $link_identifier [, string $host_name ] )
Gets or sets the host name used with a connection.
Parameters
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
host_name
If provided, this will be the new connection host name.
Return Values
Returns the current host name used for the connection.
See Also
* fbsql_username() - Get or set the username for the connection
* fbsql_password() - Get or set the user password used with a connection
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_insert_id
(PHP 4 >= 4.0.6, PHP 5)
fbsql_insert_id - Get the id generated from the previous INSERT operation
Description
int fbsql_insert_id ([ resource $link_identifier ] )
Gets the id generated from the previous INSERT operation which created a
DEFAULT UNIQUE value.
Note:
The value of the FrontBase SQL function fbsql_insert_id() always
contains the most recently generated DEFAULT UNIQUE value, and is not
reset between queries.
Parameters
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
Return Values
Returns the ID generated from the previous INSERT query, or 0 if the
previous query does not generate an DEFAULT UNIQUE value.
If you need to save the value for later, be sure to call this function
immediately after the query that generates the value.
See Also
* fbsql_affected_rows() - Get number of affected rows in previous
FrontBase operation
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_list_dbs
(PHP 4 >= 4.0.6, PHP 5)
fbsql_list_dbs - List databases available on a FrontBase server
Description
resource fbsql_list_dbs ([ resource $link_identifier ] )
Return a result pointer containing the databases available from the
current fbsql daemon. Use the fbsql_tablename() to traverse this result
pointer.
Parameters
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
Return Values
Returns a result pointer or FALSE on error.
Examples
Example #1 fbsql_list_dbs() example
Database . "\n";
}
?>
The above example will output something similar to:
database1
database2
database3
...
Note:
The above code would just as easily work with fbsql_fetch_row() or other
similar functions.
See Also
* fbsql_list_fields() - List FrontBase result fields
* fbsql_list_tables() - List tables in a FrontBase database
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_list_fields
(PHP 4 >= 4.0.6, PHP 5)
fbsql_list_fields - List FrontBase result fields
Description
resource fbsql_list_fields ( string $database_name , string $table_name [,
resource $link_identifier ] )
Retrieves information about the given table.
Parameters
database_name
The database name.
table_name
The table name.
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
Return Values
Returns a result pointer which can be used with the fbsql_field_xxx
functions, or FALSE on error.
Errors/Exceptions
A string describing the error will be placed in $phperrmsg, and unless the
function was called as @fbsql() then this error string will also be
printed out.
Examples
Example #1 fbsql_list_fields() example
The above example will output something similar to:
field1
field2
field3
...
See Also
* fbsql_field_len() - Returns the length of the specified field
* fbsql_field_name() - Get the name of the specified field in a result
* fbsql_field_type() - Get the type of the specified field in a result
* fbsql_field_flags() - Get the flags associated with the specified
field in a result
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_list_tables
(PHP 4 >= 4.0.6, PHP 5)
fbsql_list_tables - List tables in a FrontBase database
Description
resource fbsql_list_tables ( string $database [, resource $link_identifier
] )
Returns a result pointer describing the database.
Parameters
database
The database name.
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
Return Values
Returns a result pointer which can be used with the fbsql_tablename()
function to read the actual table names, or FALSE on error.
See Also
* fbsql_list_fields() - List FrontBase result fields
* fbsql_list_dbs() - List databases available on a FrontBase server
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_next_result
(PHP 4 >= 4.0.6, PHP 5)
fbsql_next_result - Move the internal result pointer to the next result
Description
bool fbsql_next_result ( resource $result )
When sending more than one SQL statement to the server or executing a
stored procedure with multiple results will cause the server to return
multiple result sets. This function will test for additional results
available form the server. If an additional result set exists it will free
the existing result set and prepare to fetch the words from the new result
set.
Parameters
result
A result identifier returned by fbsql_query() or fbsql_db_query().
Return Values
Returns TRUE if an additional result set was available or FALSE otherwise.
Examples
Example #1 fbsql_next_result() example
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_num_fields
(PHP 4 >= 4.0.6, PHP 5)
fbsql_num_fields - Get number of fields in result
Description
int fbsql_num_fields ( resource $result )
Returns the number of fields in the given result set.
Parameters
result
A result identifier returned by fbsql_query() or fbsql_db_query().
Return Values
Returns the number of fields, as an integer.
See Also
* fbsql_db_query() - Send a FrontBase query
* fbsql_query() - Send a FrontBase query
* fbsql_fetch_field() - Get column information from a result and return
as an object
* fbsql_num_rows() - Get number of rows in result
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_num_rows
(PHP 4 >= 4.0.6, PHP 5)
fbsql_num_rows - Get number of rows in result
Description
int fbsql_num_rows ( resource $result )
Gets the number of rows in the given result set.
This function is only valid for SELECT statements. To retrieve the number
of rows returned from a INSERT, UPDATE or DELETE query, use
fbsql_affected_rows().
Parameters
result
A result identifier returned by fbsql_query() or fbsql_db_query().
Return Values
Returns the number of rows returned by the last SELECT statement.
Examples
Example #1 fbsql_num_rows() example
See Also
* fbsql_affected_rows() - Get number of affected rows in previous
FrontBase operation
* fbsql_connect() - Open a connection to a FrontBase Server
* fbsql_select_db() - Select a FrontBase database
* fbsql_query() - Send a FrontBase query
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_password
(PHP 4 >= 4.0.6, PHP 5)
fbsql_password - Get or set the user password used with a connection
Description
string fbsql_password ( resource $link_identifier [, string $password ] )
Get or set the user password used with a connection.
Parameters
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
password
If provided, this will be the new connection password.
Return Values
Returns the current password used for the connection.
See Also
* fbsql_username() - Get or set the username for the connection
* fbsql_hostname() - Get or set the host name used with a connection
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_pconnect
(PHP 4 >= 4.0.6, PHP 5)
fbsql_pconnect - Open a persistent connection to a FrontBase Server
Description
resource fbsql_pconnect ([ string $hostname =
ini_get("fbsql.default_host") [, string $username =
ini_get("fbsql.default_user") [, string $password =
ini_get("fbsql.default_password") ]]] )
Establishes a persistent connection to a FrontBase server.
To set the server port number, use fbsql_select_db().
fbsql_pconnect() acts very much like fbsql_connect() with two major
differences:
First, when connecting, the function would first try to find a
(persistent) link that's already open with the same host, username and
password. If one is found, an identifier for it will be returned instead
of opening a new connection.
Second, the connection to the SQL server will not be closed when the
execution of the script ends. Instead, the link will remain open for
future use.
This type of links is therefore called 'persistent'.
Parameters
hostname
The server host name.
username
The user name for the connection.
password
The password for the connection.
Return Values
Returns a positive FrontBase persistent link identifier on success, or
FALSE on error.
See Also
* fbsql_connect() - Open a connection to a FrontBase Server
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_query
(PHP 4 >= 4.0.6, PHP 5)
fbsql_query - Send a FrontBase query
Description
resource fbsql_query ( string $query [, resource $link_identifier [, int
$batch_size ]] )
Sends a query to the currently active database on the server.
If the query succeeds, you can call fbsql_num_rows() to find out how many
rows were returned for a SELECT statement or fbsql_affected_rows() to find
out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE
statement.
Parameters
query
The SQL query to be executed.
Note:
The query string shall always end with a semicolon.
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
batch_size
Return Values
fbsql_query() returns TRUE (non-zero) or FALSE to indicate whether or not
the query succeeded. A return value of TRUE means that the query was legal
and could be executed by the server. It does not indicate anything about
the number of rows affected or returned. It is perfectly possible for a
query to succeed but affect no rows or return no rows.
For SELECT statements, fbsql_query() returns a new result identifier that
you can pass to fbsql_result().
fbsql_query() will also fail and return FALSE if you don't have permission
to access the table(s) referenced by the query.
Examples
The following query is syntactically invalid, so fbsql_query() fails and
returns FALSE:
Example #1 fbsql_query() example
The following query is semantically invalid if my_col is not a column in
the table my_tbl, so fbsql_query() fails and returns FALSE:
Example #2 fbsql_query() example
See Also
* fbsql_affected_rows() - Get number of affected rows in previous
FrontBase operation
* fbsql_db_query() - Send a FrontBase query
* fbsql_free_result() - Free result memory
* fbsql_result() - Get result data
* fbsql_select_db() - Select a FrontBase database
* fbsql_connect() - Open a connection to a FrontBase Server
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_read_blob
(PHP 4 >= 4.2.0, PHP 5)
fbsql_read_blob - Read a BLOB from the database
Description
string fbsql_read_blob ( string $blob_handle [, resource $link_identifier
] )
Reads BLOB data from the database.
If a select statement contains BLOB and/or CLOB columns FrontBase will
return the data directly when data is fetched. This default behavior can
be changed with fbsql_set_lob_mode() so the fetch functions will return
handles to BLOB and CLOB data. If a handle is fetched a user must call
fbsql_read_blob() to get the actual BLOB data from the database.
Parameters
blob_handle
A BLOB handle, returned by fbsql_create_blob().
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
Return Values
Returns a string containing the specified BLOB data.
Examples
Example #1 fbsql_read_blob() example
See Also
* fbsql_create_blob() - Create a BLOB
* fbsql_read_clob() - Read a CLOB from the database
* fbsql_set_lob_mode() - Set the LOB retrieve mode for a FrontBase
result set
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_read_clob
(PHP 4 >= 4.2.0, PHP 5)
fbsql_read_clob - Read a CLOB from the database
Description
string fbsql_read_clob ( string $clob_handle [, resource $link_identifier
] )
Reads CLOB data from the database.
If a select statement contains BLOB and/or CLOB columns FrontBase will
return the data directly when data is fetched. This default behavior can
be changed with fbsql_set_lob_mode() so the fetch functions will return
handles to BLOB and CLOB data. If a handle is fetched a user must call
fbsql_read_clob() to get the actual CLOB data from the database.
Parameters
clob_handle
A CLOB handle, returned by fbsql_create_clob().
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
Return Values
Returns a string containing the specified CLOB data.
Examples
Example #1 fbsql_read_clob() example
See Also
* fbsql_create_clob() - Create a CLOB
* fbsql_read_blob() - Read a BLOB from the database
* fbsql_set_lob_mode() - Set the LOB retrieve mode for a FrontBase
result set
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_result
(PHP 4 >= 4.0.6, PHP 5)
fbsql_result - Get result data
Description
mixed fbsql_result ( resource $result [, int $row [, mixed $field ]] )
Returns the contents of one cell from a FrontBase result set.
When working on large result sets, you should consider using one of the
functions that fetch an entire row (specified below). As these functions
return the contents of multiple cells in one function call, they're MUCH
quicker than fbsql_result().
Calls to fbsql_result() should not be mixed with calls to other functions
that deal with the result set.
Parameters
result
A result identifier returned by fbsql_query() or fbsql_db_query().
row
field
Can be the field's offset, or the field's name, or the field's
table dot field's name (tablename.fieldname).
If the column name has been aliased ('select foo as bar from...'),
use the alias instead of the column name.
Note:
Specifying a numeric offset for the field argument is much
quicker than specifying a fieldname or tablename.fieldname
argument.
Return Values
See Also
Recommended high-performance alternatives:
* fbsql_fetch_row() - Get a result row as an enumerated array
* fbsql_fetch_array() - Fetch a result row as an associative array, a
numeric array, or both
* fbsql_fetch_assoc() - Fetch a result row as an associative array
* fbsql_fetch_object() - Fetch a result row as an object
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_rollback
(PHP 4 >= 4.0.6, PHP 5)
fbsql_rollback - Rollback a transaction to the database
Description
bool fbsql_rollback ([ resource $link_identifier ] )
Ends the current transaction by rolling back all statements issued since
last commit.
This command is only needed if autocommit is set to false.
Parameters
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* fbsql_autocommit() - Enable or disable autocommit
* fbsql_commit() - Commits a transaction to the database
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_rows_fetched
(PHP 5 >= 5.1.0)
fbsql_rows_fetched - Get the number of rows affected by the last statement
Description
int fbsql_rows_fetched ( resource $result )
Gets the number of rows affected by the last statement.
Parameters
result
A result identifier returned by fbsql_query() or fbsql_db_query().
Return Values
Returns the number of rows, as an integer.
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_select_db
(PHP 4 >= 4.0.6, PHP 5)
fbsql_select_db - Select a FrontBase database
Description
bool fbsql_select_db ([ string $database_name [, resource $link_identifier
]] )
Sets the current active database on the given link identifier.
The client contacts FBExec to obtain the port number to use for the
connection to the database. If the database name is a number the system
will use that as a port number and it will not ask FBExec for the port
number. The FrontBase server can be stared as FRontBase -FBExec=No
-port= .
Every subsequent call to fbsql_query() will be made on the active
database.
Parameters
database_name
The name of the database to be selected.
If the database is protected with a database password, the you
must call fbsql_database_password() before selecting the database.
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* fbsql_connect() - Open a connection to a FrontBase Server
* fbsql_pconnect() - Open a persistent connection to a FrontBase Server
* fbsql_database_password() - Sets or retrieves the password for a
FrontBase database
* fbsql_query() - Send a FrontBase query
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_set_characterset
(PHP 5 >= 5.1.0)
fbsql_set_characterset - Change input/output character set
Description
void fbsql_set_characterset ( resource $link_identifier , int
$characterset [, int $in_out_both ] )
Warning
This function is currently not documented; only its argument list is
available.
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_set_lob_mode
(PHP 4 >= 4.2.0, PHP 5)
fbsql_set_lob_mode - Set the LOB retrieve mode for a FrontBase result set
Description
bool fbsql_set_lob_mode ( resource $result , int $lob_mode )
Sets the mode for retrieving LOB data from the database.
When BLOB and CLOB data is retrieved in FrontBase it can be retrieved
direct or indirect. Direct retrieved LOB data will always be fetched no
matter the setting of the lob mode. If the LOB data is less than 512 bytes
it will always be retrieved directly.
Parameters
result
A result identifier returned by fbsql_query() or fbsql_db_query().
lob_mode
Can be one of:
* FBSQL_LOB_DIRECT - LOB data is retrieved directly. When data
is fetched from the database with fbsql_fetch_row(), and
other fetch functions, all CLOB and BLOB columns will be
returned as ordinary columns. This is the default value on a
new FrontBase result.
* FBSQL_LOB_HANDLE - LOB data is retrieved as handles to the
data. When data is fetched from the database with
fbsql_fetch_row(), and other fetch functions, LOB data will
be returned as a handle to the data if the data is stored
indirect or the data if it is stored direct. If a handle is
returned it will be a 27 byte string formatted as
@'000000000000000000000000'.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* fbsql_create_blob() - Create a BLOB
* fbsql_create_clob() - Create a CLOB
* fbsql_read_blob() - Read a BLOB from the database
* fbsql_read_clob() - Read a CLOB from the database
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_set_password
(PHP 5)
fbsql_set_password - Change the password for a given user
Description
bool fbsql_set_password ( resource $link_identifier , string $user ,
string $password , string $old_password )
Changes the password for the given user.
Parameters
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
user
The user name.
password
The new password to be set.
old_password
The old password to be replaced.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_set_transaction
(PHP 4 >= 4.2.0, PHP 5)
fbsql_set_transaction - Set the transaction locking and isolation
Description
void fbsql_set_transaction ( resource $link_identifier , int $locking ,
int $isolation )
Sets the transaction locking and isolation.
Parameters
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
locking
The type of locking to be set. It can be one of the following
constants: FBSQL_LOCK_DEFERRED, FBSQL_LOCK_OPTIMISTIC, or
FBSQL_LOCK_PESSIMISTIC.
isolation
The type of isolation to be set. It can be one of the following
constants: FBSQL_ISO_READ_UNCOMMITTED, FBSQL_ISO_READ_COMMITTED,
FBSQL_ISO_REPEATABLE_READ, FBSQL_ISO_SERIALIZABLE, or
FBSQL_ISO_VERSIONED.
Return Values
No value is returned.
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_start_db
(PHP 4 >= 4.0.6, PHP 5)
fbsql_start_db - Start a database on local or remote server
Description
bool fbsql_start_db ( string $database_name [, resource $link_identifier
[, string $database_options ]] )
Start a database on local or remote server.
Parameters
database_name
The database name.
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
database_options
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* fbsql_db_status() - Get the status for a given database
* fbsql_stop_db() - Stop a database on local or remote server
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_stop_db
(PHP 4 >= 4.0.6, PHP 5)
fbsql_stop_db - Stop a database on local or remote server
Description
bool fbsql_stop_db ( string $database_name [, resource $link_identifier ]
)
Stops a database on local or remote server.
Parameters
database_name
The database name.
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* fbsql_db_status() - Get the status for a given database
* fbsql_start_db() - Start a database on local or remote server
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_table_name
(PHP 4 >= 4.2.0, PHP 5)
fbsql_table_name - Get table name of field
Description
string fbsql_table_name ( resource $result , int $index )
fbsql_table_name() gets the name of the current table in the given result
set.
The fbsql_num_rows() function may be used to determine the number of
tables in the result pointer.
Parameters
result
A result pointer returned by fbsql_list_tables().
index
Integer index for the current table.
Return Values
Returns the name of the table, as a string.
Examples
Example #1 fbsql_table_name() example
";
$i++;
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_tablename
(PHP 4 >= 4.2.0, PHP 5)
fbsql_tablename - Alias of fbsql_table_name()
Description
This function is an alias of: fbsql_table_name().
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_username
(PHP 4 >= 4.0.6, PHP 5)
fbsql_username - Get or set the username for the connection
Description
string fbsql_username ( resource $link_identifier [, string $username ] )
Get or set the username used for the connection.
Parameters
link_identifier
A FrontBase link identifier returned by fbsql_connect() or
fbsql_pconnect().
If optional and not specified, the function will try to find an
open link to the FrontBase server and if no such link is found it
will try to create one as if fbsql_connect() was called with no
arguments.
username
If provided, this is the new username to set.
Return Values
Returns the current username used with the connection, as a string.
See Also
* fbsql_password() - Get or set the user password used with a connection
* fbsql_hostname() - Get or set the host name used with a connection
----------------------------------------------------------------------
----------------------------------------------------------------------
fbsql_warnings
(PHP 4 >= 4.0.6, PHP 5)
fbsql_warnings - Enable or disable FrontBase warnings
Description
bool fbsql_warnings ([ bool $OnOff ] )
Enables or disables FrontBase warnings.
Parameters
OnOff
Whether to enable warnings or no.
Return Values
Returns TRUE if warnings is turned on, FALSE otherwise.
See Also
* fbsql_errno() - Returns the error number from previous operation
* fbsql_error() - Returns the error message from previous operation
----------------------------------------------------------------------
Table of Contents
* fbsql_affected_rows - Get number of affected rows in previous
FrontBase operation
* fbsql_autocommit - Enable or disable autocommit
* fbsql_blob_size - Get the size of a BLOB
* fbsql_change_user - Change logged in user of the active connection
* fbsql_clob_size - Get the size of a CLOB
* fbsql_close - Close FrontBase connection
* fbsql_commit - Commits a transaction to the database
* fbsql_connect - Open a connection to a FrontBase Server
* fbsql_create_blob - Create a BLOB
* fbsql_create_clob - Create a CLOB
* fbsql_create_db - Create a FrontBase database
* fbsql_data_seek - Move internal result pointer
* fbsql_database_password - Sets or retrieves the password for a
FrontBase database
* fbsql_database - Get or set the database name used with a connection
* fbsql_db_query - Send a FrontBase query
* fbsql_db_status - Get the status for a given database
* fbsql_drop_db - Drop (delete) a FrontBase database
* fbsql_errno - Returns the error number from previous operation
* fbsql_error - Returns the error message from previous operation
* fbsql_fetch_array - Fetch a result row as an associative array, a
numeric array, or both
* fbsql_fetch_assoc - Fetch a result row as an associative array
* fbsql_fetch_field - Get column information from a result and return as
an object
* fbsql_fetch_lengths - Get the length of each output in a result
* fbsql_fetch_object - Fetch a result row as an object
* fbsql_fetch_row - Get a result row as an enumerated array
* fbsql_field_flags - Get the flags associated with the specified field
in a result
* fbsql_field_len - Returns the length of the specified field
* fbsql_field_name - Get the name of the specified field in a result
* fbsql_field_seek - Set result pointer to a specified field offset
* fbsql_field_table - Get name of the table the specified field is in
* fbsql_field_type - Get the type of the specified field in a result
* fbsql_free_result - Free result memory
* fbsql_get_autostart_info - Description
* fbsql_hostname - Get or set the host name used with a connection
* fbsql_insert_id - Get the id generated from the previous INSERT
operation
* fbsql_list_dbs - List databases available on a FrontBase server
* fbsql_list_fields - List FrontBase result fields
* fbsql_list_tables - List tables in a FrontBase database
* fbsql_next_result - Move the internal result pointer to the next
result
* fbsql_num_fields - Get number of fields in result
* fbsql_num_rows - Get number of rows in result
* fbsql_password - Get or set the user password used with a connection
* fbsql_pconnect - Open a persistent connection to a FrontBase Server
* fbsql_query - Send a FrontBase query
* fbsql_read_blob - Read a BLOB from the database
* fbsql_read_clob - Read a CLOB from the database
* fbsql_result - Get result data
* fbsql_rollback - Rollback a transaction to the database
* fbsql_rows_fetched - Get the number of rows affected by the last
statement
* fbsql_select_db - Select a FrontBase database
* fbsql_set_characterset - Change input/output character set
* fbsql_set_lob_mode - Set the LOB retrieve mode for a FrontBase result
set
* fbsql_set_password - Change the password for a given user
* fbsql_set_transaction - Set the transaction locking and isolation
* fbsql_start_db - Start a database on local or remote server
* fbsql_stop_db - Stop a database on local or remote server
* fbsql_table_name - Get table name of field
* fbsql_tablename - Alias of fbsql_table_name
* fbsql_username - Get or set the username for the connection
* fbsql_warnings - Enable or disable FrontBase warnings
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* FrontBase Functions
* fbsql_affected_rows - Get number of affected rows in previous
FrontBase operation
* fbsql_autocommit - Enable or disable autocommit
* fbsql_blob_size - Get the size of a BLOB
* fbsql_change_user - Change logged in user of the active
connection
* fbsql_clob_size - Get the size of a CLOB
* fbsql_close - Close FrontBase connection
* fbsql_commit - Commits a transaction to the database
* fbsql_connect - Open a connection to a FrontBase Server
* fbsql_create_blob - Create a BLOB
* fbsql_create_clob - Create a CLOB
* fbsql_create_db - Create a FrontBase database
* fbsql_data_seek - Move internal result pointer
* fbsql_database_password - Sets or retrieves the password for a
FrontBase database
* fbsql_database - Get or set the database name used with a
connection
* fbsql_db_query - Send a FrontBase query
* fbsql_db_status - Get the status for a given database
* fbsql_drop_db - Drop (delete) a FrontBase database
* fbsql_errno - Returns the error number from previous operation
* fbsql_error - Returns the error message from previous operation
* fbsql_fetch_array - Fetch a result row as an associative array, a
numeric array, or both
* fbsql_fetch_assoc - Fetch a result row as an associative array
* fbsql_fetch_field - Get column information from a result and
return as an object
* fbsql_fetch_lengths - Get the length of each output in a result
* fbsql_fetch_object - Fetch a result row as an object
* fbsql_fetch_row - Get a result row as an enumerated array
* fbsql_field_flags - Get the flags associated with the specified
field in a result
* fbsql_field_len - Returns the length of the specified field
* fbsql_field_name - Get the name of the specified field in a
result
* fbsql_field_seek - Set result pointer to a specified field offset
* fbsql_field_table - Get name of the table the specified field is
in
* fbsql_field_type - Get the type of the specified field in a
result
* fbsql_free_result - Free result memory
* fbsql_get_autostart_info - Description
* fbsql_hostname - Get or set the host name used with a connection
* fbsql_insert_id - Get the id generated from the previous INSERT
operation
* fbsql_list_dbs - List databases available on a FrontBase server
* fbsql_list_fields - List FrontBase result fields
* fbsql_list_tables - List tables in a FrontBase database
* fbsql_next_result - Move the internal result pointer to the next
result
* fbsql_num_fields - Get number of fields in result
* fbsql_num_rows - Get number of rows in result
* fbsql_password - Get or set the user password used with a
connection
* fbsql_pconnect - Open a persistent connection to a FrontBase
Server
* fbsql_query - Send a FrontBase query
* fbsql_read_blob - Read a BLOB from the database
* fbsql_read_clob - Read a CLOB from the database
* fbsql_result - Get result data
* fbsql_rollback - Rollback a transaction to the database
* fbsql_rows_fetched - Get the number of rows affected by the last
statement
* fbsql_select_db - Select a FrontBase database
* fbsql_set_characterset - Change input/output character set
* fbsql_set_lob_mode - Set the LOB retrieve mode for a FrontBase
result set
* fbsql_set_password - Change the password for a given user
* fbsql_set_transaction - Set the transaction locking and isolation
* fbsql_start_db - Start a database on local or remote server
* fbsql_stop_db - Stop a database on local or remote server
* fbsql_table_name - Get table name of field
* fbsql_tablename - Alias of fbsql_table_name
* fbsql_username - Get or set the username for the connection
* fbsql_warnings - Enable or disable FrontBase warnings
----------------------------------------------------------------------
----------------------------------------------------------------------
filePro
----------------------------------------------------------------------
Introduction
These functions allow read-only access to data stored in filePro
databases.
filePro is a registered trademark of fP Technologies, Inc. You can find
more information about filePro at >> http://www.fptech.com/.
Note:
This extension has been moved to the >> PECL repository and is no longer
bundled with PHP as of PHP 5.2.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
filePro support in PHP is not enabled by default. To enable the bundled
read-only filePro support you need to use the--enable-filepro
configuration option when compiling PHP.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
This extension has no constants defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
filePro Functions
----------------------------------------------------------------------
filepro_fieldcount
(PHP 4, PHP 5 <= 5.1.6)
filepro_fieldcount - Find out how many fields are in a filePro database
Description
int filepro_fieldcount ( void )
Returns the number of fields (columns) in the opened filePro database.
Return Values
Returns the number of fields in the opened filePro database, or FALSE on
errors.
See Also
* filepro() - Read and verify the map file
----------------------------------------------------------------------
----------------------------------------------------------------------
filepro_fieldname
(PHP 4, PHP 5 <= 5.1.6)
filepro_fieldname - Gets the name of a field
Description
string filepro_fieldname ( int $field_number )
Returns the name of the field corresponding to field_number.
Parameters
field_number
The field number.
Return Values
Returns the name of the field as a string, or FALSE on errors.
----------------------------------------------------------------------
----------------------------------------------------------------------
filepro_fieldtype
(PHP 4, PHP 5 <= 5.1.6)
filepro_fieldtype - Gets the type of a field
Description
string filepro_fieldtype ( int $field_number )
Returns the edit type of the field corresponding to field_number.
Parameters
field_number
The field number.
Return Values
Returns the edit type of the field as a string, or FALSE on errors.
----------------------------------------------------------------------
----------------------------------------------------------------------
filepro_fieldwidth
(PHP 4, PHP 5 <= 5.1.6)
filepro_fieldwidth - Gets the width of a field
Description
int filepro_fieldwidth ( int $field_number )
Returns the width of the field corresponding to field_number.
Parameters
field_number
The field number.
Return Values
Returns the width of the field as a integer, or FALSE on errors.
----------------------------------------------------------------------
----------------------------------------------------------------------
filepro_retrieve
(PHP 4, PHP 5 <= 5.1.6)
filepro_retrieve - Retrieves data from a filePro database
Description
string filepro_retrieve ( int $row_number , int $field_number )
Returns the data from the specified location in the database.
Note: When safe mode is enabled, PHP checks whether the files or
directories being operated upon have the same UID (owner) as the script
that is being executed.
Parameters
row_number
The row number. Must be between zero and the total number of rows
minus one (0..filepro_rowcount() - 1)
field_number
The field number. Accepts values between zero and the total number
of fields minus one (0..filepro_fieldcount() - 1)
Return Values
Returns the specified data, or FALSE on errors.
----------------------------------------------------------------------
----------------------------------------------------------------------
filepro_rowcount
(PHP 4, PHP 5 <= 5.1.6)
filepro_rowcount - Find out how many rows are in a filePro database
Description
int filepro_rowcount ( void )
Returns the number of rows in the opened filePro database.
Note: When safe mode is enabled, PHP checks whether the files or
directories being operated upon have the same UID (owner) as the script
that is being executed.
Return Values
Returns the number of rows in the opened filePro database, or FALSE on
errors.
See Also
* filepro() - Read and verify the map file
----------------------------------------------------------------------
----------------------------------------------------------------------
filepro
(PHP 4, PHP 5 <= 5.1.6)
filepro - Read and verify the map file
Description
bool filepro ( string $directory )
This reads and verifies the map file, storing the field count and info.
No locking is done, so you should avoid modifying your filePro database
while it may be opened in PHP.
Note: When safe mode is enabled, PHP checks whether the files or
directories being operated upon have the same UID (owner) as the script
that is being executed.
Parameters
directory
The map directory.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
Table of Contents
* filepro_fieldcount - Find out how many fields are in a filePro
database
* filepro_fieldname - Gets the name of a field
* filepro_fieldtype - Gets the type of a field
* filepro_fieldwidth - Gets the width of a field
* filepro_retrieve - Retrieves data from a filePro database
* filepro_rowcount - Find out how many rows are in a filePro database
* filepro - Read and verify the map file
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* filePro Functions
* filepro_fieldcount - Find out how many fields are in a filePro
database
* filepro_fieldname - Gets the name of a field
* filepro_fieldtype - Gets the type of a field
* filepro_fieldwidth - Gets the width of a field
* filepro_retrieve - Retrieves data from a filePro database
* filepro_rowcount - Find out how many rows are in a filePro
database
* filepro - Read and verify the map file
----------------------------------------------------------------------
----------------------------------------------------------------------
Firebird/InterBase
----------------------------------------------------------------------
Introduction
Firebird/InterBase is a relational database offering many ANSI SQL-92
features that runs on Linux, Windows, and a variety of Unix platforms.
Firebird/InterBase offers excellent concurrency, high performance, and
powerful language support for stored procedures and triggers. It has been
used in production systems, under a variety of names since 1981.
InterBase is the name of the closed-source variant of this RDBMS that was
developed by Borland/Inprise. More information about InterBase is
available at >> http://www.borland.com/interbase/.
Firebird is a commercially independent project of C and C++ programmers,
technical advisors and supporters developing and enhancing a
multi-platform relational database management system based on the source
code released by Inprise Corp (now known as Borland Software Corp) under
the InterBase Public License v.1.0 on 25 July, 2000. More information
about Firebird is available at >> http://www.firebirdsql.org/.
Note:
This extension supports InterBase versions 5 and up and all versions of
Firebird. Support for InterBase version 5.x will be dropped in PHP 5.
This database uses a single quote (') character for escaping, a behavior
similar to the Sybase database, add to your php.ini the following
directive:
magic_quotes_sybase = On
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
To enable InterBase support configure PHP --with-interbase[=DIR] , where
DIR is the InterBase base install directory, which defaults to
/usr/interbase.
Note: Note to Win32 Users
In order for this extension to work, there are DLL files that must be
available to the Windows system PATH. For information on how to do this,
see the FAQ entitled "How do I add my PHP directory to the PATH on
Windows". Although copying DLL files from the PHP folder into the
Windows system directory also works (because the system directory is by
default in the system's PATH), this is not recommended. This extension
requires the following files to be in the PATH: gds32.dll
In case you installed the InterBase database server on the same machine
PHP is running on, you will have this DLL already. Therefore you don't
need to worry because gds32.dll will already be in the PATH.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
InterBase configuration options
Name Default Changeable Changelog
ibase.allow_persistent "1" PHP_INI_SYSTEM
ibase.max_persistent "-1" PHP_INI_SYSTEM
ibase.max_links "-1" PHP_INI_SYSTEM
ibase.default_db NULL PHP_INI_SYSTEM Available since PHP
5.0.0.
ibase.default_user NULL PHP_INI_ALL
ibase.default_password NULL PHP_INI_ALL
ibase.default_charset NULL PHP_INI_ALL Available since PHP
5.0.0.
ibase.timestampformat "%Y-%m-%d PHP_INI_ALL
%H:%M:%S"
ibase.dateformat "%Y-%m-%d" PHP_INI_ALL
ibase.timeformat "%H:%M:%S" PHP_INI_ALL
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
ibase.allow_persistent boolean
Whether to allow persistent connections to Firebird/InterBase.
ibase.max_persistent integer
The maximum number of persistent Firebird/InterBase connections
per process. New connections created with ibase_pconnect() will be
non-persistent if this number would be exceeded.
ibase.max_links integer
The maximum number of Firebird/InterBase connections per process,
including persistent connections.
ibase.default_db string
The default database to connect to when ibase_[p]connect() is
called without specifying a database name. If this value is set
and SQL safe mode is enabled, no other connections than to this
database will be allowed.
ibase.default_user string
The user name to use when connecting to a database if no user name
is specified.
ibase.default_password string
The password to use when connecting to a database if no password
is specified.
ibase.default_charset string
The character set to use when connecting to a database if no
character set is specified.
ibase.timestampformat string
ibase.dateformat string
ibase.timeformat string
These directives are used to set the date and time formats that
are used when returning dates and times from a result set, or when
binding arguments to date and time parameters.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
The following constants can be passed to ibase_trans() to specify
transaction behaviour.
Firebird/InterBase transaction flags
Constant Description
The default transaction settings are to be used. This
IBASE_DEFAULT default is determined by the client library, which
defines it as IBASE_WRITE|IBASE_CONCURRENCY|IBASE_WAIT
in most cases.
IBASE_READ Starts a read-only transaction.
IBASE_WRITE Starts a read-write transaction.
Starts a transaction with the isolation level set to
IBASE_CONSISTENCY 'consistency', which means the transaction cannot read
from tables that are being modified by other concurrent
transactions.
Starts a transaction with the isolation level set to
'concurrency' (or 'snapshot'), which means the
IBASE_CONCURRENCY transaction has access to all tables, but cannot see
changes that were committed by other transactions after
the transaction was started.
Starts a transaction with the isolation level set to
'read committed'. This flag should be combined with
either IBASE_REC_VERSION or IBASE_REC_NO_VERSION. This
isolation level allows access to changes that were
IBASE_COMMITTED committed after the transaction was started. If
IBASE_REC_NO_VERSION was specified, only the latest
version of a row can be read. If IBASE_REC_VERSION was
specified, a row can even be read when a modification to
it is pending in a concurrent transaction.
IBASE_WAIT Indicated that a transaction should wait and retry when
a conflict occurs.
IBASE_NOWAIT Indicated that a transaction should fail immediately
when a conflict occurs.
The following constants can be passed to ibase_fetch_row(),
ibase_fetch_assoc() or ibase_fetch_object() to specify fetch behaviour.
Firebird/InterBase fetch flags
Constant Description
Also available as IBASE_TEXTfor backward compatibility.
IBASE_FETCH_BLOBS Causes BLOB contents to be fetched inline, instead of
being fetched as BLOB identifiers.
Causes arrays to be fetched inline. Otherwise, array
IBASE_FETCH_ARRAYS identifiers are returned. Array identifiers can only be
used as arguments to INSERT operations, as no functions
to handle array identifiers are currently available.
Causes date and time fields not to be returned as
strings, but as UNIX timestamps (the number of seconds
IBASE_UNIXTIME since the epoch, which is 1-Jan-1970 0:00 UTC). Might
be problematic if used with dates before 1970 on some
systems.
The following constants are used to pass requests and options to the
service API functions (ibase_server_info(), ibase_db_info(),
ibase_backup(), ibase_restore() and ibase_maintain_db()). Please refer to
the Firebird/InterBase manuals for the meaning of these options.
IBASE_BKP_IGNORE_CHECKSUMS
IBASE_BKP_IGNORE_LIMBO
IBASE_BKP_METADATA_ONLY
IBASE_BKP_NO_GARBAGE_COLLECT
IBASE_BKP_OLD_DESCRIPTIONS
IBASE_BKP_NON_TRANSPORTABLE
IBASE_BKP_CONVERT
Options to ibase_backup()
IBASE_RES_DEACTIVATE_IDX
IBASE_RES_NO_SHADOW
IBASE_RES_NO_VALIDITY
IBASE_RES_ONE_AT_A_TIME
IBASE_RES_REPLACE
IBASE_RES_CREATE
IBASE_RES_USE_ALL_SPACE
Options to ibase_restore()
IBASE_PRP_PAGE_BUFFERS
IBASE_PRP_SWEEP_INTERVAL
IBASE_PRP_SHUTDOWN_DB
IBASE_PRP_DENY_NEW_TRANSACTIONS
IBASE_PRP_DENY_NEW_ATTACHMENTS
IBASE_PRP_RESERVE_SPACE
IBASE_PRP_RES_USE_FULL
IBASE_PRP_RES
IBASE_PRP_WRITE_MODE
IBASE_PRP_WM_ASYNC
IBASE_PRP_WM_SYNC
IBASE_PRP_ACCESS_MODE
IBASE_PRP_AM_READONLY
IBASE_PRP_AM_READWRITE
IBASE_PRP_SET_SQL_DIALECT
IBASE_PRP_ACTIVATE
IBASE_PRP_DB_ONLINE
IBASE_RPR_CHECK_DB
IBASE_RPR_IGNORE_CHECKSUM
IBASE_RPR_KILL_SHADOWS
IBASE_RPR_MEND_DB
IBASE_RPR_VALIDATE_DB
IBASE_RPR_FULL
IBASE_RPR_SWEEP_DB
Options to ibase_maintain_db()
IBASE_STS_DATA_PAGES
IBASE_STS_DB_LOG
IBASE_STS_HDR_PAGES
IBASE_STS_IDX_PAGES
IBASE_STS_SYS_RELATIONS
Options to ibase_db_info()
IBASE_SVC_SERVER_VERSION
IBASE_SVC_IMPLEMENTATION
IBASE_SVC_GET_ENV
IBASE_SVC_GET_ENV_LOCK
IBASE_SVC_GET_ENV_MSG
IBASE_SVC_USER_DBPATH
IBASE_SVC_SVR_DB_INFO
IBASE_SVC_GET_USERS
Options to ibase_server_info()
----------------------------------------------------------------------
----------------------------------------------------------------------
Firebird/InterBase Functions
----------------------------------------------------------------------
ibase_add_user
(PHP 4 >= 4.2.0, PHP 5)
ibase_add_user - Add a user to a security database (only for IB6 or later)
Description
bool ibase_add_user ( resource $service_handle , string $user_name ,
string $password [, string $first_name [, string $middle_name [, string
$last_name ]]] )
PHP 4 uses server, dba_user_name and dba_user_password instead of
service_handle parameter.
Warning
This function is currently not documented; only its argument list is
available.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ibase_modify_user() - Modify a user to a security database (only for
IB6 or later)
* ibase_delete_user() - Delete a user from a security database (only for
IB6 or later)
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_affected_rows
(PHP 5)
ibase_affected_rows - Return the number of rows that were affected by the
previous query
Description
int ibase_affected_rows ([ resource $link_identifier ] )
This function returns the number of rows that were affected by the
previous query (INSERT, UPDATE or DELETE) that was executed from within
the specified transaction context.
Parameters
link_identifier
A transaction context. If link_identifier is a connection
resource, its default transaction is used.
Return Values
Returns the number of rows as an integer.
See Also
* ibase_query() - Execute a query on an InterBase database
* ibase_execute() - Execute a previously prepared query
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_backup
(PHP 5)
ibase_backup - Initiates a backup task in the service manager and returns
immediately
Description
mixed ibase_backup ( resource $service_handle , string $source_db , string
$dest_file [, int $options = 0 [, bool $verbose = false ]] )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_blob_add
(PHP 4, PHP 5)
ibase_blob_add - Add data into a newly created blob
Description
void ibase_blob_add ( resource $blob_handle , string $data )
ibase_blob_add() adds data into a blob created with ibase_blob_create().
Parameters
blob_handle
A blob handle opened with ibase_blob_create().
data
The data to be added.
Return Values
No value is returned.
See Also
* ibase_blob_cancel() - Cancel creating blob
* ibase_blob_close() - Close blob
* ibase_blob_create() - Create a new blob for adding data
* ibase_blob_import() - Create blob, copy file in it, and close it
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_blob_cancel
(PHP 4, PHP 5)
ibase_blob_cancel - Cancel creating blob
Description
bool ibase_blob_cancel ( resource $blob_handle )
This function will discard a BLOB if it has not yet been closed by
ibase_blob_close().
Parameters
blob_handle
A BLOB handle opened with ibase_blob_create().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ibase_blob_close() - Close blob
* ibase_blob_create() - Create a new blob for adding data
* ibase_blob_import() - Create blob, copy file in it, and close it
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_blob_close
(PHP 4, PHP 5)
ibase_blob_close - Close blob
Description
mixed ibase_blob_close ( resource $blob_handle )
This function closes a BLOB that has either been opened for reading by
ibase_blob_open() or has been opened for writing by ibase_blob_create().
Parameters
blob_handle
A BLOB handle opened with ibase_blob_create() or
ibase_blob_open().
Return Values
If the BLOB was being read, this function returns TRUE on success, if the
BLOB was being written to, this function returns a string containing the
BLOB id that has been assigned to it by the database. On failure, this
function returns FALSE.
See Also
* ibase_blob_cancel() - Cancel creating blob
* ibase_blob_open() - Open blob for retrieving data parts
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_blob_create
(PHP 4, PHP 5)
ibase_blob_create - Create a new blob for adding data
Description
resource ibase_blob_create ([ resource $link_identifier = NULL ] )
ibase_blob_create() creates a new BLOB for filling with data.
Parameters
link_identifier
An InterBase link identifier. If omitted, the last opened link is
assumed.
Return Values
Returns a BLOB handle for later use with ibase_blob_add() or FALSE on
failure.
See Also
* ibase_blob_add() - Add data into a newly created blob
* ibase_blob_cancel() - Cancel creating blob
* ibase_blob_close() - Close blob
* ibase_blob_import() - Create blob, copy file in it, and close it
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_blob_echo
(PHP 4, PHP 5)
ibase_blob_echo - Output blob contents to browser
Description
bool ibase_blob_echo ( string $blob_id )
bool ibase_blob_echo ( resource $link_identifier , string $blob_id )
This function opens a BLOB for reading and sends its contents directly to
standard output (the browser, in most cases).
Parameters
link_identifier
An InterBase link identifier. If omitted, the last opened link is
assumed.
blob_id
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ibase_blob_open() - Open blob for retrieving data parts
* ibase_blob_close() - Close blob
* ibase_blob_get() - Get len bytes data from open blob
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_blob_get
(PHP 4, PHP 5)
ibase_blob_get - Get len bytes data from open blob
Description
string ibase_blob_get ( resource $blob_handle , int $len )
This function returns at most len bytes from a BLOB that has been opened
for reading by ibase_blob_open().
Note:
It is not possible to read from a BLOB that has been opened for writing
by ibase_blob_create().
Parameters
blob_handle
A BLOB handle opened with ibase_blob_open().
len
Size of returned data.
Return Values
Returns at most len bytes from the BLOB, or FALSE on failure.
Examples
Example #1 ibase_blob_get() example
BLOB_VALUE);
$blob_hndl = ibase_blob_open($data->BLOB_VALUE);
echo ibase_blob_get($blob_hndl, $blob_data[0]);
?>
Whilst this example doesn't do much more than a
'ibase_blob_echo($data->BLOB_VALUE)' would do, it does show you how to get
information into a $variable to manipulate as you please.
See Also
* ibase_blob_open() - Open blob for retrieving data parts
* ibase_blob_close() - Close blob
* ibase_blob_echo() - Output blob contents to browser
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_blob_import
(PHP 4, PHP 5)
ibase_blob_import - Create blob, copy file in it, and close it
Description
string ibase_blob_import ( resource $link_identifier , resource
$file_handle )
string ibase_blob_import ( resource $file_handle )
This function creates a BLOB, reads an entire file into it, closes it and
returns the assigned BLOB id.
Parameters
link_identifier
An InterBase link identifier. If omitted, the last opened link is
assumed.
file_handle
The file handle is a handle returned by fopen().
Return Values
Returns the BLOB id on success, or FALSE on error.
Examples
Example #1 ibase_blob_import() example
See Also
* ibase_blob_add() - Add data into a newly created blob
* ibase_blob_cancel() - Cancel creating blob
* ibase_blob_close() - Close blob
* ibase_blob_create() - Create a new blob for adding data
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_blob_info
(PHP 4, PHP 5)
ibase_blob_info - Return blob length and other useful info
Description
array ibase_blob_info ( resource $link_identifier , string $blob_id )
array ibase_blob_info ( string $blob_id )
Returns the BLOB length and other useful information.
Parameters
link_identifier
An InterBase link identifier. If omitted, the last opened link is
assumed.
blob_id
A BLOB id.
Return Values
Returns an array containing information about a BLOB. The information
returned consists of the length of the BLOB, the number of segments it
contains, the size of the largest segment, and whether it is a stream BLOB
or a segmented BLOB.
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_blob_open
(PHP 4, PHP 5)
ibase_blob_open - Open blob for retrieving data parts
Description
resource ibase_blob_open ( resource $link_identifier , string $blob_id )
resource ibase_blob_open ( string $blob_id )
Opens an existing BLOB for reading.
Parameters
link_identifier
An InterBase link identifier. If omitted, the last opened link is
assumed.
blob_id
A BLOB id.
Return Values
Returns a BLOB handle for later use with ibase_blob_get() or FALSE on
failure.
See Also
* ibase_blob_close() - Close blob
* ibase_blob_echo() - Output blob contents to browser
* ibase_blob_get() - Get len bytes data from open blob
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_close
(PHP 4, PHP 5)
ibase_close - Close a connection to an InterBase database
Description
bool ibase_close ([ resource $connection_id = NULL ] )
Closes the link to an InterBase database that's associated with a
connection id returned from ibase_connect(). Default transaction on link
is committed, other transactions are rolled back.
Parameters
connection_id
An InterBase link identifier returned from ibase_connect(). If
omitted, the last opened link is assumed.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ibase_connect() - Open a connection to an InterBase database
* ibase_pconnect() - Open a persistent connection to an InterBase
database
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_commit_ret
(PHP 5)
ibase_commit_ret - Commit a transaction without closing it
Description
bool ibase_commit_ret ([ resource $link_or_trans_identifier = NULL ] )
Commits a transaction without closing it.
Parameters
link_or_trans_identifier
If called without an argument, this function commits the default
transaction of the default link. If the argument is a connection
identifier, the default transaction of the corresponding
connection will be committed. If the argument is a transaction
identifier, the corresponding transaction will be committed. The
transaction context will be retained, so statements executed from
within this transaction will not be invalidated.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_commit
(PHP 4, PHP 5)
ibase_commit - Commit a transaction
Description
bool ibase_commit ([ resource $link_or_trans_identifier = NULL ] )
Commits a transaction.
Parameters
link_or_trans_identifier
If called without an argument, this function commits the default
transaction of the default link. If the argument is a connection
identifier, the default transaction of the corresponding
connection will be committed. If the argument is a transaction
identifier, the corresponding transaction will be committed.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_connect
(PHP 4, PHP 5)
ibase_connect - Open a connection to an InterBase database
Description
resource ibase_connect ([ string $database [, string $username [, string
$password [, string $charset [, int $buffers [, int $dialect [, string
$role [, int $sync ]]]]]]]] )
Establishes a connection to an InterBase server.
In case a second call is made to ibase_connect() with the same arguments,
no new link will be established, but instead, the link identifier of the
already opened link will be returned. The link to the server will be
closed as soon as the execution of the script ends, unless it's closed
earlier by explicitly calling ibase_close().
Parameters
database
The database argument has to be a valid path to database file on
the server it resides on. If the server is not local, it must be
prefixed with either 'hostname:' (TCP/IP), '//hostname/' (NetBEUI)
or 'hostname@' (IPX/SPX), depending on the connection protocol
used.
username
The user name. Can be set with the ibase.default_user php.ini
directive.
password
The password for username. Can be set with the
ibase.default_password php.ini directive.
charset
charset is the default character set for a database.
buffers
buffers is the number of database buffers to allocate for the
server-side cache. If 0 or omitted, server chooses its own
default.
dialect
dialect selects the default SQL dialect for any statement executed
within a connection, and it defaults to the highest one supported
by client libraries. Functional only with InterBase 6 and up.
role
Functional only with InterBase 5 and up.
sync
Return Values
Returns an InterBase link identifier on success, or FALSE on error.
Errors/Exceptions
If you get some error like "arithmetic exception, numeric overflow, or
string truncation. Cannot transliterate character between character sets"
(this occurs when you try use some character with accents) when using this
and after ibase_query() you must set the character set (i.e. ISO8859_1 or
your current character set).
Examples
Example #1 ibase_connect() example
email, "\n";
}
ibase_free_result($sth);
ibase_close($dbh);
?>
See Also
* ibase_pconnect() - Open a persistent connection to an InterBase
database
* ibase_close() - Close a connection to an InterBase database
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_db_info
(PHP 5)
ibase_db_info - Request statistics about a database
Description
string ibase_db_info ( resource $service_handle , string $db , int $action
[, int $argument = 0 ] )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_delete_user
(PHP 4 >= 4.2.0, PHP 5)
ibase_delete_user - Delete a user from a security database (only for IB6
or later)
Description
bool ibase_delete_user ( resource $service_handle , string $user_name )
PHP 4 uses server, dba_user_name and dba_user_password instead of
service_handle parameter.
Warning
This function is currently not documented; only its argument list is
available.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ibase_add_user() - Add a user to a security database (only for IB6 or
later)
* ibase_modify_user() - Modify a user to a security database (only for
IB6 or later)
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_drop_db
(PHP 5)
ibase_drop_db - Drops a database
Description
bool ibase_drop_db ([ resource $connection = NULL ] )
This functions drops a database that was opened by either ibase_connect()
or ibase_pconnect(). The database is closed and deleted from the server.
Parameters
connection
An InterBase link identifier. If omitted, the last opened link is
assumed.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ibase_connect() - Open a connection to an InterBase database
* ibase_pconnect() - Open a persistent connection to an InterBase
database
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_errcode
(PHP 5)
ibase_errcode - Return an error code
Description
int ibase_errcode ( void )
Returns the error code that resulted from the most recent InterBase
function call.
Return Values
Returns the error code as an integer, or FALSE if no error occurred.
See Also
* ibase_errmsg() - Return error messages
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_errmsg
(PHP 4, PHP 5)
ibase_errmsg - Return error messages
Description
string ibase_errmsg ( void )
Returns the error message that resulted from the most recent InterBase
function call.
Return Values
Returns the error message as a string, or FALSE if no error occurred.
See Also
* ibase_errcode() - Return an error code
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_execute
(PHP 4, PHP 5)
ibase_execute - Execute a previously prepared query
Description
resource ibase_execute ( resource $query [, mixed $bind_arg [, mixed $...
]] )
Execute a query prepared by ibase_prepare().
This is a lot more effective than using ibase_query() if you are repeating
a same kind of query several times with only some parameters changing.
Parameters
query
An InterBase query prepared by ibase_prepare().
bind_arg
...
Return Values
If the query raises an error, returns FALSE. If it is successful and there
is a (possibly empty) result set (such as with a SELECT query), returns a
result identifier. If the query was successful and there were no results,
returns TRUE.
Note:
In PHP 5.0.0 and up, this function returns the number of rows affected
by the query (if > 0 and applicable to the statement type). A query that
succeeded, but did not affect any rows (e.g. an UPDATE of a non-existent
record) will return TRUE.
Examples
Example #1 ibase_execute() example
'Eric',
5 => 'Filip',
7 => 'Larry'
);
$query = ibase_prepare($dbh, "UPDATE FOO SET BAR = ? WHERE BAZ = ?");
foreach ($updates as $baz => $bar) {
ibase_execute($query, $bar, $baz);
}
?>
See Also
* ibase_query() - Execute a query on an InterBase database
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_fetch_assoc
(PHP 4 >= 4.3.0, PHP 5)
ibase_fetch_assoc - Fetch a result row from a query as an associative
array
Description
array ibase_fetch_assoc ( resource $result [, int $fetch_flag = 0 ] )
Fetch a result row from a query as an associative array.
ibase_fetch_assoc() fetches one row of data from the result. If two or
more columns of the result have the same field names, the last column will
take precedence. To access the other column(s) of the same name, you
either need to access the result with numeric indices by using
ibase_fetch_row() or use alias names in your query.
Parameters
result
The result handle.
fetch_flag
fetch_flag is a combination of the constants IBASE_TEXT and
IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this
function to return BLOB contents instead of BLOB ids. Passing
IBASE_UNIXTIME will cause this function to return date/time values
as Unix timestamps instead of as formatted strings.
Return Values
Returns an associative array that corresponds to the fetched row.
Subsequent calls will return the next row in the result set, or FALSE if
there are no more rows.
See Also
* ibase_fetch_row() - Fetch a row from an InterBase database
* ibase_fetch_object() - Get an object from a InterBase database
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_fetch_object
(PHP 4, PHP 5)
ibase_fetch_object - Get an object from a InterBase database
Description
object ibase_fetch_object ( resource $result_id [, int $fetch_flag = 0 ] )
Fetches a row as a pseudo-object from a given result identifier.
Subsequent calls to ibase_fetch_object() return the next row in the result
set.
Parameters
result_id
An InterBase result identifier obtained either by ibase_query() or
ibase_execute().
fetch_flag
fetch_flag is a combination of the constants IBASE_TEXT and
IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this
function to return BLOB contents instead of BLOB ids. Passing
IBASE_UNIXTIME will cause this function to return date/time values
as Unix timestamps instead of as formatted strings.
Return Values
Returns an object with the next row information, or FALSE if there are no
more rows.
Examples
Example #1 ibase_fetch_object() example
email . "\n";
}
ibase_close($dbh);
?>
See Also
* ibase_fetch_row() - Fetch a row from an InterBase database
* ibase_fetch_assoc() - Fetch a result row from a query as an
associative array
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_fetch_row
(PHP 4, PHP 5)
ibase_fetch_row - Fetch a row from an InterBase database
Description
array ibase_fetch_row ( resource $result_identifier [, int $fetch_flag = 0
] )
ibase_fetch_row() fetches one row of data from the given result set.
Subsequent calls to ibase_fetch_row() return the next row in the result
set, or FALSE if there are no more rows.
Parameters
result_identifier
An InterBase result identifier.
fetch_flag
fetch_flag is a combination of the constants IBASE_TEXT and
IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this
function to return BLOB contents instead of BLOB ids. Passing
IBASE_UNIXTIME will cause this function to return date/time values
as Unix timestamps instead of as formatted strings.
Return Values
Returns an array that corresponds to the fetched row, or FALSE if there
are no more rows. Each result column is stored in an array offset,
starting at offset 0.
See Also
* ibase_fetch_assoc() - Fetch a result row from a query as an
associative array
* ibase_fetch_object() - Get an object from a InterBase database
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_field_info
(PHP 4, PHP 5)
ibase_field_info - Get information about a field
Description
array ibase_field_info ( resource $result , int $field_number )
Returns an array with information about a field after a select query has
been run.
Parameters
result
An InterBase result identifier.
field_number
Field offset.
Return Values
Returns an array with the following keys: name, alias, relation, length
and type.
Examples
Example #1 ibase_field_info() example
See Also
* ibase_num_fields() - Get the number of fields in a result set
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_free_event_handler
(PHP 5)
ibase_free_event_handler - Cancels a registered event handler
Description
bool ibase_free_event_handler ( resource $event )
This function causes the registered event handler specified by event to be
cancelled. The callback function will no longer be called for the events
it was registered to handle.
Parameters
event
An event resource, created by ibase_set_event_handler().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ibase_set_event_handler() - Register a callback function to be called
when events are posted
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_free_query
(PHP 4, PHP 5)
ibase_free_query - Free memory allocated by a prepared query
Description
bool ibase_free_query ( resource $query )
Frees a prepared query.
Parameters
query
A query prepared with ibase_prepare().
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_free_result
(PHP 4, PHP 5)
ibase_free_result - Free a result set
Description
bool ibase_free_result ( resource $result_identifier )
Frees a result set.
Parameters
result_identifier
A result set created by ibase_query() or ibase_execute().
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_gen_id
(PHP 5)
ibase_gen_id - Increments the named generator and returns its new value
Description
mixed ibase_gen_id ( string $generator [, int $increment = 1 [, resource
$link_identifier = NULL ]] )
Warning
This function is currently not documented; only its argument list is
available.
Return Values
Returns new generator value as integer, or as string if the value is too
big.
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_maintain_db
(PHP 5)
ibase_maintain_db - Execute a maintenance command on the database server
Description
bool ibase_maintain_db ( resource $service_handle , string $db , int
$action [, int $argument = 0 ] )
Warning
This function is currently not documented; only its argument list is
available.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_modify_user
(PHP 4 >= 4.2.0, PHP 5)
ibase_modify_user - Modify a user to a security database (only for IB6 or
later)
Description
bool ibase_modify_user ( resource $service_handle , string $user_name ,
string $password [, string $first_name [, string $middle_name [, string
$last_name ]]] )
Warning
This function is currently not documented; only its argument list is
available.
PHP 4 uses server, dba_user_name and dba_user_password instead of
service_handle parameter.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ibase_add_user() - Add a user to a security database (only for IB6 or
later)
* ibase_delete_user() - Delete a user from a security database (only for
IB6 or later)
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_name_result
(PHP 5)
ibase_name_result - Assigns a name to a result set
Description
bool ibase_name_result ( resource $result , string $name )
This function assigns a name to a result set. This name can be used later
in UPDATE|DELETE ... WHERE CURRENT OF name statements.
Parameters
result
An InterBase result set.
name
The name to be assigned.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 ibase_name_result() example
See Also
* ibase_prepare() - Prepare a query for later binding of parameter
placeholders and execution
* ibase_execute() - Execute a previously prepared query
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_num_fields
(PHP 4, PHP 5)
ibase_num_fields - Get the number of fields in a result set
Description
int ibase_num_fields ( resource $result_id )
Get the number of fields in a result set.
Parameters
result_id
An InterBase result identifier.
Return Values
Returns the number of fields as an integer.
Examples
Example #1 ibase_num_fields() example
See Also
* ibase_field_info() - Get information about a field
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_num_params
(PHP 5)
ibase_num_params - Return the number of parameters in a prepared query
Description
int ibase_num_params ( resource $query )
This function returns the number of parameters in the prepared query
specified by query. This is the number of binding arguments that must be
present when calling ibase_execute().
Parameters
query
The prepared query handle.
Return Values
Returns the number of parameters as an integer.
See Also
* ibase_prepare() - Prepare a query for later binding of parameter
placeholders and execution
* ibase_param_info() - Return information about a parameter in a
prepared query
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_param_info
(PHP 5)
ibase_param_info - Return information about a parameter in a prepared
query
Description
array ibase_param_info ( resource $query , int $param_number )
Returns an array with information about a parameter after a query has been
prepared.
Parameters
query
An InterBase prepared query handle.
param_number
Parameter offset.
Return Values
Returns an array with the following keys: name, alias, relation, length
and type.
See Also
* ibase_field_info() - Get information about a field
* ibase_num_params() - Return the number of parameters in a prepared
query
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_pconnect
(PHP 4, PHP 5)
ibase_pconnect - Open a persistent connection to an InterBase database
Description
resource ibase_pconnect ([ string $database [, string $username [, string
$password [, string $charset [, int $buffers [, int $dialect [, string
$role [, int $sync ]]]]]]]] )
Opens a persistent connection to an InterBase database.
ibase_pconnect() acts very much like ibase_connect() with two major
differences.
First, when connecting, the function will first try to find a (persistent)
link that's already opened with the same parameters. If one is found, an
identifier for it will be returned instead of opening a new connection.
Second, the connection to the InterBase server will not be closed when the
execution of the script ends. Instead, the link will remain open for
future use (ibase_close() will not close links established by
ibase_pconnect()). This type of link is therefore called 'persistent'.
Parameters
database
The database argument has to be a valid path to database file on
the server it resides on. If the server is not local, it must be
prefixed with either 'hostname:' (TCP/IP), '//hostname/' (NetBEUI)
or 'hostname@' (IPX/SPX), depending on the connection protocol
used.
username
The user name. Can be set with the ibase.default_user php.ini
directive.
password
The password for username. Can be set with the
ibase.default_password php.ini directive.
charset
charset is the default character set for a database.
buffers
buffers is the number of database buffers to allocate for the
server-side cache. If 0 or omitted, server chooses its own
default.
dialect
dialect selects the default SQL dialect for any statement executed
within a connection, and it defaults to the highest one supported
by client libraries. Functional only with InterBase 6 and up.
role
Functional only with InterBase 5 and up.
sync
Return Values
Returns an InterBase link identifier on success, or FALSE on error.
See Also
* ibase_close() - Close a connection to an InterBase database
* ibase_connect() - Open a connection to an InterBase database
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_prepare
(PHP 4, PHP 5)
ibase_prepare - Prepare a query for later binding of parameter
placeholders and execution
Description
resource ibase_prepare ( string $query )
resource ibase_prepare ( resource $link_identifier , string $query )
resource ibase_prepare ( resource $link_identifier , string $trans ,
string $query )
Prepare a query for later binding of parameter placeholders and execution
(via ibase_execute()).
Parameters
query
An InterBase query.
Return Values
Returns a prepared query handle, or FALSE on error.
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_query
(PHP 4, PHP 5)
ibase_query - Execute a query on an InterBase database
Description
resource ibase_query ([ resource $link_identifier ], string $query [, int
$bind_args ] )
Performs a query on an InterBase database.
Parameters
link_identifier
An InterBase link identifier. If omitted, the last opened link is
assumed.
query
An InterBase query.
bind_args
Return Values
If the query raises an error, returns FALSE. If it is successful and there
is a (possibly empty) result set (such as with a SELECT query), returns a
result identifier. If the query was successful and there were no results,
returns TRUE.
Note:
In PHP 5.0.0 and up, this function will return the number of rows
affected by the query for INSERT, UPDATE and DELETE statements. In order
to retain backward compatibility, it will return TRUE for these
statements if the query succeeded without affecting any rows.
Errors/Exceptions
If you get some error like "arithmetic exception, numeric overflow, or
string truncation. Cannot transliterate character between character sets"
(this occurs when you try use some character with accents) when using this
and after ibase_query() you must set the character set (i.e. ISO8859_1 or
your current character set).
Changelog
Version Description
On success the function now returns TRUE if there were no affected
5.3.1 rows, where it previously returned 0 (a zero followed by an empty
space).
Examples
Example #1 ibase_query() example
See Also
* ibase_errmsg() - Return error messages
* ibase_fetch_row() - Fetch a row from an InterBase database
* ibase_fetch_object() - Get an object from a InterBase database
* ibase_free_result() - Free a result set
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_restore
(PHP 5)
ibase_restore - Initiates a restore task in the service manager and
returns immediately
Description
mixed ibase_restore ( resource $service_handle , string $source_file ,
string $dest_db [, int $options = 0 [, bool $verbose = false ]] )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_rollback_ret
(PHP 5)
ibase_rollback_ret - Roll back a transaction without closing it
Description
bool ibase_rollback_ret ([ resource $link_or_trans_identifier = NULL ] )
Rolls back a transaction without closing it.
Parameters
link_or_trans_identifier
If called without an argument, this function rolls back the
default transaction of the default link. If the argument is a
connection identifier, the default transaction of the
corresponding connection will be rolled back. If the argument is a
transaction identifier, the corresponding transaction will be
rolled back. The transaction context will be retained, so
statements executed from within this transaction will not be
invalidated.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_rollback
(PHP 4, PHP 5)
ibase_rollback - Roll back a transaction
Description
bool ibase_rollback ([ resource $link_or_trans_identifier = NULL ] )
Rolls back a transaction.
Parameters
link_or_trans_identifier
If called without an argument, this function rolls back the
default transaction of the default link. If the argument is a
connection identifier, the default transaction of the
corresponding connection will be rolled back. If the argument is a
transaction identifier, the corresponding transaction will be
rolled back.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_server_info
(PHP 5)
ibase_server_info - Request information about a database server
Description
string ibase_server_info ( resource $service_handle , int $action )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_service_attach
(PHP 5)
ibase_service_attach - Connect to the service manager
Description
resource ibase_service_attach ( string $host , string $dba_username ,
string $dba_password )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_service_detach
(PHP 5)
ibase_service_detach - Disconnect from the service manager
Description
bool ibase_service_detach ( resource $service_handle )
Warning
This function is currently not documented; only its argument list is
available.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_set_event_handler
(PHP 5)
ibase_set_event_handler - Register a callback function to be called when
events are posted
Description
resource ibase_set_event_handler ( callback $event_handler , string
$event_name1 [, string $event_name2 [, string $... ]] )
resource ibase_set_event_handler ( resource $connection , callback
$event_handler , string $event_name1 [, string $event_name2 [, string $...
]] )
This function registers a PHP user function as event handler for the
specified events.
Parameters
event_handler
The callback is called with the event name and the link resource
as arguments whenever one of the specified events is posted by the
database.
The callback must return FALSE if the event handler should be
canceled. Any other return value is ignored. This function accepts
up to 15 event arguments.
event_name1
An event name.
event_name2
At most 15 events allowed.
Return Values
The return value is an event resource. This resource can be used to free
the event handler using ibase_free_event_handler().
Examples
Example #1 ibase_set_event_handler() example
See Also
* ibase_free_event_handler() - Cancels a registered event handler
* ibase_wait_event() - Wait for an event to be posted by the database
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_timefmt
(PHP 4)
ibase_timefmt - Sets the format of timestamp, date and time type columns
returned from queries
Description
bool ibase_timefmt ( string $format [, int $columntype = IBASE_TIMESTAMP ]
)
Sets the format of timestamp, date or time type columns returned from
queries.
You can set defaults for these formats with the PHP configuration
directives ibase.timestampformat, ibase.dateformat and ibase.timeformat.
Note:
This function has been removed from PHP 5, use ini_set() instead.
Parameters
format
Internally, the columns are formatted by c-function strftime(), so
refer to its documentation regarding to the format of the string.
columntype
columntype is one of the constants IBASE_TIMESTAMP, IBASE_DATE and
IBASE_TIME. If omitted, defaults to IBASE_TIMESTAMP for backwards
compatibility.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 ibase_timefmt() example
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_trans
(PHP 4, PHP 5)
ibase_trans - Begin a transaction
Description
resource ibase_trans ([ int $trans_args [, resource $link_identifier ]] )
resource ibase_trans ([ resource $link_identifier [, int $trans_args ]] )
Begins a transaction.
Note:
The behaviour of this function has been changed in PHP 5.0.0. The first
call to ibase_trans() will not return the default transaction of a
connection. All transactions started by ibase_trans() will be rolled
back at the end of the script if they were not committed or rolled back
by either ibase_commit() or ibase_rollback().
Note:
In PHP 5.0.0. and up, this function will accept multiple trans_args and
link_identifier arguments. This allows transactions over multiple
database connections, which are committed using a 2-phase commit
algorithm. This means you can rely on the updates to either succeed in
every database, or fail in every database. It does NOT mean you can use
tables from different databases in the same query!
If you use transactions over multiple databases, you will have to
specify both the link_id and transaction_id in calls to ibase_query()
and ibase_prepare().
Parameters
trans_args
trans_args can be a combination of IBASE_READ, IBASE_WRITE,
IBASE_COMMITTED, IBASE_CONSISTENCY, IBASE_CONCURRENCY,
IBASE_REC_VERSION, IBASE_REC_NO_VERSION, IBASE_WAIT and
IBASE_NOWAIT.
link_identifier
An InterBase link identifier. If omitted, the last opened link is
assumed.
Return Values
Returns a transaction handle, or FALSE on error.
----------------------------------------------------------------------
----------------------------------------------------------------------
ibase_wait_event
(PHP 5)
ibase_wait_event - Wait for an event to be posted by the database
Description
string ibase_wait_event ( string $event_name1 [, string $event_name2 [,
string $... ]] )
string ibase_wait_event ( resource $connection , string $event_name1 [,
string $event_name2 [, string $... ]] )
This function suspends execution of the script until one of the specified
events is posted by the database. The name of the event that was posted is
returned. This function accepts up to 15 event arguments.
Parameters
event_name1
The event name.
event_name2
...
Return Values
Returns the name of the event that was posted.
See Also
* ibase_set_event_handler() - Register a callback function to be called
when events are posted
* ibase_free_event_handler() - Cancels a registered event handler
----------------------------------------------------------------------
Table of Contents
* ibase_add_user - Add a user to a security database (only for IB6 or
later)
* ibase_affected_rows - Return the number of rows that were affected by
the previous query
* ibase_backup - Initiates a backup task in the service manager and
returns immediately
* ibase_blob_add - Add data into a newly created blob
* ibase_blob_cancel - Cancel creating blob
* ibase_blob_close - Close blob
* ibase_blob_create - Create a new blob for adding data
* ibase_blob_echo - Output blob contents to browser
* ibase_blob_get - Get len bytes data from open blob
* ibase_blob_import - Create blob, copy file in it, and close it
* ibase_blob_info - Return blob length and other useful info
* ibase_blob_open - Open blob for retrieving data parts
* ibase_close - Close a connection to an InterBase database
* ibase_commit_ret - Commit a transaction without closing it
* ibase_commit - Commit a transaction
* ibase_connect - Open a connection to an InterBase database
* ibase_db_info - Request statistics about a database
* ibase_delete_user - Delete a user from a security database (only for
IB6 or later)
* ibase_drop_db - Drops a database
* ibase_errcode - Return an error code
* ibase_errmsg - Return error messages
* ibase_execute - Execute a previously prepared query
* ibase_fetch_assoc - Fetch a result row from a query as an associative
array
* ibase_fetch_object - Get an object from a InterBase database
* ibase_fetch_row - Fetch a row from an InterBase database
* ibase_field_info - Get information about a field
* ibase_free_event_handler - Cancels a registered event handler
* ibase_free_query - Free memory allocated by a prepared query
* ibase_free_result - Free a result set
* ibase_gen_id - Increments the named generator and returns its new
value
* ibase_maintain_db - Execute a maintenance command on the database
server
* ibase_modify_user - Modify a user to a security database (only for IB6
or later)
* ibase_name_result - Assigns a name to a result set
* ibase_num_fields - Get the number of fields in a result set
* ibase_num_params - Return the number of parameters in a prepared query
* ibase_param_info - Return information about a parameter in a prepared
query
* ibase_pconnect - Open a persistent connection to an InterBase database
* ibase_prepare - Prepare a query for later binding of parameter
placeholders and execution
* ibase_query - Execute a query on an InterBase database
* ibase_restore - Initiates a restore task in the service manager and
returns immediately
* ibase_rollback_ret - Roll back a transaction without closing it
* ibase_rollback - Roll back a transaction
* ibase_server_info - Request information about a database server
* ibase_service_attach - Connect to the service manager
* ibase_service_detach - Disconnect from the service manager
* ibase_set_event_handler - Register a callback function to be called
when events are posted
* ibase_timefmt - Sets the format of timestamp, date and time type
columns returned from queries
* ibase_trans - Begin a transaction
* ibase_wait_event - Wait for an event to be posted by the database
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Firebird/InterBase Functions
* ibase_add_user - Add a user to a security database (only for IB6
or later)
* ibase_affected_rows - Return the number of rows that were
affected by the previous query
* ibase_backup - Initiates a backup task in the service manager and
returns immediately
* ibase_blob_add - Add data into a newly created blob
* ibase_blob_cancel - Cancel creating blob
* ibase_blob_close - Close blob
* ibase_blob_create - Create a new blob for adding data
* ibase_blob_echo - Output blob contents to browser
* ibase_blob_get - Get len bytes data from open blob
* ibase_blob_import - Create blob, copy file in it, and close it
* ibase_blob_info - Return blob length and other useful info
* ibase_blob_open - Open blob for retrieving data parts
* ibase_close - Close a connection to an InterBase database
* ibase_commit_ret - Commit a transaction without closing it
* ibase_commit - Commit a transaction
* ibase_connect - Open a connection to an InterBase database
* ibase_db_info - Request statistics about a database
* ibase_delete_user - Delete a user from a security database (only
for IB6 or later)
* ibase_drop_db - Drops a database
* ibase_errcode - Return an error code
* ibase_errmsg - Return error messages
* ibase_execute - Execute a previously prepared query
* ibase_fetch_assoc - Fetch a result row from a query as an
associative array
* ibase_fetch_object - Get an object from a InterBase database
* ibase_fetch_row - Fetch a row from an InterBase database
* ibase_field_info - Get information about a field
* ibase_free_event_handler - Cancels a registered event handler
* ibase_free_query - Free memory allocated by a prepared query
* ibase_free_result - Free a result set
* ibase_gen_id - Increments the named generator and returns its new
value
* ibase_maintain_db - Execute a maintenance command on the database
server
* ibase_modify_user - Modify a user to a security database (only
for IB6 or later)
* ibase_name_result - Assigns a name to a result set
* ibase_num_fields - Get the number of fields in a result set
* ibase_num_params - Return the number of parameters in a prepared
query
* ibase_param_info - Return information about a parameter in a
prepared query
* ibase_pconnect - Open a persistent connection to an InterBase
database
* ibase_prepare - Prepare a query for later binding of parameter
placeholders and execution
* ibase_query - Execute a query on an InterBase database
* ibase_restore - Initiates a restore task in the service manager
and returns immediately
* ibase_rollback_ret - Roll back a transaction without closing it
* ibase_rollback - Roll back a transaction
* ibase_server_info - Request information about a database server
* ibase_service_attach - Connect to the service manager
* ibase_service_detach - Disconnect from the service manager
* ibase_set_event_handler - Register a callback function to be
called when events are posted
* ibase_timefmt - Sets the format of timestamp, date and time type
columns returned from queries
* ibase_trans - Begin a transaction
* ibase_wait_event - Wait for an event to be posted by the database
----------------------------------------------------------------------
----------------------------------------------------------------------
Informix
----------------------------------------------------------------------
Introduction
The Informix driver for Informix (IDS) 7.x, SE 7.x, Universal Server (IUS)
9.x and IDS 2000 is implemented in "ifx.ec" and "php_informix.h" in the
informix extension directory. IDS 7.x support is fairly complete, with
full support for BYTE and TEXT columns. IUS 9.x support is partly
finished: the new data types are there, but SLOB and CLOB support is still
under construction.
Note:
This extension has been moved to the >> PECL repository and is no longer
bundled with PHP as of PHP 5.2.1.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
Note: Configuration notes
You need a version of ESQL/C to compile the PHP Informix driver. ESQL/C
versions from 7.2x on should be OK. ESQL/C is now part of the Informix
Client SDK.
Make sure that the "INFORMIXDIR" variable has been set, and that
$INFORMIXDIR/bin is in your PATH before you run the "configure" script.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
To be able to use the functions defined in this module you must compile
your PHP interpreter using the configure line --with-informix[=DIR] ,
where DIR is the Informix base install directory, defaults to nothing.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Note:
Make sure that the Informix environment variables INFORMIXDIR and
INFORMIXSERVER are available to the PHP ifx driver, and that the
INFORMIX bin directory is in the PATH. Check this by running a script
that contains a call to phpinfo() before you start testing. The
phpinfo() output should list these environment variables. This is true
for both CGI php and Apache mod_php. You may have to set these
environment variables in your Apache startup script.
The Informix shared libraries should also be available to the loader
(check LD_LIBRARY_PATH or ld.so.conf/ldconfig).
Note: Some notes on the use of BLOBs (TEXT and BYTE columns)
BLOBs are normally addressed by BLOB identifiers. Select queries return
a "blob id" for every BYTE and TEXT column. You can get at the contents
with "string_var = ifx_get_blob($blob_id);" if you choose to get the
BLOBs in memory (with: "ifx_blobinfile(0);"). If you prefer to receive
the content of BLOB columns in a file, use "ifx_blobinfile(1);", and
"ifx_get_blob($blob_id);" will get you the filename. Use normal file I/O
to get at the blob contents.
For insert/update queries you must create these "blob id's" yourself
with "ifx_create_blob();". You then plug the blob id's into an array,
and replace the blob columns with a question mark (?) in the query
string. For updates/inserts, you are responsible for setting the blob
contents with ifx_update_blob().
The behaviour of BLOB columns can be altered by configuration variables
that also can be set at runtime:
configuration variable: ifx.textasvarchar
configuration variable: ifx.byteasvarchar
runtime functions:
ifx_textasvarchar(0): use blob id's for select queries with TEXT columns
ifx_byteasvarchar(0): use blob id's for select queries with BYTE columns
ifx_textasvarchar(1): return TEXT columns as if they were VARCHAR
columns, so that you don't need to use blob id's for select queries.
ifx_byteasvarchar(1): return BYTE columns as if they were VARCHAR
columns, so that you don't need to use blob id's for select queries.
configuration variable: ifx.blobinfile
runtime function:
ifx_blobinfile_mode(0): return BYTE columns in memory, the blob id lets
you get at the contents.
ifx_blobinfile_mode(1): return BYTE columns in a file, the blob id lets
you get at the file name.
If you set ifx_text/byteasvarchar to 1, you can use TEXT and BYTE
columns in select queries just like normal (but rather long) VARCHAR
fields. Since all strings are "counted" in PHP, this remains "binary
safe". It is up to you to handle this correctly. The returned data can
contain anything, you are responsible for the contents.
If you set ifx_blobinfile to 1, use the file name returned by
ifx_get_blob(..) to get at the blob contents. Note that in this case YOU
ARE RESPONSIBLE FOR DELETING THE TEMPORARY FILES CREATED BY INFORMIX
when fetching the row. Every new row fetched will create new temporary
files for every BYTE column.
The location of the temporary files can be influenced by the environment
variable "blobdir", default is "." (the current directory). Something
like: putenv(blobdir=tmpblob"); will ease the cleaning up of temp files
accidentally left behind (their names all start with "blb").
Note: Automatically trimming "char" (SQLCHAR and SQLNCHAR) data
This can be set with the configuration variable
ifx.charasvarchar: if set to 1 trailing spaces will be automatically
trimmed, to save you some "chopping".
Note: NULL values
The configuration variable ifx.nullformat (and the runtime function
ifx_nullformat()) when set to TRUE will return NULL columns as the
string "NULL", when set to FALSE they return the empty string. This
allows you to discriminate between NULL columns and empty columns.
Informix configuration options
Name Default Changeable Changelog
ifx.allow_persistent "1" PHP_INI_SYSTEM Removed in PHP 5.2.1.
ifx.max_persistent "-1" PHP_INI_SYSTEM Removed in PHP 5.2.1.
ifx.max_links "-1" PHP_INI_SYSTEM Removed in PHP 5.2.1.
ifx.default_host NULL PHP_INI_SYSTEM Removed in PHP 5.2.1.
ifx.default_user NULL PHP_INI_SYSTEM Removed in PHP 5.2.1.
ifx.default_password NULL PHP_INI_SYSTEM Removed in PHP 5.2.1.
ifx.blobinfile "1" PHP_INI_ALL Removed in PHP 5.2.1.
ifx.textasvarchar "0" PHP_INI_ALL Removed in PHP 5.2.1.
ifx.byteasvarchar "0" PHP_INI_ALL Removed in PHP 5.2.1.
ifx.charasvarchar "0" PHP_INI_ALL Removed in PHP 5.2.1.
ifx.nullformat "0" PHP_INI_ALL Removed in PHP 5.2.1.
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
ifx.allow_persistent boolean
Whether to allow persistent Informix connections.
ifx.max_persistent integer
The maximum number of persistent Informix connections per process.
ifx.max_links integer
The maximum number of Informix connections per process, including
persistent connections.
ifx.default_host string
The default host to connect to when no host is specified in
ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.
ifx.default_user string
The default user id to use when none is specified in ifx_connect()
or ifx_pconnect(). Doesn't apply in safe mode.
ifx.default_password string
The default password to use when none is specified in
ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.
ifx.blobinfile boolean
Set to TRUE if you want to return blob columns in a file, FALSE if
you want them in memory. You can override the setting at runtime
with ifx_blobinfile_mode().
ifx.textasvarchar boolean
Set to TRUE if you want to return TEXT columns as normal strings
in select statements, FALSE if you want to use blob id parameters.
You can override the setting at runtime with ifx_textasvarchar().
ifx.byteasvarchar boolean
Set to TRUE if you want to return BYTE columns as normal strings
in select queries, FALSE if you want to use blob id parameters.
You can override the setting at runtime with ifx_textasvarchar().
ifx.charasvarchar boolean
Set to TRUE if you want to trim trailing spaces from CHAR columns
when fetching them.
ifx.nullformat boolean
Set to TRUE if you want to return NULL columns as the literal
string "NULL", FALSE if you want them returned as the empty string
"". You can override this setting at runtime with
ifx_nullformat().
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
IFX_SCROLL (integer)
IFX_HOLD (integer)
IFX_LO_RDONLY (integer)
IFX_LO_WRONLY (integer)
IFX_LO_APPEND (integer)
IFX_LO_RDWR (integer)
IFX_LO_BUFFER (integer)
IFX_LO_NOBUFFER (integer)
----------------------------------------------------------------------
----------------------------------------------------------------------
Informix Functions
----------------------------------------------------------------------
ifx_affected_rows
(PHP 4, PHP <=5.2.0)
ifx_affected_rows - Get number of rows affected by a query
Description
int ifx_affected_rows ( resource $result_id )
Returns the number of rows affected by a query associated with result_id.
For inserts, updates and deletes the number is the real number
(sqlerrd[2]) of affected rows. For selects it is an estimate (sqlerrd[0]).
Don't rely on it. The database server can never return the actual number
of rows that will be returned by a SELECT because it has not even begun
fetching them at this stage (just after the "PREPARE" when the optimizer
has determined the query plan).
Useful after ifx_prepare() to limit queries to reasonable result sets.
Parameters
result_id
A valid result id returned by ifx_query() or ifx_prepare().
Return Values
Returns the number of rows as an integer.
Examples
Example #1 Informix affected rows
1000) {
printf ("Too many rows in result set (%d)\n ", $rowcount);
die ("Please restrict your query \n");
}
?>
See Also
* ifx_num_rows() - Count the rows already fetched from a query
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_blobinfile_mode
(PHP 4, PHP <=5.2.0)
ifx_blobinfile_mode - Set the default blob mode for all select queries
Description
bool ifx_blobinfile_mode ( int $mode )
Set the default blob mode for all select queries.
Parameters
mode
Mode "0" means save Byte-Blobs in memory, and mode "1" means save
Byte-Blobs in a file.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_byteasvarchar
(PHP 4, PHP <=5.2.0)
ifx_byteasvarchar - Set the default byte mode
Description
bool ifx_byteasvarchar ( int $mode )
Sets the default byte mode for all select-queries.
Parameters
mode
Mode "0" will return a blob id, and mode "1" will return a varchar
with text content.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ifx_textasvarchar() - Set the default text mode
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_close
(PHP 4, PHP <=5.2.0)
ifx_close - Close Informix connection
Description
bool ifx_close ([ resource $link_identifier ] )
ifx_close() closes the link to an Informix database that's associated with
the specified link identifier.
Note that this isn't usually necessary, as non-persistent open links are
automatically closed at the end of the script's execution.
ifx_close() will not close persistent links generated by ifx_pconnect().
Parameters
link_identifier
The link identifier. If not specified, the last opened link is
assumed.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Closing a Informix connection
See Also
* ifx_connect() - Open Informix server connection
* ifx_pconnect() - Open persistent Informix connection
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_connect
(PHP 4, PHP <=5.2.0)
ifx_connect - Open Informix server connection
Description
resource ifx_connect ([ string $database [, string $userid [, string
$password ]]] )
ifx_connect() establishes a connection to an Informix server.
In case a second call is made to ifx_connect() with the same arguments, no
new link will be established, but instead, the link identifier of the
already opened link will be returned.
The link to the server will be closed as soon as the execution of the
script ends, unless it's closed earlier by explicitly calling ifx_close().
Parameters
All of the arguments are optional, and if they're missing, defaults are
taken from values supplied in php.ini (ifx.default_host for the host
(Informix libraries will use INFORMIXSERVER environment value if not
defined), ifx.default_user for user, ifx.default_password for the password
(none if not defined).
database
The database name, as a string.
userid
The username, as a string.
password
The password, as a string.
Return Values
Returns a connection identifier on success, or FALSE on error.
Examples
Example #1 Connect to a Informix database
See Also
* ifx_pconnect() - Open persistent Informix connection
* ifx_close() - Close Informix connection
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_copy_blob
(PHP 4, PHP <=5.2.0)
ifx_copy_blob - Duplicates the given blob object
Description
int ifx_copy_blob ( int $bid )
Duplicates the given blob object.
Parameters
bid
A BLOB identifier.
Return Values
Returns the new blob object-id, or FALSE on errors.
See Also
* ifx_create_blob() - Creates an blob object
* ifx_free_blob() - Deletes the blob object
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_create_blob
(PHP 4, PHP <=5.2.0)
ifx_create_blob - Creates an blob object
Description
int ifx_create_blob ( int $type , int $mode , string $param )
Creates a blob object.
Parameters
type
1 = TEXT, 0 = BYTE
mode
0 = blob-object holds the content in memory, 1 = blob-object holds
the content in file.
param
if mode = 0: pointer to the content, if mode = 1: pointer to the
filestring.
Return Values
Returns the new BLOB object-id, or FALSE on errors.
See Also
* ifx_copy_blob() - Duplicates the given blob object
* ifx_free_blob() - Deletes the blob object
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_create_char
(PHP 4, PHP <=5.2.0)
ifx_create_char - Creates an char object
Description
int ifx_create_char ( string $param )
Creates an char object.
Parameters
param
The char content.
Return Values
Returns the new char object id, or FALSE on errors.
See Also
* ifx_free_char() - Deletes the char object
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_do
(PHP 4, PHP <=5.2.0)
ifx_do - Execute a previously prepared SQL-statement
Description
bool ifx_do ( resource $result_id )
Executes a previously prepared query or opens a cursor for it.
Does NOT free result_id on error.
Also sets the real number of ifx_affected_rows() for non-select statements
for retrieval by ifx_affected_rows().
Parameters
result_id
result_id is a valid resultid returned by ifx_query() or
ifx_prepare() (select type queries only!).
Return Values
Returns TRUE on success or FALSE on failure.
See Also
Example #1 ifx_do() Example
See Also
* ifx_prepare() - Prepare an SQL-statement for execution
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_error
(PHP 4, PHP <=5.2.0)
ifx_error - Returns error code of last Informix call
Description
string ifx_error ([ resource $link_identifier ] )
Returns in a string one character describing the general results of a
statement and both SQLSTATE and SQLCODE associated with the most recent
SQL statement executed.
Parameters
link_identifier
The link identifier.
Return Values
The Informix error codes (SQLSTATE & SQLCODE) formatted as x [SQLSTATE =
aa bbb SQLCODE=cccc].
where x = space : no error
E : error
N : no more data
W : warning
? : undefined
If the "x" character is anything other than space, SQLSTATE and SQLCODE
describe the error in more detail.
See the Informix manual for the description of SQLSTATE and SQLCODE
See Also
* ifx_errormsg() - Returns error message of last Informix call
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_errormsg
(PHP 4, PHP <=5.2.0)
ifx_errormsg - Returns error message of last Informix call
Description
string ifx_errormsg ([ int $errorcode ] )
Returns the Informix error message associated with the most recent
Informix error.
Parameters
errorcode
If specified, the function will return the message corresponding
to the specified code.
Return Values
Return the error message, as a string.
Examples
Example #1 ifx_errormsg() example
", ifx_errormsg(-201));
?>
See Also
* ifx_error() - Returns error code of last Informix call
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_fetch_row
(PHP 4, PHP <=5.2.0)
ifx_fetch_row - Get row as an associative array
Description
array ifx_fetch_row ( resource $result_id [, mixed $position ] )
Fetches one row of data from the result associated with the specified
result identifier.
Subsequent calls to ifx_fetch_row() would return the next row in the
result set, or FALSE if there are no more rows.
Parameters
result_id
result_id is a valid resultid returned by ifx_query() or
ifx_prepare() (select type queries only!).
position
An optional parameter for a "fetch" operation on "scroll" cursors:
NEXT, PREVIOUS, CURRENT, FIRST, LAST or a number. If you specify a
number, an "absolute" row fetch is executed. This parameter is
optional, and only valid for SCROLL cursors.
Return Values
Returns an associative array that corresponds to the fetched row, or FALSE
if there are no more rows.
Blob columns are returned as integer blob id values for use in
ifx_get_blob() unless you have used ifx_textasvarchar(1) or
ifx_byteasvarchar(1), in which case blobs are returned as string values.
Examples
Example #1 Informix fetch rows
1000) {
printf ("Too many rows in result set (%d)\n ", $rowcount);
die ("Please restrict your query \n");
}
if (! ifx_do ($rid)) {
/* ... error ... */
}
$row = ifx_fetch_row ($rid, "NEXT");
while (is_array($row)) {
for (reset($row); $fieldname=key($row); next($row)) {
$fieldvalue = $row[$fieldname];
printf ("%s = %s,", $fieldname, $fieldvalue);
}
printf("\n ");
$row = ifx_fetch_row($rid, "NEXT");
}
ifx_free_result ($rid);
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_fieldproperties
(PHP 4, PHP <=5.2.0)
ifx_fieldproperties - List of SQL fieldproperties
Description
array ifx_fieldproperties ( resource $result_id )
Returns the Informix SQL fieldproperties of every field in the query as an
associative array. Properties are encoded as:
"SQLTYPE;length;precision;scale;ISNULLABLE" where SQLTYPE = the Informix
type like "SQLVCHAR" etc. and ISNULLABLE = "Y" or "N".
Parameters
result_id
result_id is a valid resultid returned by ifx_query() or
ifx_prepare() (select type queries only!).
Return Values
Returns an associative array with fieldnames as key and the SQL
fieldproperties as data for a query with result_id. Returns FALSE on
errors.
Examples
Example #1 Informix SQL fieldproperties
$val) {
echo "$fname:\t property = $val\n";
}
?>
See Also
* ifx_fieldtypes() - List of Informix SQL fields
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_fieldtypes
(PHP 4, PHP <=5.2.0)
ifx_fieldtypes - List of Informix SQL fields
Description
array ifx_fieldtypes ( resource $result_id )
Returns an associative array with fieldnames as key and the SQL fieldtypes
as data for the query associated with result_id.
Parameters
result_id
result_id is a valid resultid returned by ifx_query() or
ifx_prepare() (select type queries only!).
Return Values
Returns an associative array with fieldnames as key and the SQL fieldtypes
as data for query with result_id. Returns FALSE on error.
Examples
Example #1 Fieldnames and SQL fieldtypes
$val) {
echo "$fname:\t type = $val\n";
}
}
?>
See Also
* ifx_fieldproperties() - List of SQL fieldproperties
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_free_blob
(PHP 4, PHP <=5.2.0)
ifx_free_blob - Deletes the blob object
Description
bool ifx_free_blob ( int $bid )
Deletes the blobobject for the given blob object-id.
Parameters
bid
The BLOB object id.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ifx_create_blob() - Creates an blob object
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_free_char
(PHP 4, PHP <=5.2.0)
ifx_free_char - Deletes the char object
Description
bool ifx_free_char ( int $bid )
Deletes the charobject for the given char object-id.
Parameters
bid
The char object id.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ifx_create_char() - Creates an char object
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_free_result
(PHP 4, PHP <=5.2.0)
ifx_free_result - Releases resources for the query
Description
bool ifx_free_result ( resource $result_id )
Releases resources for the query associated with result_id.
Parameters
result_id
result_id is a valid resultid returned by ifx_query() or
ifx_prepare() (select type queries only!).
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ifx_do() - Execute a previously prepared SQL-statement
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_get_blob
(PHP 4, PHP <=5.2.0)
ifx_get_blob - Return the content of a blob object
Description
string ifx_get_blob ( int $bid )
Returns the content of the blob object.
Parameters
bid
The BLOB object id.
Return Values
The contents of the BLOB as a string, or FALSE on errors.
See Also
* ifx_get_char() - Return the content of the char object
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_get_char
(PHP 4, PHP <=5.2.0)
ifx_get_char - Return the content of the char object
Description
string ifx_get_char ( int $bid )
Returns the content of the char object.
Parameters
bid
The char object-id.
Return Values
Returns the contents as a string, or FALSE on errors.
See Also
* ifx_get_blob() - Return the content of a blob object
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_getsqlca
(PHP 4, PHP <=5.2.0)
ifx_getsqlca - Get the contents of sqlca.sqlerrd[0..5] after a query
Description
array ifx_getsqlca ( resource $result_id )
Returns a pseudo-row with sqlca.sqlerrd[0] ... sqlca.sqlerrd[5] after the
query associated with result_id.
For inserts, updates and deletes the values returned are those as set by
the server after executing the query. This gives access to the number of
affected rows and the serial insert value. For SELECTs the values are
those saved after the PREPARE statement. This gives access to the
*estimated* number of affected rows. The use of this function saves the
overhead of executing a SELECT dbinfo('sqlca.sqlerrdx') query, as it
retrieves the values that were saved by the ifx driver at the appropriate
moment.
Parameters
result_id
result_id is a valid result id returned by ifx_query() or
ifx_prepare() (select type queries only!).
Return Values
Returns an associative array with the following entries: sqlerrd0,
sqlerrd1, sqlerrd2, sqlerrd3, sqlerrd4 and sqlerrd5.
Examples
Example #1 Retrieve Informix sqlca.sqlerrd[x] values
\n";
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_htmltbl_result
(PHP 4, PHP <=5.2.0)
ifx_htmltbl_result - Formats all rows of a query into a HTML table
Description
int ifx_htmltbl_result ( resource $result_id [, string $html_table_options
] )
Formats and prints all rows of the result_id query into a HTML table.
Parameters
result_id
result_id is a valid resultid returned by ifx_query() or
ifx_prepare() (select type queries only!).
html_table_options
This optional argument is a string of tag options.
Return Values
Returns the number of fetched rows, or FALSE on errors.
Examples
Example #1 Informix results as HTML table
1000) {
printf ("Too many rows in result set (%d)\n ", $rowcount);
die ("Please restrict your query \n");
}
if (! ifx_do($rid)) {
/* ... error ... */
}
ifx_htmltbl_result ($rid, "border=\"2\"");
ifx_free_result($rid);
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_nullformat
(PHP 4, PHP <=5.2.0)
ifx_nullformat - Sets the default return value on a fetch row
Description
bool ifx_nullformat ( int $mode )
Sets the default return value of a NULL-value on a fetch row.
Parameters
mode
Mode "0" returns "", and mode "1" returns "NULL".
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_num_fields
(PHP 4, PHP <=5.2.0)
ifx_num_fields - Returns the number of columns in the query
Description
int ifx_num_fields ( resource $result_id )
After preparing or executing a query, this call gives you the number of
columns in the query.
Parameters
result_id
result_id is a valid resultid returned by ifx_query() or
ifx_prepare() (select type queries only!).
Return Values
Returns the number of columns in query for result_id, or FALSE on errors.
Examples
Example #1 ifx_num_fields() Example
See Also
* ifx_num_rows() - Count the rows already fetched from a query
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_num_rows
(PHP 4, PHP <=5.2.0)
ifx_num_rows - Count the rows already fetched from a query
Description
int ifx_num_rows ( resource $result_id )
Gives the number of rows fetched so far for a query with result_id after a
ifx_query() or ifx_do() query.
Parameters
result_id
result_id is a valid resultid returned by ifx_query() or
ifx_prepare() (select type queries only!).
Return Values
Returns the number of fetched rows or FALSE on errors.
See Also
* ifx_num_fields() - Returns the number of columns in the query
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_pconnect
(PHP 4, PHP <=5.2.0)
ifx_pconnect - Open persistent Informix connection
Description
resource ifx_pconnect ([ string $database [, string $userid [, string
$password ]]] )
ifx_pconnect() acts very much like ifx_connect() with two major
differences.
First, when connecting, the function would first try to find a
(persistent) link that's already open with the same host, username and
password. If one is found, an identifier for it will be returned instead
of opening a new connection.
Second, the connection to the SQL server will not be closed when the
execution of the script ends. Instead, the link will remain open for
future use (ifx_close() will not close links established by
ifx_pconnect()).
This type of links is therefore called 'persistent'.
Parameters
All of the arguments are optional, and if they're missing, defaults are
taken from values supplied in php.ini (ifx.default_host for the host
(Informix libraries will use INFORMIXSERVER environment value if not
defined), ifx.default_user for user, ifx.default_password for the password
(none if not defined).
database
The database name, as a string.
userid
The username, as a string.
password
The password, as a string.
Return Values
Returns: valid Informix persistent link identifier on success, or FALSE on
errors.
See Also
* ifx_connect() - Open Informix server connection
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_prepare
(PHP 4, PHP <=5.2.0)
ifx_prepare - Prepare an SQL-statement for execution
Description
resource ifx_prepare ( string $query , resource $link_identifier [, int
$cursor_def ], mixed $blobidarray )
Prepares a query for later use with ifx_do().
For "select-type" queries a cursor is declared and opened. Non-select
queries are "execute immediate".
For either query type the number of (estimated or real) affected rows is
saved for retrieval by ifx_affected_rows().
If the contents of the TEXT (or BYTE) column allow it, you can also use
ifx_textasvarchar(1) and ifx_byteasvarchar(1). This allows you to treat
TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR
columns for select queries, and you don't need to bother with blob id's.
With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation),
select queries will return BLOB columns as blob id's (integer value). You
can get the value of the blob as a string or file with the blob functions
(see below).
Parameters
query
The query string.
link_identifier
The link identifier.
cursor_def
This optional parameter allows you to make this a scroll and/or
hold cursor. It's a bitmask and can be either IFX_SCROLL,
IFX_HOLD, or both or'ed together.
blobidarray
If you have BLOB (BYTE or TEXT) columns in the query, you can add
a blobidarray parameter containing the corresponding "blob ids",
and you should replace those columns with a "?" in the query text.
Return Values
Returns a valid result identifier for use by ifx_do(), or FALSE on errors.
See Also
* ifx_do() - Execute a previously prepared SQL-statement
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_query
(PHP 4, PHP <=5.2.0)
ifx_query - Send Informix query
Description
resource ifx_query ( string $query , resource $link_identifier [, int
$cursor_type [, mixed $blobidarray ]] )
Sends a query to the currently active database on the server that's
associated with the specified link identifier.
For "select-type" queries a cursor is declared and opened. Non-select
queries are "execute immediate".
For either query type the number of (estimated or real) affected rows is
saved for retrieval by ifx_affected_rows().
If the contents of the TEXT (or BYTE) column allow it, you can also use
ifx_textasvarchar(1) and ifx_byteasvarchar(1). This allows you to treat
TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR
columns for select queries, and you don't need to bother with blob id's.
With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation),
select queries will return BLOB columns as blob id's (integer value). You
can get the value of the blob as a string or file with the blob functions
(see below).
Parameters
query
The query string.
link_identifier
The link identifier.
cursor_def
This optional parameter allows you to make this a scroll and/or
hold cursor. It's a bitmask and can be either IFX_SCROLL,
IFX_HOLD, or both or'ed together. I you omit this parameter the
cursor is a normal sequential cursor.
blobidarray
If you have BLOB (BYTE or TEXT) columns in the query, you can add
a blobidarray parameter containing the corresponding "blob ids",
and you should replace those columns with a "?" in the query text.
Return Values
Returns valid Informix result identifier on success, or FALSE on errors.
Examples
Example #1 Show all rows of the "orders" table as a HTML table
%s \n", ifx_error(), ifx_errormsg());
die;
}
ifx_htmltbl_result($res_id, "border=\"1\"");
ifx_free_result($res_id);
?>
Example #2 Insert some values into the "catalog" table
See Also
* ifx_connect() - Open Informix server connection
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_textasvarchar
(PHP 4, PHP <=5.2.0)
ifx_textasvarchar - Set the default text mode
Description
bool ifx_textasvarchar ( int $mode )
Sets the default text mode for all select-queries.
Parameters
mode
Mode "0" will return a blob id, and mode "1" will return a varchar
with text content.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ifx_byteasvarchar() - Set the default byte mode
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_update_blob
(PHP 4, PHP <=5.2.0)
ifx_update_blob - Updates the content of the blob object
Description
bool ifx_update_blob ( int $bid , string $content )
Updates the content of the blob object for the given blob object bid.
Parameters
bid
A BLOB object identifier.
content
The new data, as a string.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ifx_update_char() - Updates the content of the char object
----------------------------------------------------------------------
----------------------------------------------------------------------
ifx_update_char
(PHP 4, PHP <=5.2.0)
ifx_update_char - Updates the content of the char object
Description
bool ifx_update_char ( int $bid , string $content )
Updates the content of the char object for the given char object bid.
Parameters
bid
A char object identifier.
content
The new data, as a string.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ifx_update_blob() - Updates the content of the blob object
----------------------------------------------------------------------
----------------------------------------------------------------------
ifxus_close_slob
(PHP 4, PHP <=5.2.0)
ifxus_close_slob - Deletes the slob object
Description
bool ifxus_close_slob ( int $bid )
Deletes the slob object on the given slob object-id bid.
Parameters
bid
An existing slob id.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ifxus_open_slob() - Opens an slob object
----------------------------------------------------------------------
----------------------------------------------------------------------
ifxus_create_slob
(PHP 4, PHP <=5.2.0)
ifxus_create_slob - Creates an slob object and opens it
Description
int ifxus_create_slob ( int $mode )
Creates an slob object and opens it.
Parameters
mode
A combination of IFX_LO_RDONLY, IFX_LO_WRONLY, IFX_LO_APPEND
IFX_LO_RDWR, IFX_LO_BUFFER, IFX_LO_NOBUFFER.
Return Values
Return the new slob object-id, or FALSE on errors.
See Also
* ifxus_close_slob() - Deletes the slob object
* ifxus_free_slob() - Deletes the slob object
----------------------------------------------------------------------
----------------------------------------------------------------------
ifxus_free_slob
(PHP 4, PHP <=5.2.0)
ifxus_free_slob - Deletes the slob object
Description
bool ifxus_free_slob ( int $bid )
Deletes the slob object.
Parameters
bid
An existing slob id.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ifxus_close_slob() - Deletes the slob object
----------------------------------------------------------------------
----------------------------------------------------------------------
ifxus_open_slob
(PHP 4, PHP <=5.2.0)
ifxus_open_slob - Opens an slob object
Description
int ifxus_open_slob ( int $bid , int $mode )
Opens an slob object. bid should be an existing slob id.
Parameters
bid
An existing slob id.
mode
A combination of IFX_LO_RDONLY, IFX_LO_WRONLY, IFX_LO_APPEND
IFX_LO_RDWR, IFX_LO_BUFFER, IFX_LO_NOBUFFER.
Return Values
Returns the new slob object-id, or FALSE on errors.
See Also
* ifxus_close_slob() - Deletes the slob object
* ifxus_free_slob() - Deletes the slob object
----------------------------------------------------------------------
----------------------------------------------------------------------
ifxus_read_slob
(PHP 4, PHP <=5.2.0)
ifxus_read_slob - Reads nbytes of the slob object
Description
string ifxus_read_slob ( int $bid , int $nbytes )
Reads nbytes of the slob object.
Parameters
bid
An existing slob id.
nbytes
The number of bytes to read.
Return Values
Returns the slob contents as a string, or FALSE on errors.
See Also
* ifxus_write_slob() - Writes a string into the slob object
----------------------------------------------------------------------
----------------------------------------------------------------------
ifxus_seek_slob
(PHP 4, PHP <=5.2.0)
ifxus_seek_slob - Sets the current file or seek position
Description
int ifxus_seek_slob ( int $bid , int $mode , int $offset )
Sets the current file or seek position of an open slob object.
Parameters
bid
An existing slob id.
mode
0 = LO_SEEK_SET, 1 = LO_SEEK_CUR, 2 = LO_SEEK_END.
offset
A byte offset.
Return Values
Returns the seek position as an integer, or FALSE on errors.
See Also
* ifxus_tell_slob() - Returns the current file or seek position
----------------------------------------------------------------------
----------------------------------------------------------------------
ifxus_tell_slob
(PHP 4, PHP <=5.2.0)
ifxus_tell_slob - Returns the current file or seek position
Description
int ifxus_tell_slob ( int $bid )
Returns the current file or seek position of an open slob object
Parameters
bid
An existing slob id.
Return Values
Returns the seek position as an integer, or FALSE on errors.
See Also
* ifxus_seek_slob() - Sets the current file or seek position
----------------------------------------------------------------------
----------------------------------------------------------------------
ifxus_write_slob
(PHP 4, PHP <=5.2.0)
ifxus_write_slob - Writes a string into the slob object
Description
int ifxus_write_slob ( int $bid , string $content )
Writes a string into the slob object.
Parameters
bid
An existing slob id.
content
The content to write, as a string.
Return Values
Returns the bytes written as an integer, or FALSE on errors.
See Also
* ifxus_read_slob() - Reads nbytes of the slob object
----------------------------------------------------------------------
Table of Contents
* ifx_affected_rows - Get number of rows affected by a query
* ifx_blobinfile_mode - Set the default blob mode for all select queries
* ifx_byteasvarchar - Set the default byte mode
* ifx_close - Close Informix connection
* ifx_connect - Open Informix server connection
* ifx_copy_blob - Duplicates the given blob object
* ifx_create_blob - Creates an blob object
* ifx_create_char - Creates an char object
* ifx_do - Execute a previously prepared SQL-statement
* ifx_error - Returns error code of last Informix call
* ifx_errormsg - Returns error message of last Informix call
* ifx_fetch_row - Get row as an associative array
* ifx_fieldproperties - List of SQL fieldproperties
* ifx_fieldtypes - List of Informix SQL fields
* ifx_free_blob - Deletes the blob object
* ifx_free_char - Deletes the char object
* ifx_free_result - Releases resources for the query
* ifx_get_blob - Return the content of a blob object
* ifx_get_char - Return the content of the char object
* ifx_getsqlca - Get the contents of sqlca.sqlerrd[0..5] after a query
* ifx_htmltbl_result - Formats all rows of a query into a HTML table
* ifx_nullformat - Sets the default return value on a fetch row
* ifx_num_fields - Returns the number of columns in the query
* ifx_num_rows - Count the rows already fetched from a query
* ifx_pconnect - Open persistent Informix connection
* ifx_prepare - Prepare an SQL-statement for execution
* ifx_query - Send Informix query
* ifx_textasvarchar - Set the default text mode
* ifx_update_blob - Updates the content of the blob object
* ifx_update_char - Updates the content of the char object
* ifxus_close_slob - Deletes the slob object
* ifxus_create_slob - Creates an slob object and opens it
* ifxus_free_slob - Deletes the slob object
* ifxus_open_slob - Opens an slob object
* ifxus_read_slob - Reads nbytes of the slob object
* ifxus_seek_slob - Sets the current file or seek position
* ifxus_tell_slob - Returns the current file or seek position
* ifxus_write_slob - Writes a string into the slob object
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Informix Functions
* ifx_affected_rows - Get number of rows affected by a query
* ifx_blobinfile_mode - Set the default blob mode for all select
queries
* ifx_byteasvarchar - Set the default byte mode
* ifx_close - Close Informix connection
* ifx_connect - Open Informix server connection
* ifx_copy_blob - Duplicates the given blob object
* ifx_create_blob - Creates an blob object
* ifx_create_char - Creates an char object
* ifx_do - Execute a previously prepared SQL-statement
* ifx_error - Returns error code of last Informix call
* ifx_errormsg - Returns error message of last Informix call
* ifx_fetch_row - Get row as an associative array
* ifx_fieldproperties - List of SQL fieldproperties
* ifx_fieldtypes - List of Informix SQL fields
* ifx_free_blob - Deletes the blob object
* ifx_free_char - Deletes the char object
* ifx_free_result - Releases resources for the query
* ifx_get_blob - Return the content of a blob object
* ifx_get_char - Return the content of the char object
* ifx_getsqlca - Get the contents of sqlca.sqlerrd[0..5] after a
query
* ifx_htmltbl_result - Formats all rows of a query into a HTML
table
* ifx_nullformat - Sets the default return value on a fetch row
* ifx_num_fields - Returns the number of columns in the query
* ifx_num_rows - Count the rows already fetched from a query
* ifx_pconnect - Open persistent Informix connection
* ifx_prepare - Prepare an SQL-statement for execution
* ifx_query - Send Informix query
* ifx_textasvarchar - Set the default text mode
* ifx_update_blob - Updates the content of the blob object
* ifx_update_char - Updates the content of the char object
* ifxus_close_slob - Deletes the slob object
* ifxus_create_slob - Creates an slob object and opens it
* ifxus_free_slob - Deletes the slob object
* ifxus_open_slob - Opens an slob object
* ifxus_read_slob - Reads nbytes of the slob object
* ifxus_seek_slob - Sets the current file or seek position
* ifxus_tell_slob - Returns the current file or seek position
* ifxus_write_slob - Writes a string into the slob object
----------------------------------------------------------------------
----------------------------------------------------------------------
IBM DB2, Cloudscape and Apache Derby
----------------------------------------------------------------------
Introduction
These functions enable you to access IBM DB2 Universal Database, IBM
Cloudscape, and Apache Derby databases using the DB2 Call Level Interface
(DB2 CLI).
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
To connect to IBM DB2 Universal Database for Linux, UNIX, and Windows, or
IBM Cloudscape, or Apache Derby, you must install an IBM DB2 Universal
Database client on the same computer on which you are running PHP. The
extension has been developed and tested with DB2 Version 8.2.
To connect to IBM DB2 Universal Database for z/OS or iSeries, you also
require IBM DB2 Connect or the equivalent DRDA gateway software.
Requirements on Linux or Unix
The user invoking the PHP executable or SAPI must specify the DB2 instance
before accessing these functions. You can set the name of the DB2 instance
in php.ini using the ibm_db2.instance_name configuration option, or you
can source the DB2 instance profile before invoking the PHP executable.
If you created a DB2 instance named db2inst1 in /home/db2inst1/, for
example, you can add the following line to php.ini:
ibm_db2.instance_name=db2inst1
If you do not set this option in php.ini, you must issue the following
command to modify your environment variables to enable access to DB2:
bash$ source /home/db2inst1/sqllib/db2profile
To enable your PHP-enabled Web server to access these functions, you must
either set the ibm_db2.instance_name configuration option in php.ini, or
source the DB2 instance environment in your Web server start script
(typically /etc/init.d/httpd or /etc/init.d/apache).
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
To build the ibm_db2 extension, the DB2 application development header
files and libraries must be installed on your system. DB2 does not install
these by default, so you may have to return to your DB2 installer and add
this option. The header files are included with the DB2 Application
Development Client freely available for download from the IBM DB2
Universal Database >> support site.
If you add the DB2 application development header files and libraries to a
Linux or Unix operating system on which DB2 was already installed, you
must issue the command db2iupdt -e to update the symbolic links to the
header files and libraries in your DB2 instances.
ibm_db2 is a >> PECL extension, so follow the instructions in Installation
of PECL extensions to install the ibm_db2 extension for PHP. Issue the
configure command to point to the location of your DB2 header files and
libraries as follows:
bash$ ./configure --with-IBM_DB2=/path/to/DB2
The configure command defaults to /opt/IBM/db2/V8.1.
Note: Note for IIS users
If you are using the ibm_db2 driver with Microsoft Internet Information
Server (IIS) you may have to do the following:
* Install DB2 with extended operating system security.
* Add the PHP binary path to the PATH system environment variable
(default C:\php\).
* Create another system environment variable equal to the path where
the PHP.INI file is located (eg: PHPRC = C:\php\).
* Add the IUSR_COMPUTERNAME to the DB2USERS group.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
ibm_db2 Configure Options
Name Default Changeable Changelog
ibm_db2.binmode "1" PHP_INI_ALL
ibm_db2.i5_all_pconnect "0" PHP_INI_SYSTEM Available since ibm_db2
1.6.5.
ibm_db2.i5_allow_commit "0" PHP_INI_SYSTEM Available since ibm_db2
1.4.9.
ibm_db2.i5_dbcs_alloc "0" PHP_INI_SYSTEM Available since ibm_db2
1.5.0.
ibm_db2.instance_name NULL PHP_INI_SYSTEM Available since ibm_db2
1.0.2.
ibm_db2.i5_ignore_userid "0" PHP_INI_SYSTEM Available since ibm_db2
1.8.0.
Here's a short explanation of the configuration directives.
ibm_db2.binmode integer
This option controls the mode used for converting to and from
binary data in the PHP application.
* 1 (DB2_BINARY)
* 2 (DB2_CONVERT)
* 3 (DB2_PASSTHRU)
ibm_db2.i5_all_pconnect integer
This option overrides i5 db2_connect() full open and close in the
PHP application. When ibm_db2.i5_all_pconnect = 1, all db2
connections become persistent (db2_pconnect()). On i5/OS,
db2_pconnect() performs dramatically better with lower machine
stress over db2_connect(). This is a convenience override of
db2_connect() to evoke db2_pconnect() without PHP source code
changes.
* 0 db2_connect() default full open and close
* 1 db2_connect() override to db2_pconnect() for persistent
connection only
ibm_db2.i5_allow_commit integer
This option controls the commit mode used for i5 schema
collections in the PHP application.
* 0 no commit (see i5_commit for override)
* 1 allow commit (see i5_commit for override)
ibm_db2.i5_dbcs_alloc integer
This option controls the internal ibm_db2 allocation scheme for
large DBCS column buffers.
* 0 no expanded allocations (see i5_dbcs_alloc for override)
* 1 use expanded allocations (see i5_dbcs_alloc for override)
ibm_db2.instance_name string
On Linux and UNIX operating systems, this option defines the name
of the instance to use for cataloged database connections. If this
option is set, its value overrides the DB2INSTANCE environment
variable setting.
This option is ignored on Windows operating systems.
ibm_db2.i5_ignore_userid integer
This option overrides i5 db2_(p)connect userid and password in the
PHP application. When ibm_db2.i5_ignore_userid = 1, all db2
(p)connections become null userid and null password. Therefore
Apache jobs connect with the current profile (NOBODY). Use of this
override is only for simple DB2 based websites that never require
profile switching and therefore can avoid all overhead of server
mode additional QSQSRVR jobs. This is a convenience override of
db2_(p)connect to set the userid and password values to null
without PHP source code changes. This override can be used in
combination with ibm_db2.i5_all_pconnect = 1.
* 0 db2_(p)connect with specified userid and password
* 1 db2_(p)connect override connect with null userid and null
password
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
The ibm_db2 extension returns connection resources, statement resources,
and result set resources.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
DB2_BINARY (integer)
Specifies that binary data shall be returned as is. This is the
default mode.
DB2_CONVERT (integer)
Specifies that binary data shall be converted to a hexadecimal
encoding and returned as an ASCII string.
DB2_PASSTHRU (integer)
Specifies that binary data shall be converted to a NULL value.
DB2_SCROLLABLE (integer)
Specifies a scrollable cursor for a statement resource. This mode
enables random access to rows in a result set, but currently is
supported only by IBM DB2 Universal Database.
DB2_FORWARD_ONLY (integer)
Specifies a forward-only cursor for a statement resource. This is
the default cursor type and is supported on all database servers.
DB2_PARAM_IN (integer)
Specifies the PHP variable should be bound as an IN parameter for
a stored procedure.
DB2_PARAM_OUT (integer)
Specifies the PHP variable should be bound as an OUT parameter for
a stored procedure.
DB2_PARAM_INOUT (integer)
Specifies the PHP variable should be bound as an INOUT parameter
for a stored procedure.
DB2_PARAM_FILE (integer)
Specifies that the column should be bound directly to a file for
input.
DB2_AUTOCOMMIT_ON (integer)
Specifies that autocommit should be turned on.
DB2_AUTOCOMMIT_OFF (integer)
Specifies that autocommit should be turned off.
DB2_DOUBLE (integer)
Specifies that the variable should be bound as a DOUBLE, FLOAT, or
REAL data type.
DB2_LONG (integer)
Specifies that the variable should be bound as a SMALLINT,
INTEGER, or BIGINT data type.
DB2_CHAR (integer)
Specifies that the variable should be bound as a CHAR or VARCHAR
data type.
DB2_CASE_NATURAL (integer)
Specifies that column names will be returned in their natural
case.
DB2_CASE_LOWER (integer)
Specifies that column names will be returned in lower case.
DB2_CASE_UPPER (integer)
Specifies that column names will be returned in upper case.
DB2_DEFERRED_PREPARE_ON (integer)
Specifies that deferred prepare should be turned on for the
specified statement resource.
DB2_DEFERRED_PREPARE_OFF (integer)
Specifies that deferred prepare should be turned off for the
specified statement resource.
----------------------------------------------------------------------
----------------------------------------------------------------------
IBM DB2 Functions
----------------------------------------------------------------------
db2_autocommit
(PECL ibm_db2 >= 1.0.0)
db2_autocommit - Returns or sets the AUTOCOMMIT state for a database
connection
Description
mixed db2_autocommit ( resource $connection [, bool $value ] )
Sets or gets the AUTOCOMMIT behavior of the specified connection resource.
Parameters
connection
A valid database connection resource variable as returned from
db2_connect() or db2_pconnect().
value
One of the following constants:
DB2_AUTOCOMMIT_OFF
Turns AUTOCOMMIT off.
DB2_AUTOCOMMIT_ON
Turns AUTOCOMMIT on.
Return Values
When db2_autocommit() receives only the connection parameter, it returns
the current state of AUTOCOMMIT for the requested connection as an integer
value. A value of 0 indicates that AUTOCOMMIT is off, while a value of 1
indicates that AUTOCOMMIT is on.
When db2_autocommit() receives both the connection parameter and
autocommit parameter, it attempts to set the AUTOCOMMIT state of the
requested connection to the corresponding state. Returns TRUE on success
or FALSE on failure.
Examples
Example #1 Retrieving the AUTOCOMMIT value for a connection
In the following example, a connection which has been created with
AUTOCOMMIT turned off is tested with the db2_autocommit() function.
DB2_AUTOCOMMIT_OFF);
$conn = db2_connect($database, $user, $password, $options);
$ac = db2_autocommit($conn);
if ($ac == 0) {
print "$ac -- AUTOCOMMIT is off.";
} else {
print "$ac -- AUTOCOMMIT is on.";
}
?>
The above example will output:
0 -- AUTOCOMMIT is off.
Example #2 Setting the AUTOCOMMIT value for a connection
In the following example, a connection which was initially created with
AUTOCOMMIT turned off has its behavior changed to turn AUTOCOMMIT on.
DB2_AUTOCOMMIT_OFF);
$conn = db2_connect($database, $user, $password, $options);
// Turn AUTOCOMMIT on
$rc = db2_autocommit($conn, DB2_AUTOCOMMIT_ON);
if ($rc) {
print "Turning AUTOCOMMIT on succeeded.\n";
}
// Check AUTOCOMMIT state
$ac = db2_autocommit($conn);
if ($ac == 0) {
print "$ac -- AUTOCOMMIT is off.";
} else {
print "$ac -- AUTOCOMMIT is on.";
}
?>
The above example will output:
Turning AUTOCOMMIT on succeeded.
1 -- AUTOCOMMIT is on.
See Also
* db2_connect() - Returns a connection to a database
* db2_pconnect() - Returns a persistent connection to a database
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_bind_param
(PECL ibm_db2 >= 1.0.0)
db2_bind_param - Binds a PHP variable to an SQL statement parameter
Description
bool db2_bind_param ( resource $stmt , int $parameter-number , string
$variable-name [, int $parameter-type [, int $data-type = 0 [, int
$precision = -1 [, int $scale = 0 ]]]] )
Binds a PHP variable to an SQL statement parameter in a statement resource
returned by db2_prepare(). This function gives you more control over the
parameter type, data type, precision, and scale for the parameter than
simply passing the variable as part of the optional input array to
db2_execute().
Parameters
stmt
A prepared statement returned from db2_prepare().
parameter-number
Specifies the 1-indexed position of the parameter in the prepared
statement.
variable-name
A string specifying the name of the PHP variable to bind to the
parameter specified by parameter-number.
parameter-type
A constant specifying whether the PHP variable should be bound to
the SQL parameter as an input parameter (DB2_PARAM_IN), an output
parameter (DB2_PARAM_OUT), or as a parameter that accepts input
and returns output (DB2_PARAM_INOUT). To avoid memory overhead,
you can also specify DB2_PARAM_FILE to bind the PHP variable to
the name of a file that contains large object (BLOB, CLOB, or
DBCLOB) data.
data-type
A constant specifying the SQL data type that the PHP variable
should be bound as: one of DB2_BINARY, DB2_CHAR, DB2_DOUBLE, or
DB2_LONG .
precision
Specifies the precision with which the variable should be bound to
the database. This parameter can also be used for retrieving XML
output values from stored procedures. A non-negative value
specifies the maximum size of the XML data that will be retrieved
from the database. If this parameter is not used, a default of 1MB
will be assumed for retrieving the XML output value from the
stored procedure.
scale
Specifies the scale with which the variable should be bound to the
database.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Binding PHP variables to a prepared statement
The SQL statement in the following example uses two input parameters in
the WHERE clause. We call db2_bind_param() to bind two PHP variables to
the corresponding SQL parameters. Notice that the PHP variables do not
have to be declared or assigned before the call to db2_bind_param(); in
the example, $lower_limit is assigned a value before the call to
db2_bind_param(), but $upper_limit is assigned a value after the call to
db2_bind_param(). The variables must be bound and, for parameters that
accept input, must have any value assigned, before calling db2_execute().
? AND weight < ?';
$conn = db2_connect($database, $user, $password);
$stmt = db2_prepare($conn, $sql);
// We can declare the variable before calling db2_bind_param()
$lower_limit = 1;
db2_bind_param($stmt, 1, "lower_limit", DB2_PARAM_IN);
db2_bind_param($stmt, 2, "upper_limit", DB2_PARAM_IN);
// We can also declare the variable after calling db2_bind_param()
$upper_limit = 15.0;
if (db2_execute($stmt)) {
while ($row = db2_fetch_array($stmt)) {
print "{$row[0]}, {$row[1]}, {$row[2]}\n";
}
}
?>
The above example will output:
Pook, cat, 3.2
Rickety Ride, goat, 9.7
Peaches, dog, 12.3
Example #2 Calling stored procedures with IN and OUT parameters
The stored procedure match_animal in the following example accepts three
different parameters:
1. an input (IN) parameter that accepts the name of the first animal as
input
2. an input-output (INOUT) parameter that accepts the name of the second
animal as input and returns the string TRUE if an animal in the
database matches that name
3. an output (OUT) parameter that returns the sum of the weight of the
two identified animals
In addition, the stored procedure returns a result set consisting of the
animals listed in alphabetic order starting at the animal corresponding to
the input value of the first parameter and ending at the animal
corresponding to the input value of the second parameter.
The above example will output:
Values of bound parameters _before_ CALL:
1: Peaches 2: Rickety Ride 3: 0
Values of bound parameters _after_ CALL:
1: Peaches 2: TRUE 3: 22
Results:
Peaches, dog, 12.3
Pook, cat, 3.2
Rickety Ride, goat, 9.7
Example #3 Inserting a binary large object (BLOB) directly from a file
The data for large objects are typically stored in files, such as XML
documents or audio files. Rather than reading an entire file into a PHP
variable, and then binding that PHP variable into an SQL statement, you
can avoid some memory overhead by binding the file directly to the input
parameter of your SQL statement. The following example demonstrates how to
bind a file directly into a BLOB column.
See Also
* db2_execute() - Executes a prepared SQL statement
* db2_prepare() - Prepares an SQL statement to be executed
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_client_info
(PECL ibm_db2 >= 1.1.1)
db2_client_info - Returns an object with properties that describe the DB2
database client
Description
object db2_client_info ( resource $connection )
This function returns an object with read-only properties that return
information about the DB2 database client. The following table lists the
DB2 client properties:
DB2 client properties
Property name Return type Description
APPL_CODEPAGE int The application code page.
CONN_CODEPAGE int The code page for the current connection.
DATA_SOURCE_NAME string The data source name (DSN) used to create
the current connection to the database.
The name of the library that implements
DRIVER_NAME string the DB2 Call Level Interface (CLI)
specification.
The version of ODBC that the DB2 client
supports. This returns a string "MM.mm"
DRIVER_ODBC_VER string where MM is the major version and mm is
the minor version. The DB2 client always
returns "03.51".
The version of the client, in the form of
a string "MM.mm.uuuu" where MM is the
DRIVER_VER string major version, mm is the minor version,
and uuuu is the update. For example,
"08.02.0001" represents major version 8,
minor version 2, update 1.
The level of ODBC SQL grammar supported
by the client:
MINIMUM
Supports the minimum ODBC SQL grammar.
ODBC_SQL_CONFORMANCE string
CORE
Supports the core ODBC SQL grammar.
EXTENDED
Supports extended ODBC SQL grammar.
The version of ODBC that the ODBC driver
manager supports. This returns a string
ODBC_VER string "MM.mm.rrrr" where MM is the major
version, mm is the minor version, and
rrrr is the release. The DB2 client
always returns "03.01.0000".
Parameters
connection
Specifies an active DB2 client connection.
Return Values
Returns an object on a successful call. Returns FALSE on failure.
Examples
Example #1 A db2_client_info() example
To retrieve information about the client, you must pass a valid database
connection resource to db2_client_info().
DRIVER_NAME );
echo "DRIVER_VER: "; var_dump( $client->DRIVER_VER );
echo "DATA_SOURCE_NAME: "; var_dump( $client->DATA_SOURCE_NAME );
echo "DRIVER_ODBC_VER: "; var_dump( $client->DRIVER_ODBC_VER );
echo "ODBC_VER: "; var_dump( $client->ODBC_VER );
echo "ODBC_SQL_CONFORMANCE: "; var_dump( $client->ODBC_SQL_CONFORMANCE );
echo "APPL_CODEPAGE: "; var_dump( $client->APPL_CODEPAGE );
echo "CONN_CODEPAGE: "; var_dump( $client->CONN_CODEPAGE );
}
else {
echo "Error retrieving client information.
Perhaps your database connection was invalid.";
}
db2_close($conn);
?>
The above example will output:
DRIVER_NAME: string(8) "libdb2.a"
DRIVER_VER: string(10) "08.02.0001"
DATA_SOURCE_NAME: string(6) "SAMPLE"
DRIVER_ODBC_VER: string(5) "03.51"
ODBC_VER: string(10) "03.01.0000"
ODBC_SQL_CONFORMANCE: string(8) "EXTENDED"
APPL_CODEPAGE: int(819)
CONN_CODEPAGE: int(819)
See Also
* db2_server_info() - Returns an object with properties that describe
the DB2 database server
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_close
(PECL ibm_db2 >= 1.0.0)
db2_close - Closes a database connection
Description
bool db2_close ( resource $connection )
This function closes a DB2 client connection created with db2_connect()
and returns the corresponding resources to the database server.
If you attempt to close a persistent DB2 client connection created with
db2_pconnect(), the close request is ignored and the persistent DB2 client
connection remains available for the next caller.
Parameters
connection
Specifies an active DB2 client connection.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Closing a connection
The following example demonstrates a successful attempt to close a
connection to an IBM DB2, Cloudscape, or Apache Derby database.
The above example will output:
Connection was successfully closed.
See Also
* db2_connect() - Returns a connection to a database
* db2_pclose() - Closes a persistent database connection
* db2_pconnect() - Returns a persistent connection to a database
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_column_privileges
(PECL ibm_db2 >= 1.0.0)
db2_column_privileges - Returns a result set listing the columns and
associated privileges for a table
Description
resource db2_column_privileges ( resource $connection [, string $qualifier
[, string $schema [, string $table-name [, string $column-name ]]]] )
Returns a result set listing the columns and associated privileges for a
table.
Parameters
connection
A valid connection to an IBM DB2, Cloudscape, or Apache Derby
database.
qualifier
A qualifier for DB2 databases running on OS/390 or z/OS servers.
For other databases, pass NULL or an empty string.
schema
The schema which contains the tables. To match all schemas, pass
NULL or an empty string.
table-name
The name of the table or view. To match all tables in the
database, pass NULL or an empty string.
column-name
The name of the column. To match all columns in the table, pass
NULL or an empty string.
Return Values
Returns a statement resource with a result set containing rows describing
the column privileges for columns matching the specified parameters. The
rows are composed of the following columns:
Column name Description
TABLE_CAT Name of the catalog. The value is NULL if this table does not
have catalogs.
TABLE_SCHEM Name of the schema.
TABLE_NAME Name of the table or view.
COLUMN_NAME Name of the column.
GRANTOR Authorization ID of the user who granted the privilege.
GRANTEE Authorization ID of the user to whom the privilege was
granted.
PRIVILEGE The privilege for the column.
IS_GRANTABLE Whether the GRANTEE is permitted to grant this privilege to
other users.
See Also
* db2_columns() - Returns a result set listing the columns and
associated metadata for a table
* db2_foreign_keys() - Returns a result set listing the foreign keys for
a table
* db2_primary_keys() - Returns a result set listing primary keys for a
table
* db2_procedure_columns() - Returns a result set listing stored
procedure parameters
* db2_procedures() - Returns a result set listing the stored procedures
registered in a database
* db2_special_columns() - Returns a result set listing the unique row
identifier columns for a table
* db2_statistics() - Returns a result set listing the index and
statistics for a table
* db2_table_privileges() - Returns a result set listing the tables and
associated privileges in a database
* db2_tables() - Returns a result set listing the tables and associated
metadata in a database
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_columns
(PECL ibm_db2 >= 1.0.0)
db2_columns - Returns a result set listing the columns and associated
metadata for a table
Description
resource db2_columns ( resource $connection [, string $qualifier [, string
$schema [, string $table-name [, string $column-name ]]]] )
Returns a result set listing the columns and associated metadata for a
table.
Parameters
connection
A valid connection to an IBM DB2, Cloudscape, or Apache Derby
database.
qualifier
A qualifier for DB2 databases running on OS/390 or z/OS servers.
For other databases, pass NULL or an empty string.
schema
The schema which contains the tables. To match all schemas, pass
'%'.
table-name
The name of the table or view. To match all tables in the
database, pass NULL or an empty string.
column-name
The name of the column. To match all columns in the table, pass
NULL or an empty string.
Return Values
Returns a statement resource with a result set containing rows describing
the columns matching the specified parameters. The rows are composed of
the following columns:
Column name Description
TABLE_CAT Name of the catalog. The value is NULL if this table
does not have catalogs.
TABLE_SCHEM Name of the schema.
TABLE_NAME Name of the table or view.
COLUMN_NAME Name of the column.
DATA_TYPE The SQL data type for the column represented as an
integer value.
TYPE_NAME A string representing the data type for the column.
COLUMN_SIZE An integer value representing the size of the column.
BUFFER_LENGTH Maximum number of bytes necessary to store data from
this column.
DECIMAL_DIGITS The scale of the column, or NULL where scale is not
applicable.
An integer value of either 10 (representing an exact
NUM_PREC_RADIX numeric data type), 2 (representing an approximate
numeric data type), or NULL (representing a data type
for which radix is not applicable).
NULLABLE An integer value representing whether the column is
nullable or not.
REMARKS Description of the column.
COLUMN_DEF Default value for the column.
SQL_DATA_TYPE An integer value representing the size of the column.
Returns an integer value representing a datetime subtype
SQL_DATETIME_SUB code, or NULL for SQL data types to which this does not
apply.
Maximum length in octets for a character data type
CHAR_OCTET_LENGTH column, which matches COLUMN_SIZE for single-byte
character set data, or NULL for non-character data
types.
ORDINAL_POSITION The 1-indexed position of the column in the table.
IS_NULLABLE A string value where 'YES' means that the column is
nullable and 'NO' means that the column is not nullable.
See Also
* db2_column_privileges() - Returns a result set listing the columns and
associated privileges for a table
* db2_foreign_keys() - Returns a result set listing the foreign keys for
a table
* db2_primary_keys() - Returns a result set listing primary keys for a
table
* db2_procedure_columns() - Returns a result set listing stored
procedure parameters
* db2_procedures() - Returns a result set listing the stored procedures
registered in a database
* db2_special_columns() - Returns a result set listing the unique row
identifier columns for a table
* db2_statistics() - Returns a result set listing the index and
statistics for a table
* db2_table_privileges() - Returns a result set listing the tables and
associated privileges in a database
* db2_tables() - Returns a result set listing the tables and associated
metadata in a database
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_commit
(PECL ibm_db2 >= 1.0.0)
db2_commit - Commits a transaction
Description
bool db2_commit ( resource $connection )
Commits an in-progress transaction on the specified connection resource
and begins a new transaction. PHP applications normally default to
AUTOCOMMIT mode, so db2_commit() is not necessary unless AUTOCOMMIT has
been turned off for the connection resource.
Parameters
connection
A valid database connection resource variable as returned from
db2_connect() or db2_pconnect().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* db2_autocommit() - Returns or sets the AUTOCOMMIT state for a database
connection
* db2_rollback() - Rolls back a transaction
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_conn_error
(PECL ibm_db2 >= 1.0.0)
db2_conn_error - Returns a string containing the SQLSTATE returned by the
last connection attempt
Description
string db2_conn_error ([ resource $connection ] )
db2_conn_error() returns an SQLSTATE value representing the reason the
last attempt to connect to a database failed. As db2_connect() returns
FALSE in the event of a failed connection attempt, you do not pass any
parameters to db2_conn_error() to retrieve the SQLSTATE value.
If, however, the connection was successful but becomes invalid over time,
you can pass the connection parameter to retrieve the SQLSTATE value for a
specific connection.
To learn what the SQLSTATE value means, you can issue the following
command at a DB2 Command Line Processor prompt: db2 '? sqlstate-value'.
You can also call db2_conn_errormsg() to retrieve an explicit error
message and the associated SQLCODE value.
Parameters
connection
A connection resource associated with a connection that initially
succeeded, but which over time became invalid.
Return Values
Returns the SQLSTATE value resulting from a failed connection attempt.
Returns an empty string if there is no error associated with the last
connection attempt.
Examples
Example #1 Retrieving an SQLSTATE value for a failed connection attempt
The following example demonstrates how to return an SQLSTATE value after
deliberately passing invalid parameters to db2_connect().
The above example will output:
SQLSTATE value: 08001
See Also
* db2_conn_errormsg() - Returns the last connection error message and
SQLCODE value
* db2_connect() - Returns a connection to a database
* db2_stmt_error() - Returns a string containing the SQLSTATE returned
by an SQL statement
* db2_stmt_errormsg() - Returns a string containing the last SQL
statement error message
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_conn_errormsg
(PECL ibm_db2 >= 1.0.0)
db2_conn_errormsg - Returns the last connection error message and SQLCODE
value
Description
string db2_conn_errormsg ([ resource $connection ] )
db2_conn_errormsg() returns an error message and SQLCODE value
representing the reason the last database connection attempt failed. As
db2_connect() returns FALSE in the event of a failed connection attempt,
do not pass any parameters to db2_conn_errormsg() to retrieve the
associated error message and SQLCODE value.
If, however, the connection was successful but becomes invalid over time,
you can pass the connection parameter to retrieve the associated error
message and SQLCODE value for a specific connection.
Parameters
connection
A connection resource associated with a connection that initially
succeeded, but which over time became invalid.
Return Values
Returns a string containing the error message and SQLCODE value resulting
from a failed connection attempt. If there is no error associated with the
last connection attempt, db2_conn_errormsg() returns an empty string.
Examples
Example #1 Retrieving the error message returned by a failed connection
attempt
The following example demonstrates how to return an error message and
SQLCODE value after deliberately passing invalid parameters to
db2_connect().
The above example will output:
[IBM][CLI Driver] SQL1013N The database alias name
or database name "BADNAME" could not be found. SQLSTATE=42705
SQLCODE=-1013
See Also
* db2_conn_error() - Returns a string containing the SQLSTATE returned
by the last connection attempt
* db2_connect() - Returns a connection to a database
* db2_stmt_error() - Returns a string containing the SQLSTATE returned
by an SQL statement
* db2_stmt_errormsg() - Returns a string containing the last SQL
statement error message
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_connect
(PECL ibm_db2 >= 1.0.0)
db2_connect - Returns a connection to a database
Description
resource db2_connect ( string $database , string $username , string
$password [, array $options ] )
Creates a new connection to an IBM DB2 Universal Database, IBM Cloudscape,
or Apache Derby database.
Parameters
database
For a cataloged connection to a database, database represents the
database alias in the DB2 client catalog.
For an uncataloged connection to a database, database represents a
complete connection string in the following format:
DATABASE=database;HOSTNAME=hostname;PORT=port;PROTOCOL=TCPIP;UID=username;PWD=password;
where the parameters represent the following values:
database
The name of the database.
hostname
The hostname or IP address of the database server.
port
The TCP/IP port on which the database is listening
for requests.
username
The username with which you are connecting to the
database.
password
The password with which you are connecting to the
database.
username
The username with which you are connecting to the database.
For uncataloged connections, you must pass a NULL value or empty
string.
password
The password with which you are connecting to the database.
For uncataloged connections, you must pass a NULL value or empty
string.
options
An associative array of connection options that affect the
behavior of the connection, where valid array keys include:
autocommit
Passing the DB2_AUTOCOMMIT_ON value turns autocommit
on for this connection handle.
Passing the DB2_AUTOCOMMIT_OFF value turns autocommit
off for this connection handle.
DB2_ATTR_CASE
Passing the DB2_CASE_NATURAL value specifies that
column names are returned in natural case.
Passing the DB2_CASE_LOWER value specifies that
column names are returned in lower case.
Passing the DB2_CASE_UPPER value specifies that
column names are returned in upper case.
CURSOR
Passing the DB2_FORWARD_ONLY value specifies a
forward-only cursor for a statement resource. This is
the default cursor type and is supported on all
database servers.
Passing the DB2_SCROLLABLE value specifies a
scrollable cursor for a statement resource. This mode
enables random access to rows in a result set, but
currently is supported only by IBM DB2 Universal
Database.
The following new option is available in ibm_db2 version 1.7.0 and
later.
trustedcontext
Passing the DB2_TRUSTED_CONTEXT_ENABLE value turns
trusted context on for this connection handle. This
parameter cannot be set using db2_set_option().
This key works only if the database is cataloged
(even if the database is local), or if you specify
the full DSN when you create the connection.
To catalog the database, use following commands:
db2 catalog tcpip node loopback remote server
db2 catalog database as at node loopback
db2 "update dbm cfg using svcename "
db2set DB2COMM=TCPIP
The following new i5/OS options are available in ibm_db2 version
1.5.1 and later.
i5_lib
A character value that indicates the default library
that will be used for resolving unqualified file
references. This is not valid if the connection is
using system naming mode.
i5_naming
DB2_I5_NAMING_ON value turns on DB2 UDB CLI iSeries
system naming mode. Files are qualified using the
slash (/) delimiter. Unqualified files are resolved
using the library list for the job.
DB2_I5_NAMING_OFF value turns off DB2 UDB CLI default
naming mode, which is SQL naming. Files are qualified
using the period (.) delimiter. Unqualified files are
resolved using either the default library or the
current user ID.
i5_commit
The i5_commit attribute should be set before the
db2_connect(). If the value is changed after the
connection has been established, and the connection
is to a remote data source, the change does not take
effect until the next successful db2_connect() for
the connection handle.
Note:
The php.ini setting ibm_db2.i5_allow_commit==0 or
DB2_I5_TXN_NO_COMMIT is the default, but may be
overridden with the i5_commit option.
DB2_I5_TXN_NO_COMMIT - Commitment control is not
used.
DB2_I5_TXN_READ_UNCOMMITTED - Dirty reads,
nonrepeatable reads, and phantoms are possible.
DB2_I5_TXN_READ_COMMITTED - Dirty reads are not
possible. Nonrepeatable reads, and phantoms are
possible.
DB2_I5_TXN_REPEATABLE_READ - Dirty reads and
nonrepeatable reads are not possible. Phantoms are
possible.
DB2_I5_TXN_SERIALIZABLE - Transactions are
serializable. Dirty reads, non-repeatable reads, and
phantoms are not possible
i5_query_optimize
DB2_FIRST_IO All queries are optimized with the goal
of returning the first page of output as fast as
possible. This goal works well when the output is
controlled by a user who is most likely to cancel the
query after viewing the first page of output data.
Queries coded with an OPTIMIZE FOR nnn ROWS clause
honor the goal specified by the clause.
DB2_ALL_IO All queries are optimized with the goal of
running the entire query to completion in the
shortest amount of elapsed time. This is a good
option when the output of a query is being written to
a file or report, or the interface is queuing the
output data. Queries coded with an OPTIMIZE FOR nnn
ROWS clause honor the goal specified by the clause.
This is the default.
i5_dbcs_alloc
DB2_I5_DBCS_ALLOC_ON value turns on DB2 6X allocation
scheme for DBCS translation column size growth.
DB2_I5_DBCS_ALLOC_OFF value turns off DB2 6X
allocation scheme for DBCS translation column size
growth.
Note: php.ini setting ibm_db2.i5_dbcs_alloc==0 or
DB2_I5_DBCS_ALLOC_OFF is the default, but may be
overridden with the i5_dbcs_alloc option.
i5_date_fmt
DB2_I5_FMT_ISO - The International Organization for
Standardization (ISO) date format yyyy-mm-dd is used.
This is the default.
DB2_I5_FMT_USA - The United States date format
mm/dd/yyyy is used.
DB2_I5_FMT_EUR - The European date format dd.mm.yyyy
is used.
DB2_I5_FMT_JIS - The Japanese Industrial Standard
date format yyyy-mm-dd is used.
DB2_I5_FMT_MDY - The date format mm/dd/yyyy is used.
DB2_I5_FMT_DMY - The date format dd/mm/yyyy is used.
DB2_I5_FMT_YMD - The date format yy/mm/dd is used.
DB2_I5_FMT_JUL - The Julian date format yy/ddd is
used.
DB2_I5_FMT_JOB - The job default is used.
i5_date_sep
DB2_I5_SEP_SLASH - A slash ( / ) is used as the date
separator. This is the default.
DB2_I5_SEP_DASH - A dash ( - ) is used as the date
separator.
DB2_I5_SEP_PERIOD - A period ( . ) is used as the
date separator.
DB2_I5_SEP_COMMA - A comma ( , ) is used as the date
separator.
DB2_I5_SEP_BLANK - A blank is used as the date
separator.
DB2_I5_SEP_JOB - The job default is used
i5_time_fmt
DB2_I5_FMT_ISO - The International Organization for
Standardization (ISO) time format hh.mm.ss is used.
This is the default.
DB2_I5_FMT_USA - The United States time format
hh:mmxx is used, where xx is AM or PM.
DB2_I5_FMT_EUR - The European time format hh.mm.ss is
used.
DB2_I5_FMT_JIS - The Japanese Industrial Standard
time format hh:mm:ss is used.
DB2_I5_FMT_HMS - The hh:mm:ss format is used.
i5_time_sep
DB2_I5_SEP_COLON - A colon ( : ) is used as the time
separator. This is the default.
DB2_I5_SEP_PERIOD - A period ( . ) is used as the
time separator.
DB2_I5_SEP_COMMA - A comma ( , ) is used as the time
separator.
DB2_I5_SEP_BLANK - A blank is used as the time
separator.
DB2_I5_SEP_JOB - The job default is used.
i5_decimal_sep
DB2_I5_SEP_PERIOD - A period ( . ) is used as the
decimal separator. This is the default.
DB2_I5_SEP_COMMA - A comma ( , ) is used as the
decimal separator.
DB2_I5_SEP_JOB - The job default is used.
The following new i5/OS option is available in ibm_db2 version
1.8.0 and later.
i5_libl
A character value that indicates the library list
that will be used for resolving unqualified file
references. Specify the library list elements
separated by blanks 'i5_libl'=>"MYLIB YOURLIB
ANYLIB".
Note:
i5_libl calls qsys2/qcmdexc('cmd',cmdlen), which is
only available in i5/OS V5R4 and later.
Return Values
Returns a connection handle resource if the connection attempt is
successful. If the connection attempt fails, db2_connect() returns FALSE.
Examples
Example #1 Creating a cataloged connection
Cataloged connections require you to have previously cataloged the target
database through the DB2 Command Line Processor (CLP) or DB2 Configuration
Assistant.
The above example will output:
Connection succeeded.
Example #2 Creating an uncataloged connection
An uncataloged connection enables you to dynamically connect to a
database.
The above example will output:
Connection succeeded.
Example #3 Creating a connection with autocommit off by default
Passing an array of options to db2_connect() enables you to modify the
default behavior of the connection handle.
DB2_AUTOCOMMIT_OFF);
$conn = db2_connect($database, $user, $password, $options);
if ($conn) {
echo "Connection succeeded.\n";
if (db2_autocommit($conn)) {
echo "Autocommit is on.\n";
}
else {
echo "Autocommit is off.\n";
}
db2_close($conn);
}
else {
echo "Connection failed.";
}
?>
The above example will output:
Connection succeeded.
Autocommit is off.
Example #4 i5/OS best performance
To achieve best performance for your i5/OS ibm_db2 1.5.1 PHP application
use the default host, userid, and password for your db2_connect().
"qsys2"));
$result = db2_exec($i5,
"select * from systables where table_schema = '$library'");
while ($row = db2_fetch_both($result)) {
echo $row['TABLE_NAME']."";
}
db2_close($i5);
?>
The above example will output:
ANIMALS
NAMES
PICTURES
Example #5 Using trusted context
The following example shows how to enable trusted context, switch users,
and get the current user ID.
DB2_TRUSTED_CONTEXT_ENABLE);
$tc_conn = db2_connect($dsn, "", "", $options);
if($tc_conn) {
echo "Explicit trusted connection succeeded.\n";
if(db2_get_option($tc_conn, "trustedcontext")) {
$userBefore = db2_get_option($tc_conn, "trusted_user");
//Do some work as user 1.
//Switching to trusted user.
$parameters = array("trusted_user" => $tc_user,
"trusted_password" => $tcuser_pass);
$res = db2_set_option ($tc_conn, $parameters, 1);
$userAfter = db2_get_option($tc_conn, "trusted_user");
//Do more work as trusted user.
if($userBefore != $userAfter) {
echo "User has been switched." . "\n";
}
}
db2_close($tc_conn);
}
else {
echo "Explicit trusted connection failed.\n";
}
?>
The above example will output:
Explicit trusted connection succeeded.
User has been switched.
See Also
* db2_close() - Closes a database connection
* db2_pconnect() - Returns a persistent connection to a database
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_cursor_type
(PECL ibm_db2 >= 1.0.0)
db2_cursor_type - Returns the cursor type used by a statement resource
Description
int db2_cursor_type ( resource $stmt )
Returns the cursor type used by a statement resource. Use this to
determine if you are working with a forward-only cursor or scrollable
cursor.
Parameters
stmt
A valid statement resource.
Return Values
Returns either DB2_FORWARD_ONLY if the statement resource uses a
forward-only cursor or DB2_SCROLLABLE if the statement resource uses a
scrollable cursor.
See Also
* db2_prepare() - Prepares an SQL statement to be executed
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_escape_string
(PECL ibm_db2 >= 1.6.0)
db2_escape_string - Used to escape certain characters
Description
string db2_escape_string ( string $string_literal )
Prepends backslashes to special characters in the string argument.
Parameters
string_literal
The string that contains special characters that need to be
modified. Characters that are prepended with a backslash are \x00,
\n, \r, \, ', " and \x1a.
Return Values
Returns string_literal with the special characters noted above prepended
with backslashes.
Examples
Example #1 A db2_escape_string() example
Result of using the db2_escape_string() function
The above example will output:
db2_escape_string: All characters: \0 , \n , \r , \\ , \' , \" , \Z .
db2_escape_string: Backslash (\\). Single quote (\'). Double quote (\")
db2_escape_string: The NULL character \0 must be quoted as well
db2_escape_string: Intersting characters: \Z , \0 .
db2_escape_string: Nothing to quote
db2_escape_string: 200676
db2_escape_string:
See Also
* db2_prepare() - Prepares an SQL statement to be executed
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_exec
(PECL ibm_db2 >= 1.0.0)
db2_exec - Executes an SQL statement directly
Description
resource db2_exec ( resource $connection , string $statement [, array
$options ] )
Executes an SQL statement directly.
If you plan to interpolate PHP variables into the SQL statement,
understand that this is one of the more common security exposures.
Consider calling db2_prepare() to prepare an SQL statement with parameter
markers for input values. Then you can call db2_execute() to pass in the
input values and avoid SQL injection attacks.
If you plan to repeatedly issue the same SQL statement with different
parameters, consider calling db2_prepare() and db2_execute() to enable the
database server to reuse its access plan and increase the efficiency of
your database access.
Parameters
connection
A valid database connection resource variable as returned from
db2_connect() or db2_pconnect().
statement
An SQL statement. The statement cannot contain any parameter
markers.
options
An associative array containing statement options. You can use
this parameter to request a scrollable cursor on database servers
that support this functionality.
For a description of valid statement options, see
db2_set_option().
Return Values
Returns a statement resource if the SQL statement was issued successfully,
or FALSE if the database failed to execute the SQL statement.
Examples
Example #1 Creating a table with db2_exec()
The following example uses db2_exec() to issue a set of DDL statements in
the process of creating a table.
The above example will output:
Successfully created the table.
Insert... Insert... Insert... Insert... Insert... Insert... Insert...
Example #2 Executing a SELECT statement with a scrollable cursor
The following example demonstrates how to request a scrollable cursor for
an SQL statement issued by db2_exec().
DB2_SCROLLABLE));
while ($row = db2_fetch_array($stmt)) {
print "$row[0]\n";
}
}
?>
The above example will output:
Bubbles
Gizmo
Pook
Rickety Ride
Example #3 Returning XML data as an SQL ResultSet
The following example demonstrates how to work with documents stored in a
XML column using the SAMPLE database. Using some pretty simple SQL/XML,
this example returns some of the nodes in a XML document in an SQL
ResultSet format that most users are familiar with.
CID $row->NAME $row->PHONE\n");
}
db2_close($conn);
?>
The above example will output:
1000 Kathy Smith 416-555-1358
1001 Kathy Smith 905-555-7258
Example #4 Performing a "JOIN" with XML data
The following example works with documents stored in 2 different XML
columns in the SAMPLE database. It creates 2 temporary tables from the XML
documents from 2 different columns and returns an SQL ResultSet with
information regarding shipping status for the customer.
CID $row->NAME $row->PHONE $row->PONUM $row->STATUS\n");
}
db2_close($conn);
?>
The above example will output:
1001 Kathy Smith 905-555-7258 5002 Shipped
Example #5 Returning SQL data as part of a larger XML document
The following example works with a portion of the PRODUCT.DESCRIPTION
documents in the SAMPLE database. It creates a XML document containing
product description (XML data) and pricing info (SQL data).
{
for $prod in $doc/product
where $prod/description/price < 10.00
order by $prod/description/price ascending
return(
{
$prod,
{$start} ,
{$end} ,
{$promo}
}
)
}
\' passing by ref DESCRIPTION AS "doc",
PROMOSTART as "start",
PROMOEND as "end",
PROMOPRICE as "promo"
RETURNING SEQUENCE)
AS CLOB (32000))
AS NEW_PRODUCT_INFO
FROM PRODUCT
WHERE PID = \'100-100-01\'
';
$stmt = db2_exec($conn, $query);
while($row = db2_fetch_array($stmt)){
printf("$row[0]\n");
}
db2_close($conn);
?>
The above example will output:
Snow Shovel, Basic 22 inch
Basic Snow Shovel, 22 inches wide, straight handle with D-Grip
9.99
1 kg
2004-11-19
2004-12-19
7.25
See Also
* db2_execute() - Executes a prepared SQL statement
* db2_prepare() - Prepares an SQL statement to be executed
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_execute
(PECL ibm_db2 >= 1.0.0)
db2_execute - Executes a prepared SQL statement
Description
bool db2_execute ( resource $stmt [, array $parameters ] )
db2_execute() executes an SQL statement that was prepared by
db2_prepare().
If the SQL statement returns a result set, for example, a SELECT statement
or a CALL to a stored procedure that returns one or more result sets, you
can retrieve a row as an array from the stmt resource using
db2_fetch_assoc(), db2_fetch_both(), or db2_fetch_array(). Alternatively,
you can use db2_fetch_row() to move the result set pointer to the next row
and fetch a column at a time from that row with db2_result().
Refer to db2_prepare() for a brief discussion of the advantages of using
db2_prepare() and db2_execute() rather than db2_exec().
Parameters
stmt
A prepared statement returned from db2_prepare().
parameters
An array of input parameters matching any parameter markers
contained in the prepared statement.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Preparing and executing an SQL statement with parameter markers
The following example prepares an INSERT statement that accepts four
parameter markers, then iterates over an array of arrays containing the
input values to be passed to db2_execute().
The above example will output:
Successfully added new pet.
Example #2 Calling a stored procedure with an OUT parameter
The following example prepares a CALL statement that accepts one parameter
marker representing an OUT parameter, binds the PHP variable $my_pets to
the parameter using db2_bind_param(), then issues db2_execute() to execute
the CALL statement. After the CALL to the stored procedure has been made,
the value of $num_pets changes to reflect the value returned by the stored
procedure for that OUT parameter.
The above example will output:
I have 7 pets!
Example #3 Returning XML data as an SQL ResultSet
The following example demonstrates how to work with documents stored in a
XML column using the SAMPLE database. Using some pretty simple SQL/XML,
this example returns some of the nodes in a XML document in an SQL
ResultSet format that most users are familiar with.
CID $row->NAME $row->PHONE\n");
}
}
db2_close($conn);
?>
The above example will output:
1000 Kathy Smith 416-555-1358
1001 Kathy Smith 905-555-7258
Example #4 Performing a "JOIN" with XML data
The following example works with documents stored in 2 different XML
columns in the SAMPLE database. It creates 2 temporary tables from the XML
documents from 2 different columns and returns an SQL ResultSet with
information regarding shipping status for the customer.
CID $row->NAME $row->PHONE $row->PONUM $row->STATUS\n");
}
}
db2_close($conn);
?>
The above example will output:
1001 Kathy Smith 905-555-7258 5002 Shipped
Example #5 Returning SQL data as part of a larger XML document
The following example works with a portion of the PRODUCT.DESCRIPTION
documents in the SAMPLE database. It creates a XML document containing
product description (XML data) and pricing info (SQL data).
{
for $prod in $doc/product
where $prod/description/price < 10.00
order by $prod/description/price ascending
return(
{
$prod,
{$start} ,
{$end} ,
{$promo}
}
)
}
\' passing by ref DESCRIPTION AS "doc",
PROMOSTART as "start",
PROMOEND as "end",
PROMOPRICE as "promo"
RETURNING SEQUENCE)
AS CLOB (32000))
AS NEW_PRODUCT_INFO
FROM PRODUCT
WHERE PID = ?
';
$stmt = db2_prepare($conn, $query);
$pid = "100-100-01";
if ($stmt) {
db2_bind_param($stmt, 1, "pid", DB2_PARAM_IN);
db2_execute($stmt);
while($row = db2_fetch_array($stmt)){
printf("$row[0]\n");
}
}
db2_close($conn);
?>
The above example will output:
Snow Shovel, Basic 22 inch
Basic Snow Shovel, 22 inches wide, straight handle with D-Grip
9.99
1 kg
2004-11-19
2004-12-19
7.25
See Also
* db2_exec() - Executes an SQL statement directly
* db2_fetch_array() - Returns an array, indexed by column position,
representing a row in a result set
* db2_fetch_assoc() - Returns an array, indexed by column name,
representing a row in a result set
* db2_fetch_both() - Returns an array, indexed by both column name and
position, representing a row in a result set
* db2_fetch_row() - Sets the result set pointer to the next row or
requested row
* db2_prepare() - Prepares an SQL statement to be executed
* db2_result() - Returns a single column from a row in the result set
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_fetch_array
(PECL ibm_db2 >= 1.0.1)
db2_fetch_array - Returns an array, indexed by column position,
representing a row in a result set
Description
array db2_fetch_array ( resource $stmt [, int $row_number = -1 ] )
Returns an array, indexed by column position, representing a row in a
result set. The columns are 0-indexed.
Parameters
stmt
A valid stmt resource containing a result set.
row_number
Requests a specific 1-indexed row from the result set. Passing
this parameter results in a PHP warning if the result set uses a
forward-only cursor.
Return Values
Returns a 0-indexed array with column values indexed by the column
position representing the next or requested row in the result set. Returns
FALSE if there are no rows left in the result set, or if the row requested
by row_number does not exist in the result set.
Examples
Example #1 Iterating through a forward-only cursor
If you call db2_fetch_array() without a specific row number, it
automatically retrieves the next row in the result set.
The above example will output:
0 Pook cat 3.20
5 Rickety Ride goat 9.70
2 Smarty horse 350.00
Example #2 Retrieving specific rows with db2_fetch_array() from a
scrollable cursor
If your result set uses a scrollable cursor, you can call
db2_fetch_array() with a specific row number. The following example
retrieves every other row in the result set, starting with the second row.
DB2_SCROLLABLE));
$i=2;
while ($row = db2_fetch_array($result, $i)) {
printf ("%-5d %-16s %-32s %10s\n",
$row[0], $row[1], $row[2], $row[3]);
$i = $i + 2;
}
?>
The above example will output:
0 Pook cat 3.20
5 Rickety Ride goat 9.70
2 Smarty horse 350.00
See Also
* db2_fetch_assoc() - Returns an array, indexed by column name,
representing a row in a result set
* db2_fetch_both() - Returns an array, indexed by both column name and
position, representing a row in a result set
* db2_fetch_object() - Returns an object with properties representing
columns in the fetched row
* db2_fetch_row() - Sets the result set pointer to the next row or
requested row
* db2_result() - Returns a single column from a row in the result set
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_fetch_assoc
(PECL ibm_db2 >= 1.0.0)
db2_fetch_assoc - Returns an array, indexed by column name, representing a
row in a result set
Description
array db2_fetch_assoc ( resource $stmt [, int $row_number = -1 ] )
Returns an array, indexed by column name, representing a row in a result
set.
Parameters
stmt
A valid stmt resource containing a result set.
row_number
Requests a specific 1-indexed row from the result set. Passing
this parameter results in a PHP warning if the result set uses a
forward-only cursor.
Return Values
Returns an associative array with column values indexed by the column name
representing the next or requested row in the result set. Returns FALSE if
there are no rows left in the result set, or if the row requested by
row_number does not exist in the result set.
Examples
Example #1 Iterating through a forward-only cursor
If you call db2_fetch_assoc() without a specific row number, it
automatically retrieves the next row in the result set.
The above example will output:
0 Pook cat 3.20
5 Rickety Ride goat 9.70
2 Smarty horse 350.00
Example #2 Retrieving specific rows with db2_fetch_assoc() from a
scrollable cursor
If your result set uses a scrollable cursor, you can call
db2_fetch_assoc() with a specific row number. The following example
retrieves every other row in the result set, starting with the second row.
DB2_SCROLLABLE));
$i=2;
while ($row = db2_fetch_assoc($result, $i)) {
printf ("%-5d %-16s %-32s %10s\n",
$row['ID'], $row['NAME'], $row['BREED'], $row['WEIGHT']);
$i = $i + 2;
}
?>
The above example will output:
0 Pook cat 3.20
5 Rickety Ride goat 9.70
2 Smarty horse 350.00
See Also
* db2_fetch_array() - Returns an array, indexed by column position,
representing a row in a result set
* db2_fetch_both() - Returns an array, indexed by both column name and
position, representing a row in a result set
* db2_fetch_object() - Returns an object with properties representing
columns in the fetched row
* db2_fetch_row() - Sets the result set pointer to the next row or
requested row
* db2_result() - Returns a single column from a row in the result set
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_fetch_both
(PECL ibm_db2 >= 1.0.0)
db2_fetch_both - Returns an array, indexed by both column name and
position, representing a row in a result set
Description
array db2_fetch_both ( resource $stmt [, int $row_number = -1 ] )
Returns an array, indexed by both column name and position, representing a
row in a result set. Note that the row returned by db2_fetch_both()
requires more memory than the single-indexed arrays returned by
db2_fetch_assoc() or db2_fetch_array().
Parameters
stmt
A valid stmt resource containing a result set.
row_number
Requests a specific 1-indexed row from the result set. Passing
this parameter results in a PHP warning if the result set uses a
forward-only cursor.
Return Values
Returns an associative array with column values indexed by both the column
name and 0-indexed column number. The array represents the next or
requested row in the result set. Returns FALSE if there are no rows left
in the result set, or if the row requested by row_number does not exist in
the result set.
Examples
Example #1 Iterating through a forward-only cursor
If you call db2_fetch_both() without a specific row number, it
automatically retrieves the next row in the result set. The following
example accesses columns in the returned array by both column name and by
numeric index.
The above example will output:
0 Pook cat 3.20
5 Rickety Ride goat 9.70
2 Smarty horse 350.00
Example #2 Retrieving specific rows with db2_fetch_both() from a
scrollable cursor
If your result set uses a scrollable cursor, you can call db2_fetch_both()
with a specific row number. The following example retrieves every other
row in the result set, starting with the second row.
DB2_SCROLLABLE));
$i=2;
while ($row = db2_fetch_both($result, $i)) {
printf ("%-5d %-16s %-32s %10s\n",
$row[0], $row['NAME'], $row[2], $row['WEIGHT']);
$i = $i + 2;
}
?>
The above example will output:
0 Pook cat 3.20
5 Rickety Ride goat 9.70
2 Smarty horse 350.00
See Also
* db2_fetch_array() - Returns an array, indexed by column position,
representing a row in a result set
* db2_fetch_assoc() - Returns an array, indexed by column name,
representing a row in a result set
* db2_fetch_object() - Returns an object with properties representing
columns in the fetched row
* db2_fetch_row() - Sets the result set pointer to the next row or
requested row
* db2_result() - Returns a single column from a row in the result set
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_fetch_object
(PECL ibm_db2 >= 1.0.0)
db2_fetch_object - Returns an object with properties representing columns
in the fetched row
Description
object db2_fetch_object ( resource $stmt [, int $row_number = -1 ] )
Returns an object in which each property represents a column returned in
the row fetched from a result set.
Parameters
stmt
A valid stmt resource containing a result set.
row_number
Requests a specific 1-indexed row from the result set. Passing
this parameter results in a PHP warning if the result set uses a
forward-only cursor.
Return Values
Returns an object representing a single row in the result set. The
properties of the object map to the names of the columns in the result
set.
The IBM DB2, Cloudscape, and Apache Derby database servers typically fold
column names to upper-case, so the object properties will reflect that
case.
If your SELECT statement calls a scalar function to modify the value of a
column, the database servers return the column number as the name of the
column in the result set. If you prefer a more descriptive column name and
object property, you can use the AS clause to assign a name to the column
in the result set.
Returns FALSE if no row was retrieved.
Examples
Example #1 A db2_fetch_object() example
The following example issues a SELECT statement with a scalar function,
RTRIM, that removes whitespace from the end of the column. Rather than
creating an object with the properties "BREED" and "2", we use the AS
clause in the SELECT statement to assign the name "name" to the modified
column. The database server folds the column names to upper-case,
resulting in an object with the properties "BREED" and "NAME".
NAME}, my little {$pet->BREED}!";
}
db2_close($conn);
}
?>
The above example will output:
Come here, Pook, my little cat!
See Also
* db2_fetch_array() - Returns an array, indexed by column position,
representing a row in a result set
* db2_fetch_assoc() - Returns an array, indexed by column name,
representing a row in a result set
* db2_fetch_both() - Returns an array, indexed by both column name and
position, representing a row in a result set
* db2_fetch_row() - Sets the result set pointer to the next row or
requested row
* db2_result() - Returns a single column from a row in the result set
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_fetch_row
(PECL ibm_db2 >= 1.0.0)
db2_fetch_row - Sets the result set pointer to the next row or requested
row
Description
bool db2_fetch_row ( resource $stmt [, int $row_number ] )
Use db2_fetch_row() to iterate through a result set, or to point to a
specific row in a result set if you requested a scrollable cursor.
To retrieve individual fields from the result set, call the db2_result()
function.
Rather than calling db2_fetch_row() and db2_result(), most applications
will call one of db2_fetch_assoc(), db2_fetch_both(), or db2_fetch_array()
to advance the result set pointer and return a complete row as an array.
Parameters
stmt
A valid stmt resource.
row_number
With scrollable cursors, you can request a specific row number in
the result set. Row numbering is 1-indexed.
Return Values
Returns TRUE if the requested row exists in the result set. Returns FALSE
if the requested row does not exist in the result set.
Examples
Example #1 Iterating through a result set
The following example demonstrates how to iterate through a result set
with db2_fetch_row() and retrieve columns from the result set with
db2_result().
The above example will output:
cat Pook
gold fish Bubbles
budgerigar Gizmo
goat Rickety Ride
Example #2 i5/OS recommended alternatives to db2_fetch_row/db2_result
On i5/OS it is recommended that you use db2_fetch_both(),
db2_fetch_array(), or db2_fetch_object() over
db2_fetch_row()/db2_result(). In general db2_fetch_row()/db2_result() have
more issues with various column types in EBCIDIC to ASCII translation,
including possible truncation in DBCS applications. You may also find the
performance of db2_fetch_both(), db2_fetch_array(), and db2_fetch_object()
to be superior to db2_fetch_row()/db2_result().
DB2_SCROLLABLE));
while ($row = db2_fetch_both($stmt)){
echo " db2_fetch_both {$row['SPECIFIC_NAME']} {$row['ROUTINE_CREATED']} {$row[5]}";
}
$stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
while ($row = db2_fetch_array($stmt)){
echo " db2_fetch_array {$row[1]} {$row[5]}";
}
$stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
while ($row = db2_fetch_object($stmt)){
echo " db2_fetch_object {$row->SPECIFIC_NAME} {$row->ROUTINE_CREATED}";
}
db2_close($conn);
?>
The above example will output:
db2_fetch_both MATCH_ANIMAL 2006-08-25-17.10.23.775000 2006-08-25-17.10.23.775000
db2_fetch_both MULTIRESULTS 2006-10-17-10.11.05.308000 2006-10-17-10.11.05.308000
db2_fetch_array MATCH_ANIMAL 2006-08-25-17.10.23.775000
db2_fetch_array MULTIRESULTS 2006-10-17-10.11.05.308000
db2_fetch_object MATCH_ANIMAL 2006-08-25-17.10.23.775000
db2_fetch_object MULTIRESULTS 2006-10-17-10.11.05.308000
See Also
* db2_fetch_array() - Returns an array, indexed by column position,
representing a row in a result set
* db2_fetch_assoc() - Returns an array, indexed by column name,
representing a row in a result set
* db2_fetch_both() - Returns an array, indexed by both column name and
position, representing a row in a result set
* db2_fetch_object() - Returns an object with properties representing
columns in the fetched row
* db2_result() - Returns a single column from a row in the result set
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_field_display_size
(PECL ibm_db2 >= 1.0.0)
db2_field_display_size - Returns the maximum number of bytes required to
display a column
Description
int db2_field_display_size ( resource $stmt , mixed $column )
Returns the maximum number of bytes required to display a column in a
result set.
Parameters
stmt
Specifies a statement resource containing a result set.
column
Specifies the column in the result set. This can either be an
integer representing the 0-indexed position of the column, or a
string containing the name of the column.
Return Values
Returns an integer value with the maximum number of bytes required to
display the specified column. If the column does not exist in the result
set, db2_field_display_size() returns FALSE.
See Also
* db2_field_name() - Returns the name of the column in the result set
* db2_field_num() - Returns the position of the named column in a result
set
* db2_field_precision() - Returns the precision of the indicated column
in a result set
* db2_field_scale() - Returns the scale of the indicated column in a
result set
* db2_field_type() - Returns the data type of the indicated column in a
result set
* db2_field_width() - Returns the width of the current value of the
indicated column in a result set
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_field_name
(PECL ibm_db2 >= 1.0.0)
db2_field_name - Returns the name of the column in the result set
Description
string db2_field_name ( resource $stmt , mixed $column )
Returns the name of the specified column in the result set.
Parameters
stmt
Specifies a statement resource containing a result set.
column
Specifies the column in the result set. This can either be an
integer representing the 0-indexed position of the column, or a
string containing the name of the column.
Return Values
Returns a string containing the name of the specified column. If the
specified column does not exist in the result set, db2_field_name()
returns FALSE.
See Also
* db2_field_display_size() - Returns the maximum number of bytes
required to display a column
* db2_field_num() - Returns the position of the named column in a result
set
* db2_field_precision() - Returns the precision of the indicated column
in a result set
* db2_field_scale() - Returns the scale of the indicated column in a
result set
* db2_field_type() - Returns the data type of the indicated column in a
result set
* db2_field_width() - Returns the width of the current value of the
indicated column in a result set
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_field_num
(PECL ibm_db2 >= 1.0.0)
db2_field_num - Returns the position of the named column in a result set
Description
int db2_field_num ( resource $stmt , mixed $column )
Returns the position of the named column in a result set.
Parameters
stmt
Specifies a statement resource containing a result set.
column
Specifies the column in the result set. This can either be an
integer representing the 0-indexed position of the column, or a
string containing the name of the column.
Return Values
Returns an integer containing the 0-indexed position of the named column
in the result set. If the specified column does not exist in the result
set, db2_field_num() returns FALSE.
See Also
* db2_field_display_size() - Returns the maximum number of bytes
required to display a column
* db2_field_name() - Returns the name of the column in the result set
* db2_field_precision() - Returns the precision of the indicated column
in a result set
* db2_field_scale() - Returns the scale of the indicated column in a
result set
* db2_field_type() - Returns the data type of the indicated column in a
result set
* db2_field_width() - Returns the width of the current value of the
indicated column in a result set
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_field_precision
(PECL ibm_db2 >= 1.0.0)
db2_field_precision - Returns the precision of the indicated column in a
result set
Description
int db2_field_precision ( resource $stmt , mixed $column )
Returns the precision of the indicated column in a result set.
Parameters
stmt
Specifies a statement resource containing a result set.
column
Specifies the column in the result set. This can either be an
integer representing the 0-indexed position of the column, or a
string containing the name of the column.
Return Values
Returns an integer containing the precision of the specified column. If
the specified column does not exist in the result set,
db2_field_precision() returns FALSE.
See Also
* db2_field_display_size() - Returns the maximum number of bytes
required to display a column
* db2_field_name() - Returns the name of the column in the result set
* db2_field_num() - Returns the position of the named column in a result
set
* db2_field_scale() - Returns the scale of the indicated column in a
result set
* db2_field_type() - Returns the data type of the indicated column in a
result set
* db2_field_width() - Returns the width of the current value of the
indicated column in a result set
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_field_scale
(PECL ibm_db2 >= 1.0.0)
db2_field_scale - Returns the scale of the indicated column in a result
set
Description
int db2_field_scale ( resource $stmt , mixed $column )
Returns the scale of the indicated column in a result set.
Parameters
stmt
Specifies a statement resource containing a result set.
column
Specifies the column in the result set. This can either be an
integer representing the 0-indexed position of the column, or a
string containing the name of the column.
Return Values
Returns an integer containing the scale of the specified column. If the
specified column does not exist in the result set, db2_field_scale()
returns FALSE.
See Also
* db2_field_display_size() - Returns the maximum number of bytes
required to display a column
* db2_field_name() - Returns the name of the column in the result set
* db2_field_num() - Returns the position of the named column in a result
set
* db2_field_precision() - Returns the precision of the indicated column
in a result set
* db2_field_type() - Returns the data type of the indicated column in a
result set
* db2_field_width() - Returns the width of the current value of the
indicated column in a result set
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_field_type
(PECL ibm_db2 >= 1.0.0)
db2_field_type - Returns the data type of the indicated column in a result
set
Description
string db2_field_type ( resource $stmt , mixed $column )
Returns the data type of the indicated column in a result set.
Parameters
stmt
Specifies a statement resource containing a result set.
column
Specifies the column in the result set. This can either be an
integer representing the 0-indexed position of the column, or a
string containing the name of the column.
Return Values
Returns a string containing the defined data type of the specified column.
If the specified column does not exist in the result set, db2_field_type()
returns FALSE.
See Also
* db2_field_display_size() - Returns the maximum number of bytes
required to display a column
* db2_field_name() - Returns the name of the column in the result set
* db2_field_num() - Returns the position of the named column in a result
set
* db2_field_precision() - Returns the precision of the indicated column
in a result set
* db2_field_scale() - Returns the scale of the indicated column in a
result set
* db2_field_width() - Returns the width of the current value of the
indicated column in a result set
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_field_width
(PECL ibm_db2 >= 1.0.0)
db2_field_width - Returns the width of the current value of the indicated
column in a result set
Description
int db2_field_width ( resource $stmt , mixed $column )
Returns the width of the current value of the indicated column in a result
set. This is the maximum width of the column for a fixed-length data type,
or the actual width of the column for a variable-length data type.
Parameters
stmt
Specifies a statement resource containing a result set.
column
Specifies the column in the result set. This can either be an
integer representing the 0-indexed position of the column, or a
string containing the name of the column.
Return Values
Returns an integer containing the width of the specified character or
binary data type column in a result set. If the specified column does not
exist in the result set, db2_field_width() returns FALSE.
See Also
* db2_field_display_size() - Returns the maximum number of bytes
required to display a column
* db2_field_name() - Returns the name of the column in the result set
* db2_field_num() - Returns the position of the named column in a result
set
* db2_field_precision() - Returns the precision of the indicated column
in a result set
* db2_field_scale() - Returns the scale of the indicated column in a
result set
* db2_field_type() - Returns the data type of the indicated column in a
result set
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_foreign_keys
(PECL ibm_db2 >= 1.0.0)
db2_foreign_keys - Returns a result set listing the foreign keys for a
table
Description
resource db2_foreign_keys ( resource $connection , string $qualifier ,
string $schema , string $table-name )
Returns a result set listing the foreign keys for a table.
Parameters
connection
A valid connection to an IBM DB2, Cloudscape, or Apache Derby
database.
qualifier
A qualifier for DB2 databases running on OS/390 or z/OS servers.
For other databases, pass NULL or an empty string.
schema
The schema which contains the tables. If schema is NULL,
db2_foreign_keys() matches the schema for the current connection.
table-name
The name of the table.
Return Values
Returns a statement resource with a result set containing rows describing
the foreign keys for the specified table. The result set is composed of
the following columns:
Column name Description
PKTABLE_CAT Name of the catalog for the table containing the primary
key. The value is NULL if this table does not have catalogs.
PKTABLE_SCHEM Name of the schema for the table containing the primary key.
PKTABLE_NAME Name of the table containing the primary key.
PKCOLUMN_NAME Name of the column containing the primary key.
FKTABLE_CAT Name of the catalog for the table containing the foreign
key. The value is NULL if this table does not have catalogs.
FKTABLE_SCHEM Name of the schema for the table containing the foreign key.
FKTABLE_NAME Name of the table containing the foreign key.
FKCOLUMN_NAME Name of the column containing the foreign key.
KEY_SEQ 1-indexed position of the column in the key.
UPDATE_RULE Integer value representing the action applied to the foreign
key when the SQL operation is UPDATE.
DELETE_RULE Integer value representing the action applied to the foreign
key when the SQL operation is DELETE.
FK_NAME The name of the foreign key.
PK_NAME The name of the primary key.
An integer value representing whether the foreign key
DEFERRABILITY deferrability is SQL_INITIALLY_DEFERRED,
SQL_INITIALLY_IMMEDIATE, or SQL_NOT_DEFERRABLE.
See Also
* db2_column_privileges() - Returns a result set listing the columns and
associated privileges for a table
* db2_columns() - Returns a result set listing the columns and
associated metadata for a table
* db2_primary_keys() - Returns a result set listing primary keys for a
table
* db2_procedure_columns() - Returns a result set listing stored
procedure parameters
* db2_procedures() - Returns a result set listing the stored procedures
registered in a database
* db2_special_columns() - Returns a result set listing the unique row
identifier columns for a table
* db2_statistics() - Returns a result set listing the index and
statistics for a table
* db2_table_privileges() - Returns a result set listing the tables and
associated privileges in a database
* db2_tables() - Returns a result set listing the tables and associated
metadata in a database
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_free_result
(PECL ibm_db2 >= 1.0.0)
db2_free_result - Frees resources associated with a result set
Description
bool db2_free_result ( resource $stmt )
Frees the system and database resources that are associated with a result
set. These resources are freed implicitly when a script finishes, but you
can call db2_free_result() to explicitly free the result set resources
before the end of the script.
Parameters
stmt
A valid statement resource.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* db2_free_stmt() - Frees resources associated with the indicated
statement resource
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_free_stmt
(PECL ibm_db2 >= 1.0.0)
db2_free_stmt - Frees resources associated with the indicated statement
resource
Description
bool db2_free_stmt ( resource $stmt )
Frees the system and database resources that are associated with a
statement resource. These resources are freed implicitly when a script
finishes, but you can call db2_free_stmt() to explicitly free the
statement resources before the end of the script.
Parameters
stmt
A valid statement resource.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* db2_free_result() - Frees resources associated with a result set
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_get_option
(PECL ibm_db2 >= 1.6.0)
db2_get_option - Retrieves an option value for a statement resource or a
connection resource
Description
string db2_get_option ( resource $resource , string $option )
Retrieves the value of a specified option value for a statement resource
or a connection resource.
Parameters
resource
A valid statement resource as returned from db2_prepare() or a
valid connection resource as returned from db2_connect() or
db2_pconnect().
option
A valid statement or connection options. The following new options
are available as of ibm_db2 version 1.6.0. They provide useful
tracking information that can be set during execution with
db2_get_option().
Note:
Prior versions of ibm_db2 do not support these new options.
When the value in each option is being set, some servers might
not handle the entire length provided and might truncate the
value.
To ensure that the data specified in each option is converted
correctly when transmitted to a host system, use only the
characters A through Z, 0 through 9, and the underscore (_) or
period (.).
userid
SQL_ATTR_INFO_USERID - A pointer to a null-terminated
character string used to identify the client user ID
sent to the host database server when using DB2
Connect.
Note:
DB2 for z/OS and OS/390 servers support up to a
length of 16 characters. This user-id is not to be
confused with the authentication user-id, it is for
identification purposes only and is not used for
any authorization.
acctstr
SQL_ATTR_INFO_ACCTSTR - A pointer to a
null-terminated character string used to identify the
client accounting string sent to the host database
server when using DB2 Connect.
Note:
DB2 for z/OS and OS/390 servers support up to a
length of 200 characters.
applname
SQL_ATTR_INFO_APPLNAME - A pointer to a
null-terminated character string used to identify the
client application name sent to the host database
server when using DB2 Connect.
Note:
DB2 for z/OS and OS/390 servers support up to a
length of 32 characters.
wrkstnname
SQL_ATTR_INFO_WRKSTNNAME - A pointer to a
null-terminated character string used to identify the
client workstation name sent to the host database
server when using DB2 Connect.
Note:
DB2 for z/OS and OS/390 servers support up to a
length of 18 characters.
The following table specifies which options are compatible with the
available resource types:
Resource-Parameter Matrix
Key Value Resource Type
Connection Statement Result Set
userid SQL_ATTR_INFO_USERID X X -
acctstr SQL_ATTR_INFO_ACCTSTR X X -
applname SQL_ATTR_INFO_APPLNAME X X -
wrkstnname SQL_ATTR_INFO_WRKSTNNAME X X -
Return Values
Returns the current setting of the connection attribute provided on
success or FALSE on failure.
Examples
Example #1 Setting and retrieving parameters through a connection resource
'db2inst1');
$conn1 = db2_connect($database, $user, $password, $options1);
$val = db2_get_option($conn1, 'userid');
echo $val . "\n";
$options2 = array('acctstr' => 'account');
$conn2 = db2_connect($database, $user, $password, $options2);
$val = db2_get_option($conn2, 'acctstr');
echo $val . "\n";
$options3 = array('applname' => 'myapp');
$conn3 = db2_connect($database, $user, $password, $options3);
$val = db2_get_option($conn3, 'applname');
echo $val . "\n";
$options4 = array('wrkstnname' => 'workstation');
$conn4 = db2_connect($database, $user, $password, $options4);
$val = db2_get_option($conn4, 'wrkstnname');
echo $val . "\n";
echo "Client attributes passed post-connection:\n";
/* Create the associative options array with valid key-value pairs */
/* Assign the attributes after a connection is made */
/* Access the options specified */
$options5 = array('userid' => 'db2inst1');
$conn5 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn5, $options5, 1);
$val = db2_get_option($conn5, 'userid');
echo $val . "\n";
$options6 = array('acctstr' => 'account');
$conn6 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn6, $options6, 1);
$val = db2_get_option($conn6, 'acctstr');
echo $val . "\n";
$options7 = array('applname' => 'myapp');
$conn7 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn7, $options7, 1);
$val = db2_get_option($conn7, 'applname');
echo $val . "\n";
$options8 = array('wrkstnname' => 'workstation');
$conn8 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn8, $options8, 1);
$val = db2_get_option($conn8, 'wrkstnname');
echo $val . "\n";
?>
The above example will output:
Client attributes passed through connection string:
db2inst1
account
myapp
workstation
Client attributes passed post-connection:
db2inst1
account
myapp
workstation
See Also
* db2_connect() - Returns a connection to a database
* db2_cursor_type() - Returns the cursor type used by a statement
resource
* db2_exec() - Executes an SQL statement directly
* db2_set_option() - Set options for connection or statement resources
* db2_pconnect() - Returns a persistent connection to a database
* db2_prepare() - Prepares an SQL statement to be executed
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_last_insert_id
(PECL ibm_db2 >= 1.7.1)
db2_last_insert_id - Returns the auto generated ID of the last insert
query that successfully executed on this connection
Description
string db2_last_insert_id ( resource $resource )
Returns the auto generated ID of the last insert query that successfully
executed on this connection.
The result of this function is not affected by any of the following:
* A single row INSERT statement with a VALUES clause for a table without
an identity column.
* A multiple row INSERT statement with a VALUES clause.
* An INSERT statement with a fullselect.
* A ROLLBACK TO SAVEPOINT statement.
Parameters
resource
A valid connection resource as returned from db2_connect() or
db2_pconnect(). The value of this parameter cannot be a statement
resource or result set resource.
Return Values
Returns the auto generated ID of last insert query that successfully
executed on this connection.
Examples
Example #1 A db2_last_insert_id() example
The following example shows how to return the auto generated ID of last
insert query that successfully executed on this connection.
The above example will output:
Last Insert ID is : 1
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_lob_read
(PECL ibm_db2 >= 1.6.0)
db2_lob_read - Gets a user defined size of LOB files with each invocation
Description
string db2_lob_read ( resource $stmt , int $colnum , int $length )
Use db2_lob_read() to iterate through a specified column of a result set
and retrieve a user defined size of LOB data.
Parameters
stmt
A valid stmt resource containing LOB data.
colnum
A valid column number in the result set of the stmt resource.
length
The size of the LOB data to be retrieved from the stmt resource.
Return Values
Returns the amount of data the user specifies. Returns FALSE if the data
cannot be retrieved.
Examples
Example #1 Iterating through different types of data
The above example will output:
Loop 0: THIS I
Loop 1: S A CL
Loop 2: OB TES
Loop 3: T. THI
Loop 4: S IS A
Loop 5: CLOB
Loop 6: TEST.
Loop 0: THIS I
Loop 1: S A BL
Loop 2: OB TES
Loop 3: T. THI
Loop 4: S IS A
Loop 5: BLOB
Loop 6: TEST.
See Also
* db2_bind_param() - Binds a PHP variable to an SQL statement parameter
* db2_exec() - Executes an SQL statement directly
* db2_execute() - Executes a prepared SQL statement
* db2_fetch_row() - Sets the result set pointer to the next row or
requested row
* db2_prepare() - Prepares an SQL statement to be executed
* db2_result() - Returns a single column from a row in the result set
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_next_result
(PECL ibm_db2 >= 1.0.0)
db2_next_result - Requests the next result set from a stored procedure
Description
resource db2_next_result ( resource $stmt )
A stored procedure can return zero or more result sets. While you handle
the first result set in exactly the same way you would handle the results
returned by a simple SELECT statement, to fetch the second and subsequent
result sets from a stored procedure you must call the db2_next_result()
function and return the result to a uniquely named PHP variable.
Parameters
stmt
A prepared statement returned from db2_exec() or db2_execute().
Return Values
Returns a new statement resource containing the next result set if the
stored procedure returned another result set. Returns FALSE if the stored
procedure did not return another result set.
Examples
Example #1 Calling a stored procedure that returns multiple result sets
In the following example, we call a stored procedure that returns three
result sets. The first result set is fetched directly from the same
statement resource on which we invoked the CALL statement, while the
second and third result sets are fetched from statement resources returned
from our calls to the db2_next_result() function.
The above example will output:
Fetching first result set
array(2) {
[0]=>
string(16) "Bubbles "
[1]=>
int(3)
}
array(2) {
[0]=>
string(16) "Gizmo "
[1]=>
int(4)
}
Fetching second result set
array(4) {
[0]=>
string(16) "Sweater "
[1]=>
int(6)
[2]=>
string(5) "llama"
[3]=>
string(6) "150.00"
}
array(4) {
[0]=>
string(16) "Smarty "
[1]=>
int(2)
[2]=>
string(5) "horse"
[3]=>
string(6) "350.00"
}
Fetching third result set
array(1) {
[0]=>
string(16) "Bubbles "
}
array(1) {
[0]=>
string(16) "Gizmo "
}
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_num_fields
(PECL ibm_db2 >= 1.0.0)
db2_num_fields - Returns the number of fields contained in a result set
Description
int db2_num_fields ( resource $stmt )
Returns the number of fields contained in a result set. This is most
useful for handling the result sets returned by dynamically generated
queries, or for result sets returned by stored procedures, where your
application cannot otherwise know how to retrieve and use the results.
Parameters
stmt
A valid statement resource containing a result set.
Return Values
Returns an integer value representing the number of fields in the result
set associated with the specified statement resource. Returns FALSE if the
statement resource is not a valid input value.
Examples
Example #1 Retrieving the number of fields in a result set
The following example demonstrates how to retrieve the number of fields
returned in a result set.
The above example will output:
There are 4 columns in the result set.
See Also
* db2_execute() - Executes a prepared SQL statement
* db2_field_display_size() - Returns the maximum number of bytes
required to display a column
* db2_field_name() - Returns the name of the column in the result set
* db2_field_num() - Returns the position of the named column in a result
set
* db2_field_precision() - Returns the precision of the indicated column
in a result set
* db2_field_scale() - Returns the scale of the indicated column in a
result set
* db2_field_type() - Returns the data type of the indicated column in a
result set
* db2_field_width() - Returns the width of the current value of the
indicated column in a result set
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_num_rows
(PECL ibm_db2 >= 1.0.0)
db2_num_rows - Returns the number of rows affected by an SQL statement
Description
int db2_num_rows ( resource $stmt )
Returns the number of rows deleted, inserted, or updated by an SQL
statement.
To determine the number of rows that will be returned by a SELECT
statement, issue SELECT COUNT(*) with the same predicates as your intended
SELECT statement and retrieve the value.
If your application logic checks the number of rows returned by a SELECT
statement and branches if the number of rows is 0, consider modifying your
application to attempt to return the first row with one of
db2_fetch_assoc(), db2_fetch_both(), db2_fetch_array(), or
db2_fetch_row(), and branch if the fetch function returns FALSE.
Note:
If you issue a SELECT statement using a scrollable cursor,
db2_num_rows() returns the number of rows returned by the SELECT
statement. However, the overhead associated with scrollable cursors
significantly degrades the performance of your application, so if this
is the only reason you are considering using scrollable cursors, you
should use a forward-only cursor and either call SELECT COUNT(*) or rely
on the boolean return value of the fetch functions to achieve the
equivalent functionality with much better performance.
Parameters
stmt
A valid stmt resource containing a result set.
Return Values
Returns the number of rows affected by the last SQL statement issued by
the specified statement handle.
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_pclose
(PECL ibm_db2 >= 1.8.0)
db2_pclose - Closes a persistent database connection
Description
bool db2_pclose ( resource $resource )
This function closes a DB2 client connection created with db2_pconnect()
and returns the corresponding resources to the database server.
Note:
This function is only available on i5/OS in response to i5/OS system
administration requests.
If you have a persistent DB2 client connection created with
db2_pconnect(), you may use this function to close the connection. To
avoid substantial connection performance penalties, this function should
only be used in rare cases when the persistent connection has become
unresponsive or the persistent connection will not be needed for a long
period of time.
Parameters
connection
Specifies an active DB2 client connection.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Closing a persistent connection
The following example demonstrates a successful attempt to close a
connection to an IBM DB2 i5/OS database.
The above example will output:
Connection was successfully closed.
See Also
* db2_close() - Closes a database connection
* db2_pconnect() - Returns a persistent connection to a database
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_pconnect
(PECL ibm_db2 >= 1.0.0)
db2_pconnect - Returns a persistent connection to a database
Description
resource db2_pconnect ( string $database , string $username , string
$password [, array $options ] )
Returns a persistent connection to an IBM DB2 Universal Database, IBM
Cloudscape, or Apache Derby database.
For more information on persistent connections, refer to Persistent
Database Connections.
Calling db2_close() on a persistent connection always returns TRUE, but
the underlying DB2 client connection remains open and waiting to serve the
next matching db2_pconnect() request.
Users running version 1.9.0 or later of ibm_db2 should be aware that the
extension will perform a transaction rollback on persistent connections at
the end of a request, thus ending the transaction. This prevents the
transaction block from carrying over to the next request which uses that
connection if script execution ends before the transaction block does.
Parameters
database
The database alias in the DB2 client catalog.
username
The username with which you are connecting to the database.
password
The password with which you are connecting to the database.
options
An associative array of connection options that affect the
behavior of the connection, where valid array keys include:
autocommit
Passing the DB2_AUTOCOMMIT_ON value turns autocommit
on for this connection handle.
Passing the DB2_AUTOCOMMIT_OFF value turns autocommit
off for this connection handle.
DB2_ATTR_CASE
Passing the DB2_CASE_NATURAL value specifies that
column names are returned in natural case.
Passing the DB2_CASE_LOWER value specifies that
column names are returned in lower case.
Passing the DB2_CASE_UPPER value specifies that
column names are returned in upper case.
CURSOR
Passing the DB2_FORWARD_ONLY value specifies a
forward-only cursor for a statement resource. This is
the default cursor type and is supported on all
database servers.
Passing the DB2_SCROLLABLE value specifies a
scrollable cursor for a statement resource. This mode
enables random access to rows in a result set, but
currently is supported only by IBM DB2 Universal
Database.
The following new option is available in ibm_db2 version 1.7.0 and
later.
trustedcontext
Passing the DB2_TRUSTED_CONTEXT_ENABLE value turns
trusted context on for this connection handle. This
parameter cannot be set using db2_set_option().
This key works only if the database is cataloged
(even if the database is local), or if you specify
the full DSN when you create the connection.
To catalog the database, use following commands:
db2 catalog tcpip node loopback remote server
db2 catalog database as at node loopback
db2 "update dbm cfg using svcename "
db2set DB2COMM=TCPIP
The following new i5/OS options are available in ibm_db2 version
1.5.1 and later.
Tip
Conflicting connection attributes used in conjunction with
persistent connections can produce indeterminate results on i5/OS.
Site policies should be establish for all applications using each
persistent connection user profile. The default DB2_AUTOCOMMIT_ON
is suggested when using persistent connections.
i5_lib
A character value that indicates the default library
that will be used for resolving unqualified file
references. This is not valid if the connection is
using system naming mode.
i5_naming
DB2_I5_NAMING_ON value turns on DB2 UDB CLI iSeries
system naming mode. Files are qualified using the
slash (/) delimiter. Unqualified files are resolved
using the library list for the job.
DB2_I5_NAMING_OFF value turns off DB2 UDB CLI default
naming mode, which is SQL naming. Files are qualified
using the period (.) delimiter. Unqualified files are
resolved using either the default library or the
current user ID.
i5_commit
The i5_commit attribute should be set before the
db2_pconnect(). If the value is changed after the
connection has been established, and the connection
is to a remote data source, the change does not take
effect until the next successful db2_pconnect() for
the connection handle.
Note:
The php.ini setting ibm_db2.i5_allow_commit==0 or
DB2_I5_TXN_NO_COMMIT is the default, but may be
overridden with the i5_commit option.
DB2_I5_TXN_NO_COMMIT - Commitment control is not
used.
DB2_I5_TXN_READ_UNCOMMITTED - Dirty reads,
nonrepeatable reads, and phantoms are possible.
DB2_I5_TXN_READ_COMMITTED - Dirty reads are not
possible. Nonrepeatable reads, and phantoms are
possible.
DB2_I5_TXN_REPEATABLE_READ - Dirty reads and
nonrepeatable reads are not possible. Phantoms are
possible.
DB2_I5_TXN_SERIALIZABLE - Transactions are
serializable. Dirty reads, non-repeatable reads, and
phantoms are not possible
i5_query_optimize
DB2_FIRST_IO All queries are optimized with the goal
of returning the first page of output as fast as
possible. This goal works well when the output is
controlled by a user who is most likely to cancel the
query after viewing the first page of output data.
Queries coded with an OPTIMIZE FOR nnn ROWS clause
honor the goal specified by the clause.
DB2_ALL_IO All queries are optimized with the goal of
running the entire query to completion in the
shortest amount of elapsed time. This is a good
option when the output of a query is being written to
a file or report, or the interface is queuing the
output data. Queries coded with an OPTIMIZE FOR nnn
ROWS clause honor the goal specified by the clause.
This is the default.
i5_dbcs_alloc
DB2_I5_DBCS_ALLOC_ON value turns on DB2 6X allocation
scheme for DBCS translation column size growth.
DB2_I5_DBCS_ALLOC_OFF value turns off DB2 6X
allocation scheme for DBCS translation column size
growth.
Note:
The php.ini setting ibm_db2.i5_dbcs_alloc==0 or
DB2_I5_DBCS_ALLOC_OFF is the default, but may be
overridden with the i5_dbcs_alloc option.
i5_date_fmt
DB2_I5_FMT_ISO - The International Organization for
Standardization (ISO) date format yyyy-mm-dd is used.
This is the default.
DB2_I5_FMT_USA - The United States date format
mm/dd/yyyy is used.
DB2_I5_FMT_EUR - The European date format dd.mm.yyyy
is used.
DB2_I5_FMT_JIS - The Japanese Industrial Standard
date format yyyy-mm-dd is used.
DB2_I5_FMT_MDY - The date format mm/dd/yyyy is used.
DB2_I5_FMT_DMY - The date format dd/mm/yyyy is used.
DB2_I5_FMT_YMD - The date format yy/mm/dd is used.
DB2_I5_FMT_JUL - The Julian date format yy/ddd is
used.
DB2_I5_FMT_JOB - The job default is used.
i5_date_sep
DB2_I5_SEP_SLASH - A slash ( / ) is used as the date
separator. This is the default.
DB2_I5_SEP_DASH - A dash ( - ) is used as the date
separator.
DB2_I5_SEP_PERIOD - A period ( . ) is used as the
date separator.
DB2_I5_SEP_COMMA - A comma ( , ) is used as the date
separator.
DB2_I5_SEP_BLANK - A blank is used as the date
separator.
DB2_I5_SEP_JOB - The job default is used
i5_time_fmt
DB2_I5_FMT_ISO - The International Organization for
Standardization (ISO) time format hh.mm.ss is used.
This is the default.
DB2_I5_FMT_USA - The United States time format
hh:mmxx is used, where xx is AM or PM.
DB2_I5_FMT_EUR - The European time format hh.mm.ss is
used.
DB2_I5_FMT_JIS - The Japanese Industrial Standard
time format hh:mm:ss is used.
DB2_I5_FMT_HMS - The hh:mm:ss format is used.
i5_time_sep
DB2_I5_SEP_COLON - A colon ( : ) is used as the time
separator. This is the default.
DB2_I5_SEP_PERIOD - A period ( . ) is used as the
time separator.
DB2_I5_SEP_COMMA - A comma ( , ) is used as the time
separator.
DB2_I5_SEP_BLANK - A blank is used as the time
separator.
DB2_I5_SEP_JOB - The job default is used.
i5_decimal_sep
DB2_I5_SEP_PERIOD - A period ( . ) is used as the
decimal separator. This is the default.
DB2_I5_SEP_COMMA - A comma ( , ) is used as the
decimal separator.
DB2_I5_SEP_JOB - The job default is used.
The following new i5/OS option is available in ibm_db2 version
1.8.0 and later.
i5_libl
A character value that indicates the library list
that will be used for resolving unqualified file
references. Specify the library list elements
separated by blanks 'i5_libl'=>"MYLIB YOURLIB
ANYLIB".
Note:
i5_libl calls qsys2/qcmdexc('cmd',cmdlen), which is
only available in i5/OS V5R4 and later.
Return Values
Returns a connection handle resource if the connection attempt is
successful. db2_pconnect() tries to reuse an existing connection resource
that exactly matches the database, username, and password parameters. If
the connection attempt fails, db2_pconnect() returns FALSE.
Changelog
Version Description
ibm_db2 1.9.0 Active transactions within a persistent connection will be
rolled back at the end of each request.
ibm_db2 1.8.0 The i5_libl option is available for i5/OS users.
ibm_db2 1.7.0 The trustedcontext option is available.
The i5_lib, i5_naming, i5_commit, i5_query_optimize,
ibm_db2 1.5.1 i5_dbcs_alloc, i5_date_fmt, i5_date_sep, i5_time_fmt,
i5_time_sep and i5_decimal_sep options are available for
i5/OS users.
Examples
Example #1 A db2_pconnect() example
In the following example, the first call to db2_pconnect() returns a new
persistent connection resource. The second call to db2_pconnect() returns
a persistent connection resource that simply reuses the first persistent
connection resource.
The above example will output:
Persistent connection succeeded.
Second persistent connection succeeded.
Example #2 Using trusted context
The following example shows how to enable trusted context, switch users,
and get the current user ID.
DB2_TRUSTED_CONTEXT_ENABLE);
$tc_conn = db2_pconnect($dsn, "", "", $options);
if($tc_conn) {
echo "Explicit trusted connection succeeded.\n";
if(db2_get_option($tc_conn, "trustedcontext")) {
$userBefore = db2_get_option($tc_conn, "trusted_user");
//Do some work as user 1.
//Switching to trusted user.
$parameters = array("trusted_user" => $tc_user,
"trusted_password" => $tcuser_pass);
$res = db2_set_option ($tc_conn, $parameters, 1);
$userAfter = db2_get_option($tc_conn, "trusted_user");
//Do more work as trusted user.
if($userBefore != $userAfter) {
echo "User has been switched." . "\n";
}
}
db2_close($tc_conn);
}
else {
echo "Explicit trusted connection failed.\n";
}
?>
The above example will output:
Explicit trusted connection succeeded.
User has been switched.
See Also
* db2_connect() - Returns a connection to a database
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_prepare
(PECL ibm_db2 >= 1.0.0)
db2_prepare - Prepares an SQL statement to be executed
Description
resource db2_prepare ( resource $connection , string $statement [, array
$options ] )
db2_prepare() creates a prepared SQL statement which can include 0 or more
parameter markers (? characters) representing parameters for input,
output, or input/output. You can pass parameters to the prepared statement
using db2_bind_param(), or for input values only, as an array passed to
db2_execute().
There are three main advantages to using prepared statements in your
application:
* Performance: when you prepare a statement, the database server creates
an optimized access plan for retrieving data with that statement.
Subsequently issuing the prepared statement with db2_execute() enables
the statements to reuse that access plan and avoids the overhead of
dynamically creating a new access plan for every statement you issue.
* Security: when you prepare a statement, you can include parameter
markers for input values. When you execute a prepared statement with
input values for placeholders, the database server checks each input
value to ensure that the type matches the column definition or
parameter definition.
* Advanced functionality: Parameter markers not only enable you to pass
input values to prepared SQL statements, they also enable you to
retrieve OUT and INOUT parameters from stored procedures using
db2_bind_param().
Parameters
connection
A valid database connection resource variable as returned from
db2_connect() or db2_pconnect().
statement
An SQL statement, optionally containing one or more parameter
markers..
options
An associative array containing statement options. You can use
this parameter to request a scrollable cursor on database servers
that support this functionality.
For a description of valid statement options, see
db2_set_option().
Return Values
Returns a statement resource if the SQL statement was successfully parsed
and prepared by the database server. Returns FALSE if the database server
returned an error. You can determine which error was returned by calling
db2_stmt_error() or db2_stmt_errormsg().
Examples
Example #1 Preparing and executing an SQL statement with parameter markers
The following example prepares an INSERT statement that accepts four
parameter markers, then iterates over an array of arrays containing the
input values to be passed to db2_execute().
See Also
* db2_bind_param() - Binds a PHP variable to an SQL statement parameter
* db2_execute() - Executes a prepared SQL statement
* db2_stmt_error() - Returns a string containing the SQLSTATE returned
by an SQL statement
* db2_stmt_errormsg() - Returns a string containing the last SQL
statement error message
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_primary_keys
(PECL ibm_db2 >= 1.0.0)
db2_primary_keys - Returns a result set listing primary keys for a table
Description
resource db2_primary_keys ( resource $connection , string $qualifier ,
string $schema , string $table-name )
Returns a result set listing the primary keys for a table.
Parameters
connection
A valid connection to an IBM DB2, Cloudscape, or Apache Derby
database.
qualifier
A qualifier for DB2 databases running on OS/390 or z/OS servers.
For other databases, pass NULL or an empty string.
schema
The schema which contains the tables. If schema is NULL,
db2_primary_keys() matches the schema for the current connection.
table-name
The name of the table.
Return Values
Returns a statement resource with a result set containing rows describing
the primary keys for the specified table. The result set is composed of
the following columns:
Column name Description
TABLE_CAT Name of the catalog for the table containing the primary key.
The value is NULL if this table does not have catalogs.
TABLE_SCHEM Name of the schema for the table containing the primary key.
TABLE_NAME Name of the table containing the primary key.
COLUMN_NAME Name of the column containing the primary key.
KEY_SEQ 1-indexed position of the column in the key.
PK_NAME The name of the primary key.
See Also
* db2_column_privileges() - Returns a result set listing the columns and
associated privileges for a table
* db2_columns() - Returns a result set listing the columns and
associated metadata for a table
* db2_foreign_keys() - Returns a result set listing the foreign keys for
a table
* db2_procedure_columns() - Returns a result set listing stored
procedure parameters
* db2_procedures() - Returns a result set listing the stored procedures
registered in a database
* db2_special_columns() - Returns a result set listing the unique row
identifier columns for a table
* db2_statistics() - Returns a result set listing the index and
statistics for a table
* db2_table_privileges() - Returns a result set listing the tables and
associated privileges in a database
* db2_tables() - Returns a result set listing the tables and associated
metadata in a database
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_procedure_columns
(PECL ibm_db2 >= 1.0.0)
db2_procedure_columns - Returns a result set listing stored procedure
parameters
Description
resource db2_procedure_columns ( resource $connection , string $qualifier
, string $schema , string $procedure , string $parameter )
Returns a result set listing the parameters for one or more stored
procedures.
Parameters
connection
A valid connection to an IBM DB2, Cloudscape, or Apache Derby
database.
qualifier
A qualifier for DB2 databases running on OS/390 or z/OS servers.
For other databases, pass NULL or an empty string.
schema
The schema which contains the procedures. This parameter accepts a
search pattern containing _ and % as wildcards.
procedure
The name of the procedure. This parameter accepts a search pattern
containing _ and % as wildcards.
parameter
The name of the parameter. This parameter accepts a search pattern
containing _ and % as wildcards. If this parameter is NULL, all
parameters for the specified stored procedures are returned.
Return Values
Returns a statement resource with a result set containing rows describing
the parameters for the stored procedures matching the specified
parameters. The rows are composed of the following columns:
Column name Description
PROCEDURE_CAT The catalog that contains the procedure. The value is
NULL if this table does not have catalogs.
PROCEDURE_SCHEM Name of the schema that contains the stored procedure.
PROCEDURE_NAME Name of the procedure.
COLUMN_NAME Name of the parameter.
An integer value representing the type of the parameter:
Return value Parameter type
COLUMN_TYPE 1 (SQL_PARAM_INPUT) Input (IN) parameter.
2 (SQL_PARAM_INPUT_OUTPUT) Input/output (INOUT)
parameter.
3 (SQL_PARAM_OUTPUT) Output (OUT) parameter.
DATA_TYPE The SQL data type for the parameter represented as an
integer value.
TYPE_NAME A string representing the data type for the parameter.
COLUMN_SIZE An integer value representing the size of the parameter.
BUFFER_LENGTH Maximum number of bytes necessary to store data for this
parameter.
DECIMAL_DIGITS The scale of the parameter, or NULL where scale is not
applicable.
An integer value of either 10 (representing an exact
NUM_PREC_RADIX numeric data type), 2 (representing an approximate
numeric data type), or NULL (representing a data type
for which radix is not applicable).
NULLABLE An integer value representing whether the parameter is
nullable or not.
REMARKS Description of the parameter.
COLUMN_DEF Default value for the parameter.
SQL_DATA_TYPE An integer value representing the size of the parameter.
Returns an integer value representing a datetime subtype
SQL_DATETIME_SUB code, or NULL for SQL data types to which this does not
apply.
Maximum length in octets for a character data type
CHAR_OCTET_LENGTH parameter, which matches COLUMN_SIZE for single-byte
character set data, or NULL for non-character data
types.
ORDINAL_POSITION The 1-indexed position of the parameter in the CALL
statement.
A string value where 'YES' means that the parameter
IS_NULLABLE accepts or returns NULL values and 'NO' means that the
parameter does not accept or return NULL values.
See Also
* db2_column_privileges() - Returns a result set listing the columns and
associated privileges for a table
* db2_columns() - Returns a result set listing the columns and
associated metadata for a table
* db2_foreign_keys() - Returns a result set listing the foreign keys for
a table
* db2_primary_keys() - Returns a result set listing primary keys for a
table
* db2_procedures() - Returns a result set listing the stored procedures
registered in a database
* db2_special_columns() - Returns a result set listing the unique row
identifier columns for a table
* db2_statistics() - Returns a result set listing the index and
statistics for a table
* db2_table_privileges() - Returns a result set listing the tables and
associated privileges in a database
* db2_tables() - Returns a result set listing the tables and associated
metadata in a database
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_procedures
(PECL ibm_db2 >= 1.0.0)
db2_procedures - Returns a result set listing the stored procedures
registered in a database
Description
resource db2_procedures ( resource $connection , string $qualifier ,
string $schema , string $procedure )
Returns a result set listing the stored procedures registered in a
database.
Parameters
connection
A valid connection to an IBM DB2, Cloudscape, or Apache Derby
database.
qualifier
A qualifier for DB2 databases running on OS/390 or z/OS servers.
For other databases, pass NULL or an empty string.
schema
The schema which contains the procedures. This parameter accepts a
search pattern containing _ and % as wildcards.
procedure
The name of the procedure. This parameter accepts a search pattern
containing _ and % as wildcards.
Return Values
Returns a statement resource with a result set containing rows describing
the stored procedures matching the specified parameters. The rows are
composed of the following columns:
Column name Description
PROCEDURE_CAT The catalog that contains the procedure. The value is
NULL if this table does not have catalogs.
PROCEDURE_SCHEM Name of the schema that contains the stored procedure.
PROCEDURE_NAME Name of the procedure.
NUM_INPUT_PARAMS Number of input (IN) parameters for the stored
procedure.
NUM_OUTPUT_PARAMS Number of output (OUT) parameters for the stored
procedure.
NUM_RESULT_SETS Number of result sets returned by the stored procedure.
REMARKS Any comments about the stored procedure.
PROCEDURE_TYPE Always returns 1, indicating that the stored procedure
does not return a return value.
See Also
* db2_column_privileges() - Returns a result set listing the columns and
associated privileges for a table
* db2_columns() - Returns a result set listing the columns and
associated metadata for a table
* db2_foreign_keys() - Returns a result set listing the foreign keys for
a table
* db2_primary_keys() - Returns a result set listing primary keys for a
table
* db2_procedure_columns() - Returns a result set listing stored
procedure parameters
* db2_special_columns() - Returns a result set listing the unique row
identifier columns for a table
* db2_statistics() - Returns a result set listing the index and
statistics for a table
* db2_table_privileges() - Returns a result set listing the tables and
associated privileges in a database
* db2_tables() - Returns a result set listing the tables and associated
metadata in a database
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_result
(PECL ibm_db2 >= 1.0.0)
db2_result - Returns a single column from a row in the result set
Description
mixed db2_result ( resource $stmt , mixed $column )
Use db2_result() to return the value of a specified column in the current
row of a result set. You must call db2_fetch_row() before calling
db2_result() to set the location of the result set pointer.
Parameters
stmt
A valid stmt resource.
column
Either an integer mapping to the 0-indexed field in the result
set, or a string matching the name of the column.
Return Values
Returns the value of the requested field if the field exists in the result
set. Returns NULL if the field does not exist, and issues a warning.
Examples
Example #1 A db2_result() example
The following example demonstrates how to iterate through a result set
with db2_fetch_row() and retrieve columns from the result set with
db2_result().
The above example will output:
cat Pook
gold fish Bubbles
budgerigar Gizmo
goat Rickety Ride
See Also
* db2_fetch_array() - Returns an array, indexed by column position,
representing a row in a result set
* db2_fetch_assoc() - Returns an array, indexed by column name,
representing a row in a result set
* db2_fetch_both() - Returns an array, indexed by both column name and
position, representing a row in a result set
* db2_fetch_object() - Returns an object with properties representing
columns in the fetched row
* db2_fetch_row() - Sets the result set pointer to the next row or
requested row
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_rollback
(PECL ibm_db2 >= 1.0.0)
db2_rollback - Rolls back a transaction
Description
bool db2_rollback ( resource $connection )
Rolls back an in-progress transaction on the specified connection resource
and begins a new transaction. PHP applications normally default to
AUTOCOMMIT mode, so db2_rollback() normally has no effect unless
AUTOCOMMIT has been turned off for the connection resource.
Parameters
connection
A valid database connection resource variable as returned from
db2_connect() or db2_pconnect().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Rolling back a DELETE statement
In the following example, we count the number of rows in a table, turn off
AUTOCOMMIT mode on a database connection, delete all of the rows in the
table and return the count of 0 to prove that the rows have been removed.
We then issue db2_rollback() and return the updated count of rows in the
table to show that the number is the same as before we issued the DELETE
statement. The return to the original state of the table demonstrates that
the roll back of the transaction succeeded.
The above example will output:
7
0
7
See Also
* db2_autocommit() - Returns or sets the AUTOCOMMIT state for a database
connection
* db2_commit() - Commits a transaction
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_server_info
(PECL ibm_db2 >= 1.1.1)
db2_server_info - Returns an object with properties that describe the DB2
database server
Description
object db2_server_info ( resource $connection )
This function returns an object with read-only properties that return
information about the IBM DB2, Cloudscape, or Apache Derby database
server. The following table lists the database server properties:
Database server properties
Property name Return type Description
The name of the database server to which
you are connected. For DB2 servers this
DBMS_NAME string is a combination of DB2 followed by the
operating system on which the database
server is running.
The version of the database server, in
the form of a string "MM.mm.uuuu" where
DBMS_VER string MM is the major version, mm is the minor
version, and uuuu is the update. For
example, "08.02.0001" represents major
version 8, minor version 2, update 1.
DB_CODEPAGE int The code page of the database to which
you are connected.
DB_NAME string The name of the database to which you
are connected.
The default transaction isolation level
supported by the server:
UR
Uncommitted read: changes are
immediately visible by all concurrent
transactions.
CS
Cursor stability: a row read by one
transaction can be altered and
committed by a second concurrent
transaction.
DFT_ISOLATION string RS
Read stability: a transaction can add
or remove rows matching a search
condition or a pending transaction.
RR
Repeatable read: data affected by
pending transaction is not available
to other transactions.
NC
No commit: any changes are visible at
the end of a successful operation.
Explicit commits and rollbacks are
not allowed.
IDENTIFIER_QUOTE_CHAR string The character used to delimit an
identifier.
INST_NAME string The instance on the database server that
contains the database.
An array of the isolation options
ISOLATION_OPTION array supported by the database server. The
isolation options are described in the
DFT_ISOLATION property.
KEYWORDS array An array of the keywords reserved by the
database server.
TRUE if the database server supports the
LIKE_ESCAPE_CLAUSE bool use of % and _ wildcard characters.
FALSE if the database server does not
support these wildcard characters.
Maximum length of a column name
MAX_COL_NAME_LEN int supported by the database server,
expressed in bytes.
Maximum length of an SQL identifier
MAX_IDENTIFIER_LEN int supported by the database server,
expressed in characters.
Maximum size of columns combined in an
MAX_INDEX_SIZE int index supported by the database server,
expressed in bytes.
Maximum length of a procedure name
MAX_PROC_NAME_LEN int supported by the database server,
expressed in bytes.
Maximum length of a row in a base table
MAX_ROW_SIZE int supported by the database server,
expressed in bytes.
Maximum length of a schema name
MAX_SCHEMA_NAME_LEN int supported by the database server,
expressed in bytes.
Maximum length of an SQL statement
MAX_STATEMENT_LEN int supported by the database server,
expressed in bytes.
Maximum length of a table name supported
MAX_TABLE_NAME_LEN int by the database server, expressed in
bytes.
TRUE if the database server supports
NON_NULLABLE_COLUMNS bool columns that can be defined as NOT NULL,
FALSE if the database server does not
support columns defined as NOT NULL.
TRUE if the database server supports the
PROCEDURES bool use of the CALL statement to call stored
procedures, FALSE if the database server
does not support the CALL statement.
A string containing all of the
SPECIAL_CHARS string characters other than a-Z, 0-9, and
underscore that can be used in an
identifier name.
The level of conformance to the ANSI/ISO
SQL-92 specification offered by the
database server:
ENTRY
Entry-level SQL-92 compliance.
FIPS127
SQL_CONFORMANCE string
FIPS-127-2 transitional compliance.
FULL
Full level SQL-92 compliance.
INTERMEDIATE
Intermediate level SQL-92 compliance.
Parameters
connection
Specifies an active DB2 client connection.
Return Values
Returns an object on a successful call. Returns FALSE on failure.
Examples
Example #1 A db2_server_info() example
To retrieve information about the server, you must pass a valid database
connection resource to db2_server_info().
DBMS_NAME );
echo "DBMS_VER: "; var_dump( $server->DBMS_VER );
echo "DB_CODEPAGE: "; var_dump( $server->DB_CODEPAGE );
echo "DB_NAME: "; var_dump( $server->DB_NAME );
echo "INST_NAME: "; var_dump( $server->INST_NAME );
echo "SPECIAL_CHARS: "; var_dump( $server->SPECIAL_CHARS );
echo "KEYWORDS: "; var_dump( sizeof($server->KEYWORDS) );
echo "DFT_ISOLATION: "; var_dump( $server->DFT_ISOLATION );
echo "ISOLATION_OPTION: ";
$il = '';
foreach( $server->ISOLATION_OPTION as $opt )
{
$il .= $opt." ";
}
var_dump( $il );
echo "SQL_CONFORMANCE: "; var_dump( $server->SQL_CONFORMANCE );
echo "PROCEDURES: "; var_dump( $server->PROCEDURES );
echo "IDENTIFIER_QUOTE_CHAR: "; var_dump( $server->IDENTIFIER_QUOTE_CHAR );
echo "LIKE_ESCAPE_CLAUSE: "; var_dump( $server->LIKE_ESCAPE_CLAUSE );
echo "MAX_COL_NAME_LEN: "; var_dump( $server->MAX_COL_NAME_LEN );
echo "MAX_ROW_SIZE: "; var_dump( $server->MAX_ROW_SIZE );
echo "MAX_IDENTIFIER_LEN: "; var_dump( $server->MAX_IDENTIFIER_LEN );
echo "MAX_INDEX_SIZE: "; var_dump( $server->MAX_INDEX_SIZE );
echo "MAX_PROC_NAME_LEN: "; var_dump( $server->MAX_PROC_NAME_LEN );
echo "MAX_SCHEMA_NAME_LEN: "; var_dump( $server->MAX_SCHEMA_NAME_LEN );
echo "MAX_STATEMENT_LEN: "; var_dump( $server->MAX_STATEMENT_LEN );
echo "MAX_TABLE_NAME_LEN: "; var_dump( $server->MAX_TABLE_NAME_LEN );
echo "NON_NULLABLE_COLUMNS: "; var_dump( $server->NON_NULLABLE_COLUMNS );
db2_close($conn);
}
?>
The above example will output:
DBMS_NAME: string(9) "DB2/LINUX"
DBMS_VER: string(10) "08.02.0000"
DB_CODEPAGE: int(1208)
DB_NAME: string(6) "SAMPLE"
INST_NAME: string(8) "db2inst1"
SPECIAL_CHARS: string(2) "@#"
KEYWORDS: int(179)
DFT_ISOLATION: string(2) "CS"
ISOLATION_OPTION: string(12) "UR CS RS RR "
SQL_CONFORMANCE: string(7) "FIPS127"
PROCEDURES: bool(true)
IDENTIFIER_QUOTE_CHAR: string(1) """
LIKE_ESCAPE_CLAUSE: bool(true)
MAX_COL_NAME_LEN: int(30)
MAX_ROW_SIZE: int(32677)
MAX_IDENTIFIER_LEN: int(18)
MAX_INDEX_SIZE: int(1024)
MAX_PROC_NAME_LEN: int(128)
MAX_SCHEMA_NAME_LEN: int(30)
MAX_STATEMENT_LEN: int(2097152)
MAX_TABLE_NAME_LEN: int(128)
NON_NULLABLE_COLUMNS: bool(true)
See Also
* db2_client_info() - Returns an object with properties that describe
the DB2 database client
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_set_option
(PECL ibm_db2 >= 1.0.0)
db2_set_option - Set options for connection or statement resources
Description
bool db2_set_option ( resource $resource , array $options , int $type )
Sets options for a statement resource or a connection resource. You cannot
set options for result set resources.
Parameters
resource
A valid statement resource as returned from db2_prepare() or a
valid connection resource as returned from db2_connect() or
db2_pconnect().
options
An associative array containing valid statement or connection
options. This parameter can be used to change autocommit values,
cursor types (scrollable or forward), and to specify the case of
the column names (lower, upper, or natural) that will appear in a
result set.
autocommit
Passing DB2_AUTOCOMMIT_ON turns autocommit on for the
specified connection resource.
Passing DB2_AUTOCOMMIT_OFF turns autocommit off for
the specified connection resource.
cursor
Passing DB2_FORWARD_ONLY specifies a forward-only
cursor for a statement resource. This is the default
cursor type, and is supported by all database
servers.
Passing DB2_SCROLLABLE specifies a scrollable cursor
for a statement resource. Scrollable cursors enable
result set rows to be accessed in non-sequential
order, but are only supported by IBM DB2 Universal
Database databases.
binmode
Passing DB2_BINARY specifies that binary data will be
returned as is. This is the default mode. This is the
equivalent of setting ibm_db2.binmode=1 in php.ini.
Passing DB2_CONVERT specifies that binary data will
be converted to hexadecimal encoding, and will be
returned as such. This is the equivalent of setting
ibm_db2.binmode=2 in php.ini.
Passing DB2_PASSTHRU specifies that binary data will
be converted to NULL. This is the equivalent of
setting ibm_db2.binmode=3 in php.ini.
db2_attr_case
Passing DB2_CASE_LOWER specifies that column names of
the result set are returned in lower case.
Passing DB2_CASE_UPPER specifies that column names of
the result set are returned in upper case.
Passing DB2_CASE_NATURAL specifies that column names
of the result set are returned in natural case.
deferred_prepare
Passing DB2_DEFERRED_PREPARE_ON turns deferred
prepare on for the specified statement resource.
Passing DB2_DEFERRED_PREPARE_OFF turns deferred
prepare off for the specified statement resource.
The following new i5/OS options are available in ibm_db2 version
1.5.1 and later. These options apply only when running PHP and
ibm_db2 natively on i5 systems.
i5_fetch_only
DB2_I5_FETCH_ON - Cursors are read-only and cannot be
used for positioned updates or deletes. This is the
default unless SQL_ATTR_FOR_FETCH_ONLY environment
has been set to SQL_FALSE.
DB2_I5_FETCH_OFF - Cursors can be used for positioned
updates and deletes.
The following new option is available in ibm_db2 version 1.8.0 and
later.
rowcount
DB2_ROWCOUNT_PREFETCH_ON - Client can request the
full row count prior to fetching, which means that
db2_num_rows() returns the number of rows selected
even when a ROLLFORWARD_ONLY cursor is used.
DB2_ROWCOUNT_PREFETCH_OFF - Client cannot request the
full row count prior to fetching.
The following new options are available in ibm_db2 version 1.7.0
and later.
trusted_user
To switch the user to a trusted user, pass the User
ID (String) of the trusted user as the value of this
key. This option can be set on a connection resource
only. To use this option, trusted context must be
enabled on the connection resource.
trusted_password
The password (String) that corresponds to the user
specified by the trusted_user key.
The following new options are available in ibm_db2 version 1.6.0
and later. These options provide useful tracking information that
can be accessed during execution with db2_get_option().
Note:
When the value in each option is being set, some servers might
not handle the entire length provided and might truncate the
value.
To ensure that the data specified in each option is converted
correctly when transmitted to a host system, use only the
characters A through Z, 0 through 9, and the underscore (_) or
period (.).
userid
SQL_ATTR_INFO_USERID - A pointer to a null-terminated
character string used to identify the client user ID
sent to the host database server when using DB2
Connect.
Note:
DB2 for z/OS and OS/390 servers support up to a
length of 16 characters. This user-id is not to be
confused with the authentication user-id, it is for
identification purposes only and is not used for
any authorization.
acctstr
SQL_ATTR_INFO_ACCTSTR - A pointer to a
null-terminated character string used to identify the
client accounting string sent to the host database
server when using DB2 Connect.
Note:
DB2 for z/OS and OS/390 servers support up to a
length of 200 characters.
applname
SQL_ATTR_INFO_APPLNAME - A pointer to a
null-terminated character string used to identify the
client application name sent to the host database
server when using DB2 Connect.
Note:
DB2 for z/OS and OS/390 servers support up to a
length of 32 characters.
wrkstnname
SQL_ATTR_INFO_WRKSTNNAME - A pointer to a
null-terminated character string used to identify the
client workstation name sent to the host database
server when using DB2 Connect.
Note:
DB2 for z/OS and OS/390 servers support up to a
length of 18 characters.
type
An integer value that specifies the type of resource that was
passed into the function. The type of resource and this value must
correspond.
Passing 1 as the value specifies that a connection resource has
been passed into the function.
Passing any integer not equal to 1 as the value specifies that a
statement resource has been passed into the function.
The following table specifies which options are compatible with the
available resource types:
Resource-Parameter Matrix
Key Value Resource Type
Connection Statement Result Set
autocommit DB2_AUTOCOMMIT_ON X - -
autocommit DB2_AUTOCOMMIT_OFF X - -
cursor DB2_SCROLLABLE - X -
cursor DB2_FORWARD_ONLY - X -
binmode DB2_BINARY X X -
binmode DB2_CONVERT X X -
binmode DB2_PASSTHRU X X -
db2_attr_case DB2_CASE_LOWER X X -
db2_attr_case DB2_CASE_UPPER X X -
db2_attr_case DB2_CASE_NATURAL X X -
deferred_prepare DB2_DEFERRED_PREPARE_ON - X -
deferred_prepare DB2_DEFERRED_PREPARE_OFF - X -
i5_fetch_only DB2_I5_FETCH_ON - X -
i5_fetch_only DB2_I5_FETCH_OFF - X -
rowcount DB2_ROWCOUNT_PREFETCH_ON - X -
rowcount DB2_ROWCOUNT_PREFETCH_OFF - X -
trusted_user (String) X - -
trusted_password (String) X - -
userid SQL_ATTR_INFO_USERID X X -
acctstr SQL_ATTR_INFO_ACCTSTR X X -
applname SQL_ATTR_INFO_APPLNAME X X -
wrkstnname SQL_ATTR_INFO_WRKSTNNAME X X -
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Setting one parameter with a connection resource
DB2_AUTOCOMMIT_ON);
/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);
/* Check if all options could be set correctly */
if($result)
{
echo 'Options Set Successfully';
}
else
{
echo 'Could Not Set Options';
}
?>
The above example will output:
Options Set Successfully
Example #2 Setting multiple parameters with a connection resource
DB2_AUTOCOMMIT_OFF,
'binmode' => DB2_PASSTHRU,
'db2_attr_case' => DB2_CASE_UPPER,
'cursor' => DB2_SCROLLABLE);
/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);
/* Check if all options could be set correctly */
if($result)
{
echo 'Options Set Successfully';
}
else
{
echo 'Could Not Set Options';
}
?>
The above example will output:
Options Set Successfully
Example #3 Setting multiple parameters with an invalid key
DB2_AUTOCOMMIT_OFF,
'MY_INVALID_KEY' => DB2_PASSTHRU,
'db2_attr_case' => DB2_CASE_UPPER,
'cursor' => DB2_SCROLLABLE);
/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);
/* Check if all options could be set correctly */
if($result)
{
echo 'Options Set Successfully';
}
else
{
echo 'Could Not Set Options';
}
?>
The above example will output:
Could Not Set Options
Example #4 Setting multiple parameters with an invalid value
DB2_AUTOCOMMIT_OFF,
'binmode' => 'INVALID_VALUE',
'db2_attr_case' => DB2_CASE_UPPER,
'cursor' => DB2_SCROLLABLE);
/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);
/* Check if all options could be set correctly */
if($result)
{
echo 'Options Set Successfully';
}
else
{
echo 'Could Not Set Options';
}
?>
The above example will output:
Could Not Set Options
Example #5 Setting multiple parameters with a connection resource and the
wrong type
DB2_AUTOCOMMIT_OFF,
'binmode' => DB2_PASSTHRU,
'db2_attr_case' => DB2_CASE_UPPER,
'cursor' => DB2_SCROLLABLE);
/* Call the function using the correct resource, options array, and the wrong type value */
$result = db2_set_option($conn, $options, 2);
/* Check if all options could be set correctly */
if($result)
{
echo 'Options Set Successfully';
}
else
{
echo 'Could Not Set Options';
}
?>
The above example will output:
Could Not Set Options
Example #6 Setting multiple parameters with the wrong resource
DB2_AUTOCOMMIT_OFF,
'binmode' => DB2_PASSTHRU,
'db2_attr_case' => DB2_CASE_UPPER,
'cursor' => DB2_SCROLLABLE);
$stmt = db2_prepare($conn, 'SELECT * FROM EMPLOYEE');
/* Call the function using the wrong resource, and the correct options array, and type values */
$result = db2_set_option($stmt, $options, 1);
/* Check if all options could be set correctly */
if($result)
{
echo 'Options Set Successfully';
}
else
{
echo 'Could Not Set Options';
}
?>
The above example will output:
Could Not Set Options
Example #7 Putting it all together
DB2_CASE_LOWER,
'cursor' => DB2_SCROLLABLE);
$stmt = db2_prepare($conn, 'SELECT * FROM EMPLOYEE WHERE EMPNO = ? OR EMPNO = ?');
/* Call the function using the correct resource, options array, and type values */
$option_result = db2_set_option($stmt, $options, 2);
$result = db2_execute($stmt, array('000130', '000140'));
/* Get Row 2 before Row 1 since Scrollable Cursor */
print_r(db2_fetch_assoc($stmt, 2));
print ' ';
print_r(db2_fetch_assoc($stmt, 1));
?>
The above example will output:
Array
(
[empno] => 000140
[firstnme] => HEATHER
[midinit] => A
[lastname] => NICHOLLS
[workdept] => C01
[phoneno] => 1793
[hiredate] => 1976-12-15
[job] => ANALYST
[edlevel] => 18
[sex] => F
[birthdate] => 1946-01-19
[salary] => 28420.00
[bonus] => 600.00
[comm] => 2274.00
)
Array
(
[empno] => 000130
[firstnme] => DELORES
[midinit] => M
[lastname] => QUINTANA
[workdept] => C01
[phoneno] => 4578
[hiredate] => 1971-07-28
[job] => ANALYST
[edlevel] => 16
[sex] => F
[birthdate] => 1925-09-15
[salary] => 23800.00
[bonus] => 500.00
[comm] => 1904.00
)
Example #8 i5/OS cursors are read-only
"nobody"));
$stmt = db2_prepare($conn, 'select * from names where first = ?');
$name = "first2";
db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
$options = array("i5_fetch_only"=>DB2_I5_FETCH_ON);
db2_set_option($stmt,$options,0);
if (db2_execute($stmt)) {
while ($row = db2_fetch_array($stmt)) {
echo "{$row[0]} {$row[1]}";
}
}
?>
The above example will output:
first2 last2
See Also
* db2_connect() - Returns a connection to a database
* db2_pconnect() - Returns a persistent connection to a database
* db2_exec() - Executes an SQL statement directly
* db2_prepare() - Prepares an SQL statement to be executed
* db2_cursor_type() - Returns the cursor type used by a statement
resource
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_special_columns
(PECL ibm_db2 >= 1.0.0)
db2_special_columns - Returns a result set listing the unique row
identifier columns for a table
Description
resource db2_special_columns ( resource $connection , string $qualifier ,
string $schema , string $table_name , int $scope )
Returns a result set listing the unique row identifier columns for a
table.
Parameters
connection
A valid connection to an IBM DB2, Cloudscape, or Apache Derby
database.
qualifier
A qualifier for DB2 databases running on OS/390 or z/OS servers.
For other databases, pass NULL or an empty string.
schema
The schema which contains the tables.
table_name
The name of the table.
scope
Integer value representing the minimum duration for which the
unique row identifier is valid. This can be one of the following
values:
Integer value SQL constant Description
Row identifier is valid only
0 SQL_SCOPE_CURROW while the cursor is positioned
on the row.
Row identifier is valid for
1 SQL_SCOPE_TRANSACTION the duration of the
transaction.
Row identifier is valid for
2 SQL_SCOPE_SESSION the duration of the
connection.
Return Values
Returns a statement resource with a result set containing rows with unique
row identifier information for a table. The rows are composed of the
following columns:
Column name Description
Integer SQL constant Description
value
Row identifier is valid only
0 SQL_SCOPE_CURROW while the cursor is
positioned on the row.
SCOPE Row identifier is valid for
1 SQL_SCOPE_TRANSACTION the duration of the
transaction.
Row identifier is valid for
2 SQL_SCOPE_SESSION the duration of the
connection.
COLUMN_NAME Name of the unique column.
DATA_TYPE SQL data type for the column.
TYPE_NAME Character string representation of the SQL data type for
the column.
COLUMN_SIZE An integer value representing the size of the column.
BUFFER_LENGTH Maximum number of bytes necessary to store data from this
column.
DECIMAL_DIGITS The scale of the column, or NULL where scale is not
applicable.
An integer value of either 10 (representing an exact
NUM_PREC_RADIX numeric data type), 2 (representing an approximate numeric
data type), or NULL (representing a data type for which
radix is not applicable).
PSEUDO_COLUMN Always returns 1.
See Also
* db2_column_privileges() - Returns a result set listing the columns and
associated privileges for a table
* db2_columns() - Returns a result set listing the columns and
associated metadata for a table
* db2_foreign_keys() - Returns a result set listing the foreign keys for
a table
* db2_primary_keys() - Returns a result set listing primary keys for a
table
* db2_procedure_columns() - Returns a result set listing stored
procedure parameters
* db2_procedures() - Returns a result set listing the stored procedures
registered in a database
* db2_statistics() - Returns a result set listing the index and
statistics for a table
* db2_table_privileges() - Returns a result set listing the tables and
associated privileges in a database
* db2_tables() - Returns a result set listing the tables and associated
metadata in a database
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_statistics
(PECL ibm_db2 >= 1.0.0)
db2_statistics - Returns a result set listing the index and statistics for
a table
Description
resource db2_statistics ( resource $connection , string $qualifier ,
string $schema , string $table-name , bool $unique )
Returns a result set listing the index and statistics for a table.
Parameters
connection
A valid connection to an IBM DB2, Cloudscape, or Apache Derby
database.
qualifier
A qualifier for DB2 databases running on OS/390 or z/OS servers.
For other databases, pass NULL or an empty string.
schema
The schema that contains the targeted table. If this parameter is
NULL, the statistics and indexes are returned for the schema of
the current user.
table_name
The name of the table.
unique
An integer value representing the type of index information to
return.
0
Return only the information for unique indexes on the
table.
1
Return the information for all indexes on the table.
Return Values
Returns a statement resource with a result set containing rows describing
the statistics and indexes for the base tables matching the specified
parameters. The rows are composed of the following columns:
Column name Description
TABLE_CAT The catalog that contains the table. The value is NULL if
this table does not have catalogs.
TABLE_SCHEM Name of the schema that contains the table.
TABLE_NAME Name of the table.
An integer value representing whether the index prohibits
unique values, or whether the row represents statistics
on the table itself:
NON_UNIQUE Return value Parameter type
0 (SQL_FALSE) The index allows duplicate values.
1 (SQL_TRUE) The index values must be unique.
NULL This row is statistics information for the
table itself.
INDEX_QUALIFIER A string value representing the qualifier that would have
to be prepended to INDEX_NAME to fully qualify the index.
INDEX_NAME A string representing the name of the index.
An integer value representing the type of information
contained in this row of the result set:
Return value Parameter type
0 (SQL_TABLE_STAT) The row contains statistics about
the table itself.
TYPE 1 (SQL_INDEX_CLUSTERED) The row contains information
about a clustered index.
2 (SQL_INDEX_HASH) The row contains information
about a hashed index.
The row contains information
3 (SQL_INDEX_OTHER) about a type of index that is
neither clustered nor hashed.
The 1-indexed position of the column in the index. NULL
ORDINAL_POSITION if the row contains statistics information about the
table itself.
COLUMN_NAME The name of the column in the index. NULL if the row
contains statistics information about the table itself.
A if the column is sorted in ascending order, D if the
ASC_OR_DESC column is sorted in descending order, NULL if the row
contains statistics information about the table itself.
If the row contains information about an index, this
column contains an integer value representing the number
of unique values in the index.
CARDINALITY
If the row contains information about the table itself,
this column contains an integer value representing the
number of rows in the table.
If the row contains information about an index, this
column contains an integer value representing the number
of pages used to store the index.
PAGES
If the row contains information about the table itself,
this column contains an integer value representing the
number of pages used to store the table.
FILTER_CONDITION Always returns NULL.
See Also
* db2_column_privileges() - Returns a result set listing the columns and
associated privileges for a table
* db2_columns() - Returns a result set listing the columns and
associated metadata for a table
* db2_foreign_keys() - Returns a result set listing the foreign keys for
a table
* db2_primary_keys() - Returns a result set listing primary keys for a
table
* db2_procedure_columns() - Returns a result set listing stored
procedure parameters
* db2_procedures() - Returns a result set listing the stored procedures
registered in a database
* db2_special_columns() - Returns a result set listing the unique row
identifier columns for a table
* db2_table_privileges() - Returns a result set listing the tables and
associated privileges in a database
* db2_tables() - Returns a result set listing the tables and associated
metadata in a database
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_stmt_error
(PECL ibm_db2 >= 1.0.0)
db2_stmt_error - Returns a string containing the SQLSTATE returned by an
SQL statement
Description
string db2_stmt_error ([ resource $stmt ] )
Returns a string containing the SQLSTATE value returned by an SQL
statement.
If you do not pass a statement resource as an argument to
db2_stmt_error(), the driver returns the SQLSTATE value associated with
the last attempt to return a statement resource, for example, from
db2_prepare() or db2_exec().
To learn what the SQLSTATE value means, you can issue the following
command at a DB2 Command Line Processor prompt: db2 '? sqlstate-value'.
You can also call db2_stmt_errormsg() to retrieve an explicit error
message and the associated SQLCODE value.
Parameters
stmt
A valid statement resource.
Return Values
Returns a string containing an SQLSTATE value.
See Also
* db2_conn_error() - Returns a string containing the SQLSTATE returned
by the last connection attempt
* db2_conn_errormsg() - Returns the last connection error message and
SQLCODE value
* db2_stmt_errormsg() - Returns a string containing the last SQL
statement error message
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_stmt_errormsg
(PECL ibm_db2 >= 1.0.0)
db2_stmt_errormsg - Returns a string containing the last SQL statement
error message
Description
string db2_stmt_errormsg ([ resource $stmt ] )
Returns a string containing the last SQL statement error message.
If you do not pass a statement resource as an argument to
db2_stmt_errormsg(), the driver returns the error message associated with
the last attempt to return a statement resource, for example, from
db2_prepare() or db2_exec().
Parameters
stmt
A valid statement resource.
Return Values
Returns a string containing the error message and SQLCODE value for the
last error that occurred issuing an SQL statement.
See Also
* db2_conn_error() - Returns a string containing the SQLSTATE returned
by the last connection attempt
* db2_conn_errormsg() - Returns the last connection error message and
SQLCODE value
* db2_stmt_error() - Returns a string containing the SQLSTATE returned
by an SQL statement
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_table_privileges
(PECL ibm_db2 >= 1.0.0)
db2_table_privileges - Returns a result set listing the tables and
associated privileges in a database
Description
resource db2_table_privileges ( resource $connection [, string $qualifier
[, string $schema [, string $table_name ]]] )
Returns a result set listing the tables and associated privileges in a
database.
Parameters
connection
A valid connection to an IBM DB2, Cloudscape, or Apache Derby
database.
qualifier
A qualifier for DB2 databases running on OS/390 or z/OS servers.
For other databases, pass NULL or an empty string.
schema
The schema which contains the tables. This parameter accepts a
search pattern containing _ and % as wildcards.
table_name
The name of the table. This parameter accepts a search pattern
containing _ and % as wildcards.
Return Values
Returns a statement resource with a result set containing rows describing
the privileges for the tables that match the specified parameters. The
rows are composed of the following columns:
Column name Description
TABLE_CAT The catalog that contains the table. The value is NULL if
this table does not have catalogs.
TABLE_SCHEM Name of the schema that contains the table.
TABLE_NAME Name of the table.
GRANTOR Authorization ID of the user who granted the privilege.
GRANTEE Authorization ID of the user to whom the privilege was
granted.
The privilege that has been granted. This can be one of
PRIVILEGE ALTER, CONTROL, DELETE, INDEX, INSERT, REFERENCES, SELECT, or
UPDATE.
IS_GRANTABLE A string value of "YES" or "NO" indicating whether the
grantee can grant the privilege to other users.
See Also
* db2_column_privileges() - Returns a result set listing the columns and
associated privileges for a table
* db2_columns() - Returns a result set listing the columns and
associated metadata for a table
* db2_foreign_keys() - Returns a result set listing the foreign keys for
a table
* db2_primary_keys() - Returns a result set listing primary keys for a
table
* db2_procedure_columns() - Returns a result set listing stored
procedure parameters
* db2_procedures() - Returns a result set listing the stored procedures
registered in a database
* db2_special_columns() - Returns a result set listing the unique row
identifier columns for a table
* db2_statistics() - Returns a result set listing the index and
statistics for a table
* db2_tables() - Returns a result set listing the tables and associated
metadata in a database
----------------------------------------------------------------------
----------------------------------------------------------------------
db2_tables
(PECL ibm_db2 >= 1.0.0)
db2_tables - Returns a result set listing the tables and associated
metadata in a database
Description
resource db2_tables ( resource $connection [, string $qualifier [, string
$schema [, string $table-name [, string $table-type ]]]] )
Returns a result set listing the tables and associated metadata in a
database.
Parameters
connection
A valid connection to an IBM DB2, Cloudscape, or Apache Derby
database.
qualifier
A qualifier for DB2 databases running on OS/390 or z/OS servers.
For other databases, pass NULL or an empty string.
schema
The schema which contains the tables. This parameter accepts a
search pattern containing _ and % as wildcards.
table-name
The name of the table. This parameter accepts a search pattern
containing _ and % as wildcards.
table-type
A list of comma-delimited table type identifiers. To match all
table types, pass NULL or an empty string. Valid table type
identifiers include: ALIAS, HIERARCHY TABLE, INOPERATIVE VIEW,
NICKNAME, MATERIALIZED QUERY TABLE, SYSTEM TABLE, TABLE, TYPED
TABLE, TYPED VIEW, and VIEW.
Return Values
Returns a statement resource with a result set containing rows describing
the tables that match the specified parameters. The rows are composed of
the following columns:
Column name Description
TABLE_CAT The catalog that contains the table. The value is NULL if this
table does not have catalogs.
TABLE_SCHEM Name of the schema that contains the table.
TABLE_NAME Name of the table.
TABLE_TYPE Table type identifier for the table.
REMARKS Description of the table.
See Also
* db2_column_privileges() - Returns a result set listing the columns and
associated privileges for a table
* db2_columns() - Returns a result set listing the columns and
associated metadata for a table
* db2_foreign_keys() - Returns a result set listing the foreign keys for
a table
* db2_primary_keys() - Returns a result set listing primary keys for a
table
* db2_procedure_columns() - Returns a result set listing stored
procedure parameters
* db2_procedures() - Returns a result set listing the stored procedures
registered in a database
* db2_special_columns() - Returns a result set listing the unique row
identifier columns for a table
* db2_statistics() - Returns a result set listing the index and
statistics for a table
* db2_table_privileges() - Returns a result set listing the tables and
associated privileges in a database
----------------------------------------------------------------------
Table of Contents
* db2_autocommit - Returns or sets the AUTOCOMMIT state for a database
connection
* db2_bind_param - Binds a PHP variable to an SQL statement parameter
* db2_client_info - Returns an object with properties that describe the
DB2 database client
* db2_close - Closes a database connection
* db2_column_privileges - Returns a result set listing the columns and
associated privileges for a table
* db2_columns - Returns a result set listing the columns and associated
metadata for a table
* db2_commit - Commits a transaction
* db2_conn_error - Returns a string containing the SQLSTATE returned by
the last connection attempt
* db2_conn_errormsg - Returns the last connection error message and
SQLCODE value
* db2_connect - Returns a connection to a database
* db2_cursor_type - Returns the cursor type used by a statement resource
* db2_escape_string - Used to escape certain characters
* db2_exec - Executes an SQL statement directly
* db2_execute - Executes a prepared SQL statement
* db2_fetch_array - Returns an array, indexed by column position,
representing a row in a result set
* db2_fetch_assoc - Returns an array, indexed by column name,
representing a row in a result set
* db2_fetch_both - Returns an array, indexed by both column name and
position, representing a row in a result set
* db2_fetch_object - Returns an object with properties representing
columns in the fetched row
* db2_fetch_row - Sets the result set pointer to the next row or
requested row
* db2_field_display_size - Returns the maximum number of bytes required
to display a column
* db2_field_name - Returns the name of the column in the result set
* db2_field_num - Returns the position of the named column in a result
set
* db2_field_precision - Returns the precision of the indicated column in
a result set
* db2_field_scale - Returns the scale of the indicated column in a
result set
* db2_field_type - Returns the data type of the indicated column in a
result set
* db2_field_width - Returns the width of the current value of the
indicated column in a result set
* db2_foreign_keys - Returns a result set listing the foreign keys for a
table
* db2_free_result - Frees resources associated with a result set
* db2_free_stmt - Frees resources associated with the indicated
statement resource
* db2_get_option - Retrieves an option value for a statement resource or
a connection resource
* db2_last_insert_id - Returns the auto generated ID of the last insert
query that successfully executed on this connection
* db2_lob_read - Gets a user defined size of LOB files with each
invocation
* db2_next_result - Requests the next result set from a stored procedure
* db2_num_fields - Returns the number of fields contained in a result
set
* db2_num_rows - Returns the number of rows affected by an SQL statement
* db2_pclose - Closes a persistent database connection
* db2_pconnect - Returns a persistent connection to a database
* db2_prepare - Prepares an SQL statement to be executed
* db2_primary_keys - Returns a result set listing primary keys for a
table
* db2_procedure_columns - Returns a result set listing stored procedure
parameters
* db2_procedures - Returns a result set listing the stored procedures
registered in a database
* db2_result - Returns a single column from a row in the result set
* db2_rollback - Rolls back a transaction
* db2_server_info - Returns an object with properties that describe the
DB2 database server
* db2_set_option - Set options for connection or statement resources
* db2_special_columns - Returns a result set listing the unique row
identifier columns for a table
* db2_statistics - Returns a result set listing the index and statistics
for a table
* db2_stmt_error - Returns a string containing the SQLSTATE returned by
an SQL statement
* db2_stmt_errormsg - Returns a string containing the last SQL statement
error message
* db2_table_privileges - Returns a result set listing the tables and
associated privileges in a database
* db2_tables - Returns a result set listing the tables and associated
metadata in a database
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* IBM DB2 Functions
* db2_autocommit - Returns or sets the AUTOCOMMIT state for a
database connection
* db2_bind_param - Binds a PHP variable to an SQL statement
parameter
* db2_client_info - Returns an object with properties that describe
the DB2 database client
* db2_close - Closes a database connection
* db2_column_privileges - Returns a result set listing the columns
and associated privileges for a table
* db2_columns - Returns a result set listing the columns and
associated metadata for a table
* db2_commit - Commits a transaction
* db2_conn_error - Returns a string containing the SQLSTATE
returned by the last connection attempt
* db2_conn_errormsg - Returns the last connection error message and
SQLCODE value
* db2_connect - Returns a connection to a database
* db2_cursor_type - Returns the cursor type used by a statement
resource
* db2_escape_string - Used to escape certain characters
* db2_exec - Executes an SQL statement directly
* db2_execute - Executes a prepared SQL statement
* db2_fetch_array - Returns an array, indexed by column position,
representing a row in a result set
* db2_fetch_assoc - Returns an array, indexed by column name,
representing a row in a result set
* db2_fetch_both - Returns an array, indexed by both column name
and position, representing a row in a result set
* db2_fetch_object - Returns an object with properties representing
columns in the fetched row
* db2_fetch_row - Sets the result set pointer to the next row or
requested row
* db2_field_display_size - Returns the maximum number of bytes
required to display a column
* db2_field_name - Returns the name of the column in the result set
* db2_field_num - Returns the position of the named column in a
result set
* db2_field_precision - Returns the precision of the indicated
column in a result set
* db2_field_scale - Returns the scale of the indicated column in a
result set
* db2_field_type - Returns the data type of the indicated column in
a result set
* db2_field_width - Returns the width of the current value of the
indicated column in a result set
* db2_foreign_keys - Returns a result set listing the foreign keys
for a table
* db2_free_result - Frees resources associated with a result set
* db2_free_stmt - Frees resources associated with the indicated
statement resource
* db2_get_option - Retrieves an option value for a statement
resource or a connection resource
* db2_last_insert_id - Returns the auto generated ID of the last
insert query that successfully executed on this connection
* db2_lob_read - Gets a user defined size of LOB files with each
invocation
* db2_next_result - Requests the next result set from a stored
procedure
* db2_num_fields - Returns the number of fields contained in a
result set
* db2_num_rows - Returns the number of rows affected by an SQL
statement
* db2_pclose - Closes a persistent database connection
* db2_pconnect - Returns a persistent connection to a database
* db2_prepare - Prepares an SQL statement to be executed
* db2_primary_keys - Returns a result set listing primary keys for
a table
* db2_procedure_columns - Returns a result set listing stored
procedure parameters
* db2_procedures - Returns a result set listing the stored
procedures registered in a database
* db2_result - Returns a single column from a row in the result set
* db2_rollback - Rolls back a transaction
* db2_server_info - Returns an object with properties that describe
the DB2 database server
* db2_set_option - Set options for connection or statement
resources
* db2_special_columns - Returns a result set listing the unique row
identifier columns for a table
* db2_statistics - Returns a result set listing the index and
statistics for a table
* db2_stmt_error - Returns a string containing the SQLSTATE
returned by an SQL statement
* db2_stmt_errormsg - Returns a string containing the last SQL
statement error message
* db2_table_privileges - Returns a result set listing the tables
and associated privileges in a database
* db2_tables - Returns a result set listing the tables and
associated metadata in a database
----------------------------------------------------------------------
----------------------------------------------------------------------
Ingres DBMS, EDBC, and Enterprise Access Gateways
----------------------------------------------------------------------
Introduction
The Ingres driver for PHP enables you to connect to and query the Ingres
DBMS, EDBC, and Enterprise Access Gateways.
Note:
This extension has been moved to the >> PECL repository and is no longer
bundled with PHP as of PHP 5.1.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
To use or build the PHP extension for Ingres you must have a working
Ingres client environment. You can download the client software for Ingres
from >> http://esd.ingres.com/.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
This >> PECL extension is not bundled with PHP. Information for installing
this PECL extension may be found in the manual chapter titled Installation
of PECL extensions. Additional information such as new releases,
downloads, source files, maintainer information, and a CHANGELOG, can be
located here: >> http://pecl.php.net/package/ingres.
You can download the DLL for this PECL extension from
>> http://esd.ingres.com/product/drivers/PHP/.
To have these functions available, you must >> download and compile this
extension, enabling Ingres support using the --with-ingres[=DIR] option,
where DIR is the Ingres base directory. If the II_SYSTEM environment
variable is not set correctly you may need to use --with-ingres=DIR to
specify your Ingres installation directory.
PHP code written for version 2.x and later is not backward-compatible with
earlier versions of this PHP extension. However, it is possible to run two
incompatible releases within the same PHP environment using the
--enable-ingres2 option. This configuration option renames the extension
to ingres2, changing function names, configuration settings, and
constants. For example, with this option enabled, ingres_connect() becomes
ingres2_connect().
To use this extension the system environment variable II_SYSTEM must be
defined. Linux and UNIX users will also need to define the shared library
search path, for example, LD_LIBRARY_PATH. When used with the Apache web
server these variables must be set explicitly in the startup script for
Apache. In addition, the PassEnv directive is required for the Ingres
extension to load the correct shared libraries. For example:
Example #1 Example usage of PassEnv for Ingres
PassEnv II_SYSTEM
PassEnv LD_LIBRARY_PATH
Note:
For example configurations for different web servers and operating
systems see
>> http://community.ingres.com/wiki/Ingres_Articles#Ingres_and_Web_Servers.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Ingres configuration options
Name Default Changeable Changelog
ingres.allow_persistent "1" PHP_INI_SYSTEM Available since ingres
1.0.0
ingres.array_index_start "1" PHP_INI_ALL Available since ingres
1.4.0.
ingres.auto "1" PHP_INI_ALL Available since ingres
2.0.0.
ingres.blob_segment_length "4096" PHP_INI_ALL Available since ingres
1.2.0.
ingres.cursor_mode "0" PHP_INI_ALL Available since ingres
1.1.0.
ingres.default_database NULL PHP_INI_ALL Available since ingres
1.0.0
ingres.default_password NULL PHP_INI_ALL Available since ingres
1.0.0
ingres.default_user NULL PHP_INI_ALL Available since ingres
1.0.0
ingres.describe 1 PHP_INI_ALL Available since ingres
2.1.0
ingres.fetch_buffer_size 100 PHP_INI_ALL Available since ingres
2.1.0
ingres.max_links "-1" PHP_INI_SYSTEM Available since ingres
1.0.0
ingres.max_persistent "-1" PHP_INI_SYSTEM Available since ingres
1.0.0
ingres.reuse_connection "1" PHP_INI_ALL Available since ingres
2.0.0
ingres.scrollable "1" PHP_INI_ALL Available since ingres
2.0.0.
ingres.trace "0" PHP_INI_ALL Available since ingres
2.0.0.
ingres.trace_connect "0" PHP_INI_ALL Available since ingres
1.2.1.
ingres.utf8 "1" PHP_INI_ALL Available since ingres
2.0.0.
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
ingres.allow_persistent boolean
Specifies whether to allow persistent connections to Ingres
ingres.array_index_start integer
Specifies the start value for an integer key for arrays generated
by ingres_fetch_row() or ingres_fetch_array(). By default
ingres.array_index_start is set to 1. If you wish to make the
ingres extension behave like other database extensions set this
configuration option to 0.
ingres.auto boolean
Enables or disables autocommit emulation. Ingres cannot have
multiple cursors open with autocommit enabled. When enabled, the
driver emulates autocommit.
ingres.blob_segment_length integer
Specifies the amount of memory to use when reading BLOB data, in
bytes
ingres.cursor_mode integer
Specifies the default mode for cursors opened with
ingres_prepare(). Valid values are INGRES_CURSOR_UPDATE or
INGRES_CURSOR_READONLY.
ingres.default_database string
Specifies the default database name to use when connecting to the
database server if no other name is specified. Does not apply in
SQL safe mode.
ingres.default_password string
Specifies the default password to use when connecting to the
database server if no other name is specified. Does not apply in
SQL safe mode.
ingres.default_user string
Specifies the default user name to use when connecting to the
database server if no other name is specified. Does not apply in
SQL safe mode.
ingres.describe boolean
Enables the use of DESCRIBE INPUT to determine the expected data
types for queries that use parameters. Available with Ingres 9.1.0
and later. When disabled, queries that have parameters passed may
need to manually describe the types of those parameters using the
types parameter in ingres_query().
Note:
Enabling this feature with ingres_query() will cause additional
communications traffic between this extension and the server. To
minimize this additional traffic, use ingres_prepare() and
ingres_execute().
ingres.fetch_buffer_size integer
Specifies the number of pre-fetch rows that ingres_fetch_array(),
ingres_fetch_object() and ingres_fetch_row() will try and fetch in
one fetch operation.
ingres.max_links integer
Specifies the maximum number of Ingres sessions allowed per
process or thread. The number of sessions should not exceed the
total number of connected sessions configured within Ingres.
ingres.max_persistent integer
Specifies the maximum number of persistent Ingres sessions allowed
per process or thread. The number of sessions should not exceed
the total number of connected sessions configured within Ingres.
ingres.reuse_connection boolean
Reuses an existing active connection if connecting to the same
database with the same user name
ingres.scrollable boolean
Enables support for scrollable cursors. When fetching CLOB or BLOB
data, this should be set to FALSE. Available with Ingres 9.2.0 or
later.
ingres.trace boolean
Enables simple tracing using E_NOTICE messages
ingres.trace_connect boolean
Prints E_NOTICE messages during ingres_connect() or
ingres_pconnect() calls
ingres.utf8 boolean
Assumes that strings being passed to National Character column
types (NVARCHAR or NCHAR) are using UTF8 encoding and converts
them to UTF16 for the server
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
ingres_connect() and ingres_pconnect() return an Ingres link identifier.
ingres_query() and ingres_unbuffered_query() return an Ingres result
identifier.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
INGRES_ASSOC (integer)
Columns are returned into the array having the fieldname as the
array index. Used with ingres_fetch_array().
INGRES_NUM (integer)
Columns are returned into the array having a numerical index to
the fields. By default this index starts at 1, the first field in
the result. To change this value, see ingres.array_index_start.
Used with ingres_fetch_array().
INGRES_BOTH (integer)
Columns are returned into the array having both a numerical index
and the fieldname as the array index. Used with
ingres_fetch_array().
INGRES_EXT_VERSION (string)
Specifies the version of the Ingres Extension. Available since
version 1.2.0 of the PECL extension.
INGRES_API_VERSION (integer)
Specifies the version of Ingres OpenAPI that the extension was
built against. Available since version 1.2.0 of the PECL
extension.
INGRES_CURSOR_READONLY (integer)
Specifies that Ingres cursors should be opened in "readonly" mode.
Available since version 1.2.0 of the PECL extension. Used with
ingres.cursor_mode.
INGRES_CURSOR_UPDATE (integer)
Specifies that Ingres cursors should be opened "for update."
Available since version 1.2.0 of the PECL extension. Used with
ingres.cursor_mode.
INGRES_DATE_MULTINATIONAL (integer)
Equivalent to the II_DATE_FORMAT setting of MULTINATIONAL.
Available since version 1.2.0 of the PECL extension. Used with
ingres_connect(), ingres_pconnect() and ingres_set_environment().
See options in ingres_set_environment().
INGRES_DATE_MULTINATIONAL4 (integer)
Equivalent to the II_DATE_FORMAT setting of MULTINATIONAL4.
Available since version 1.2.0 of the PECL extension. Used with
ingres_connect(), ingres_pconnect() and ingres_set_environment().
See options in ingres_set_environment().
INGRES_DATE_FINNISH (integer)
Equivalent to the II_DATE_FORMAT setting of FINNISH. Available
since version 1.2.0 of the PECL extension. Used with
ingres_connect(), ingres_pconnect() and ingres_set_environment().
See options in ingres_set_environment().
INGRES_DATE_ISO (integer)
Equivalent to the II_DATE_FORMAT setting of ISO. Available since
version 1.2.0 of the PECL extension. Used with ingres_connect(),
ingres_pconnect() and ingres_set_environment(). See options in
ingres_set_environment().
INGRES_DATE_ISO4 (integer)
Equivalent to the II_DATE_FORMAT setting of ISO4. Available since
version 1.2.0 of the PECL extension. Used with ingres_connect(),
ingres_pconnect() and ingres_set_environment(). See options in
ingres_set_environment().
INGRES_DATE_GERMAN (integer)
Equivalent to the II_DATE_FORMAT setting of GERMAN. Available
since version 1.2.0 of the PECL extension. Used with
ingres_connect(), ingres_pconnect() and ingres_set_environment().
See options in ingres_set_environment().
INGRES_DATE_MDY (integer)
Equivalent to the II_DATE_FORMAT setting of MDY. Available since
version 1.2.0 of the PECL extension. Used with ingres_connect(),
ingres_pconnect() and ingres_set_environment(). See options in
ingres_set_environment().
INGRES_DATE_DMY (integer)
Equivalent to the II_DATE_FORMAT setting of DMY. Available since
version 1.2.0 of the PECL extension. Used with ingres_connect(),
ingres_pconnect() and ingres_set_environment(). See options in
ingres_set_environment().
INGRES_DATE_YMD (integer)
Equivalent to the II_DATE_FORMAT setting of YMD. Available since
version 1.2.0 of the PECL extension. Used with ingres_connect(),
ingres_pconnect() and ingres_set_environment(). See options in
ingres_set_environment().
INGRES_MONEY_LEADING (integer)
Specifies the currency character that should be placed at the
start of a money value. Equivalent to setting II_MONEY_FORMAT to
"L:". Available since version 1.2.0 of the PECL extension. Used
with ingres_connect(), ingres_pconnect() and
ingres_set_environment(). See options in ingres_set_environment().
INGRES_MONEY_TRAILING (integer)
Specifies the currency character that should be placed at the end
of a money value. Equivalent to setting II_MONEY_FORMAT to "T:".
Available since version 1.2.0 of the PECL extension. Used with
ingres_connect(), ingres_pconnect() and ingres_set_environment().
See options in ingres_set_environment().
INGRES_STRUCTURE_BTREE (integer)
Specifies the default table or index structure to BTREE when used
in combination with the options or index_structure option when
connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and ingres_pconnect(). See options in
ingres_connect().
INGRES_STRUCTURE_CBTREE (integer)
Specifies the default table or index structure to COMPRESSED BTREE
when used in combination with the options or index_structure
option when connecting. Available since version 1.4.0 of the PECL
extension. Used with ingres_connect() and ingres_pconnect(). See
options in ingres_connect().
INGRES_STRUCTURE_HASH (integer)
Specifies the default table or index structure to HASH when used
in combination with the options or index_structure option when
connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and ingres_pconnect(). See options in
ingres_connect().
INGRES_STRUCTURE_CHASH (integer)
Specifies the default table or index structure to COMPRESSED HASH
when used in combination with the options or index_structure
option when connecting. Available since version 1.4.0 of the PECL
extension. Used with ingres_connect() and ingres_pconnect(). See
options in ingres_connect().
INGRES_STRUCTURE_HEAP (integer)
Specifies the default table structure to HEAP when used in
combination with the options option when connecting. Available
since version 1.4.0 of the PECL extension. Used with
ingres_connect() and ingres_pconnect(). See options in
ingres_connect().
INGRES_STRUCTURE_CHEAP (integer)
Specifies the default table structure to COMPRESSED HEAP when used
in combination with the options option when connecting. Available
since version 1.4.0 of the PECL extension. Used with
ingres_connect() and ingres_pconnect(). See options in
ingres_connect().
INGRES_STRUCTURE_ISAM (integer)
Specifies the default table or index structure to ISAM when used
in combination with the options or index_structure option when
connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and ingres_pconnect(). See options in
ingres_connect().
INGRES_STRUCTURE_CISAM (integer)
Specifies the default table or index structure to COMPRESSED ISAM
when used in combination with the options or index_structure
option when connecting. Available since version 1.4.0 of the PECL
extension. Used with ingres_connect() and ingres_pconnect(). See
options in ingres_connect().
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Table of Contents
* Basic usage
----------------------------------------------------------------------
Basic usage
The following simple example shows how to connect to an Ingres database,
execute a query, print resulting rows and disconnect from the database.
Example #1 Simple Ingres Example
\n";
while ($iitables = ingres_fetch_object($result)) {
echo "\t\n";
echo "\t\t" . $iitables->relid . " \n";
echo "\t\t" . $iitables->relowner . " \n";
echo "\t \n";
}
echo "
\n";
// Free results
ingres_free_result($result);
// Commit transaction
ingres_commit($link);
// Closing connection
ingres_close($link);
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Ingres Functions
----------------------------------------------------------------------
ingres_autocommit_state
(PECL ingres >= 2.0.0)
ingres_autocommit_state - Test if the connection is using autocommit
Description
bool ingres_autocommit_state ( resource $link )
ingres_autocommit_state() is called to determine whether the current link
has autocommit enabled or not.
Parameters
link
The connection link identifier
Return Values
Returns TRUE if autocommit is enabled or FALSE when autocommit is disabled
See Also
* ingres_autocommit() - Switch autocommit on or off
* ingres_query() - Send an SQL query to Ingres
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_autocommit
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)
ingres_autocommit - Switch autocommit on or off
Description
bool ingres_autocommit ( resource $link )
ingres_autocommit() is called before opening a transaction (before the
first call to ingres_query() or just after a call to ingres_rollback() or
ingres_commit()) to switch the autocommit mode of the server on or off
(when the script begins the autocommit mode is off).
When autocommit mode is on, every query is automatically committed by the
server, as if ingres_commit() was called after every call to
ingres_query(). To see if autocommit is enabled use,
ingres_autocommit_state().
By default Ingres will rollback any uncommitted transactions at the end of
a request. Use this function or ingres_commit() to ensure your data is
committed to the database.
Parameters
link
The connection link identifier
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ingres_autocommit_state() - Test if the connection is using autocommit
* ingres_query() - Send an SQL query to Ingres
* ingres_rollback() - Roll back a transaction
* ingres_commit() - Commit a transaction
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_charset
(PECL ingres >= 2.1.0)
ingres_charset - Returns the installation character set
Description
string ingres_charset ( resource $link )
ingres_charset() is called to determine the character set being used by
the Ingres client, from II_CHARSETxx (where xx is the installation code).
Note:
You can override the value returned by using the function putenv().
Changing the value of II_CHARSETxx in a running Ingres installation can
cause data corruption.
Parameters
link
The connection link identifier
Return Values
Returns a string with the value for II_CHARSETxx or returns NULL if the
value could not be determined.
Examples
Example #1 ingres_charset() - Get the installation character set
See Also
* ingres_connect() - Open a connection to an Ingres database
* ingres_query() - Send an SQL query to Ingres
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_close
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)
ingres_close - Close an Ingres database connection
Description
bool ingres_close ( resource $link )
ingres_close() closes the connection to the Ingres server that is
associated with the specified link.
ingres_close() is usually unnecessary, as it will not close persistent
connections and all non-persistent connections are automatically closed at
the end of the script.
Parameters
link
The connection link identifier
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ingres_connect() - Open a connection to an Ingres database
* ingres_pconnect() - Open a persistent connection to an Ingres database
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_commit
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)
ingres_commit - Commit a transaction
Description
bool ingres_commit ( resource $link )
ingres_commit() commits the currently open transaction, making all changes
made to the database permanent.
This closes the transaction. A new transaction can be opened by sending a
query with ingres_query().
You can also have the server commit automatically after every query by
calling ingres_autocommit() before opening the transaction.
By default Ingres will roll back any uncommitted transactions at the end
of a request. Use this function or ingres_autocommit() to ensure your that
data is committed to the database.
Parameters
link
The connection link identifier
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ingres_query() - Send an SQL query to Ingres
* ingres_rollback() - Roll back a transaction
* ingres_autocommit() - Switch autocommit on or off
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_connect
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)
ingres_connect - Open a connection to an Ingres database
Description
resource ingres_connect ([ string $database [, string $username [, string
$password [, array $options ]]]] )
ingres_connect() opens a connection with the given Ingres database.
The connection is closed when the script ends or when ingres_close() is
called on this link.
Parameters
If some parameters are missing, ingres_connect() uses the values in
php.ini for ingres.default_database, ingres.default_user and
ingres.default_password.
database
The database name. Must follow the syntax:
[vnode::]dbname[/svr_class]
username
The Ingres user name
password
The password associated with username
options
ingres_connect() options
Option name Option Description Example
type
date_century_boundary integer The threshold by which a 50
2-digit year is determined to
be in the current century or
in the next century.
Equivalent to
II_DATE_CENTURY_BOUNDARY.
group string Specifies the group ID of the payroll
user, equivalent to the "-G"
flag
role string The role ID of the
application. If a role
password is required, the
parameter value should be
specified as "role/password"
effective_user string The ingres user account being another_user
impersonated, equivalent to
the "-u" flag
dbms_password string The internal database password s3cr3t
for the user connecting to
Ingres
table_structure string The default structure for new INGRES_STRUCTURE_BTREE
tables. Valid values for
table_structure are:
* INGRES_STRUCTURE_BTREE
* INGRES_STRUCTURE_HASH
* INGRES_STRUCTURE_HEAP
* INGRES_STRUCTURE_ISAM
* INGRES_STRUCTURE_CBTREE
* INGRES_STRUCTURE_CISAM
* INGRES_STRUCTURE_CHASH
* INGRES_STRUCTURE_CHEAP
index_structure string The default structure for new INGRES_STRUCTURE_HASH
secondary indexes. Valid
values for index_structure
are:
* INGRES_STRUCTURE_CBTREE
* INGRES_STRUCTURE_CISAM
* INGRES_STRUCTURE_CHASH
* INGRES_STRUCTURE_BTREE
* INGRES_STRUCTURE_HASH
* INGRES_STRUCTURE_ISAM
login_local boolean Determines how the connection TRUE
user ID and password are used
when a VNODE is included in
the target database string. If
set to TRUE, the user ID and
password are used to locally
access the VNODE, and the
VNODE login information is
used to establish the DBMS
connection. If set to FALSE,
the process user ID is used to
access the VNODE, and the
connection user ID and
password are used in place of
the VNODE login information to
establish the DBMS connection.
This parameter is ignored if
no VNODE is included in the
target database string. The
default is FALSE.
timezone string Controls the timezone of the
session. If not set it will
default to the value defined
by II_TIMEZONE_NAME. If
II_TIMEZONE_NAME is not
defined, NA-PACIFIC (GMT-8
with Daylight Savings) is
used.
date_format integer Sets the allowable input and INGRES_DATE_MULTINATIONAL4
output format for Ingres
dates. Defaults to the value
defined by II_DATE_FORMAT. If
II_DATE_FORMAT is not set the
default date format is US,
e.g. mm/dd/yy. Valid values
for date_format are:
* INGRES_DATE_DMY
* INGRES_DATE_FINISH
* INGRES_DATE_GERMAN
* INGRES_DATE_ISO
* INGRES_DATE_ISO4
* INGRES_DATE_MDY
* INGRES_DATE_MULTINATIONAL
* INGRES_DATE_MULTINATIONAL4
* INGRES_DATE_YMD
* INGRES_DATE_US
decimal_separator string The character identifier for ","
decimal data
money_lort integer Leading or trailing currency INGRES_MONEY_TRAILING
sign. Valid values for
money_lort are:
* INGRES_MONEY_LEADING
* INGRES_MONEY_TRAILING
money_sign string The currency symbol to be used EUR
with the MONEY datatype
money_precision integer The precision of the MONEY 3
datatype
float4_precision integer Precision of the FLOAT4 10
datatype
float8_precision integer Precision of the FLOAT8 data 10
blob_segment_length integer The amount of data in bytes to 8192
fetch at a time when
retrieving BLOB or CLOB data,
defaults to 4096 bytes when
not explicitly set
Return Values
Returns a Ingres link resource on success or FALSE on failure
Examples
Example #1 Open a connection to an Ingres database
See Also
* ingres_pconnect() - Open a persistent connection to an Ingres database
* ingres_close() - Close an Ingres database connection
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_cursor
(PECL ingres >= 1.1.0)
ingres_cursor - Get a cursor name for a given result resource
Description
string ingres_cursor ( resource $result )
Returns a string with the active cursor name. If no cursor is active then
NULL is returned.
Parameters
result
The query result identifier
Return Values
Returns a string containing the active cursor name. If no cursor is active
then NULL is returned.
Examples
Example #1 Get cursor name for a query resource
See Also
* ingres_prepare() - Prepare a query for later execution
* ingres_execute() - Execute a prepared query
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_errno
(PECL ingres >= 1.1.0)
ingres_errno - Get the last Ingres error number generated
Description
int ingres_errno ([ resource $link ] )
Returns an integer containing the last error number. If no error was
reported 0 is returned.
If a link resource is passed to ingres_errno() it returns the last error
recorded for the link. If no link is passed, then ingres_errno() returns
the last error reported using the default link.
The function, ingres_errno(), should always be called after executing a
database query. Calling another function before ingres_errno() is called
will reset or change any error code from the last Ingres function call.
Parameters
link
The connection link identifier
Return Values
Returns an integer containing the last error number. If no error was
reported, 0 is returned.
Examples
Example #1 Get the last Ingres error number generated
See Also
* ingres_error() - Get a meaningful error message for the last error
generated
* ingres_errsqlstate() - Get the last SQLSTATE error code generated
* ingres_next_error() - Get the next Ingres error
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_error
(PECL ingres >= 1.1.0)
ingres_error - Get a meaningful error message for the last error generated
Description
string ingres_error ([ resource $link ] )
Returns a string containing the last error, or NULL if no error has
occurred.
If a link resource is passed to ingres_error(), it returns the last error
recorded for the link. If no link is passed then ingres_error() returns
the last error reported using the default link.
The function, ingres_error(), should always be called after executing any
database query. Calling another function before ingres_error() is called
will reset or change any error message from the last Ingres function call.
Parameters
link
The connection link identifier
Return Values
Returns a string containing the last error, or NULL if no error has
occurred.
Examples
Example #1 Get a message for the last error generated
See Also
* ingres_errno() - Get the last Ingres error number generated
* ingres_errsqlstate() - Get the last SQLSTATE error code generated
* ingres_next_error() - Get the next Ingres error
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_errsqlstate
(PECL ingres >= 1.1.0)
ingres_errsqlstate - Get the last SQLSTATE error code generated
Description
string ingres_errsqlstate ([ resource $link ] )
Returns a string containing the last SQLSTATE, or NULL if no error has
occurred.
If a link resource is passed to ingres_errsqlstate(), it returns the last
error recorded for the link. If no link is passed, then
ingres_errsqlstate() returns the last error reported using the default
link.
The function, ingres_errsqlstate(), should always be called after
executing any database query. Calling another function before
ingres_errsqlstate() is called will reset or change any error message from
the last Ingres function call.
Parameters
link
The connection link identifier
Return Values
Returns a string containing the last SQLSTATE, or NULL if no error has
occurred.
Examples
Example #1 Get the last SQLSTATE error code generated
See Also
* ingres_errno() - Get the last Ingres error number generated
* ingres_error() - Get a meaningful error message for the last error
generated
* ingres_next_error() - Get the next Ingres error
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_escape_string
(PECL ingres >= 2.1.0)
ingres_escape_string - Escape special characters for use in a query
Description
string ingres_escape_string ( resource $link , string $source_string )
ingres_escape_string() is used to escape certain characters within a
string before it is sent to the database server.
Parameters
link
The connection link identifier
source_string
The source string to be parsed
Return Values
Returns a string containing the escaped data.
Examples
Example #1 Escape special characters for use in a query
up_first . ' ';
}
ingres_commit($link);
ingres_close($link);
?>
See Also
* ingres_query() - Send an SQL query to Ingres
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_execute
(PECL ingres >= 1.1.0)
ingres_execute - Execute a prepared query
Description
bool ingres_execute ( resource $result [, array $params [, string $types
]] )
Execute a query prepared using ingres_prepare().
Note: Related Configurations
See also the ingres.describe, ingres.scrollable and ingres.utf8
directives in Runtime Configuration.
Parameters
result
The result query identifier
params
An array of parameter values to be used with the query
types
A string containing a sequence of types for the parameter values
passed. See the types parameter in ingres_query() for the list of
type codes.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ingres_unbuffered_query() - Send an unbuffered SQL query to Ingres
* ingres_fetch_array() - Fetch a row of result into an array
* ingres_fetch_assoc() - Fetch a row of result into an associative array
* ingres_fetch_object() - Fetch a row of result into an object
* ingres_fetch_row() - Fetch a row of result into an enumerated array
* ingres_commit() - Commit a transaction
* ingres_rollback() - Roll back a transaction
* ingres_autocommit() - Switch autocommit on or off
* ingres_set_environment() - Set environment features controlling output
options
* ingres_errno() - Get the last Ingres error number generated
* ingres_error() - Get a meaningful error message for the last error
generated
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_fetch_array
( PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)
ingres_fetch_array - Fetch a row of result into an array
Description
array ingres_fetch_array ( resource $result [, int $result_type ] )
This function is an extended version of ingres_fetch_row(). In addition to
storing the data in the numeric indices of the result array, it also
stores the data in associative indices, using the field names as keys.
If two or more columns of the result have the same field names, the last
column will take precedence. To access the another column or columns of
the same name, you must use the numeric index of the column or make an
alias for the column. For example:
With regard to speed, the function is identical to ingres_fetch_object(),
and almost as quick as ingres_fetch_row() (the difference is
insignificant).
By default, arrays created by ingres_fetch_array() start from position 1
and not 0 as with other DBMS extensions. The starting position can be
adjusted to 0 using the configuration parameter ingres.array_index_start.
Note: Related Configurations
See also the ingres.array_index_start, ingres.fetch_buffer_size and
ingres.utf8 directives in Runtime Configuration.
Parameters
result
The query result identifier
result_type
The result type. This result_type can be INGRES_NUM for enumerated
array, INGRES_ASSOC for associative array, or INGRES_BOTH
(default).
Return Values
Returns an array that corresponds to the fetched row, or FALSE if there
are no more rows
Examples
Example #1 Fetch a row of result into an array
See Also
* ingres_query() - Send an SQL query to Ingres
* ingres_num_fields() - Get the number of fields returned by the last
query
* ingres_field_name() - Get the name of a field in a query result
* ingres_fetch_assoc() - Fetch a row of result into an associative array
* ingres_fetch_object() - Fetch a row of result into an object
* ingres_fetch_row() - Fetch a row of result into an enumerated array
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_fetch_assoc
(PECL ingres >= 2.2.2)
ingres_fetch_assoc - Fetch a row of result into an associative array
Description
array ingres_fetch_assoc ( resource $result )
This function is stores the data fetched from a query executed using
ingres_query() in an associative array, using the field names as keys.
With regard to speed, the function is identical to ingres_fetch_object(),
and almost as quick as ingres_fetch_row() (the difference is
insignificant).
By default, arrays created by ingres_fetch_assoc() start from position 1
and not 0 as with other DBMS extensions. The starting position can be
adjusted to 0 using the configuration parameter ingres.array_index_start.
Note: Related Configurations
See also the ingres.array_index_start, ingres.fetch_buffer_size and
ingres.utf8 directives in Runtime Configuration.
Parameters
result
The query result identifier
Return Values
Returns an associative array that corresponds to the fetched row, or FALSE
if there are no more rows
Examples
Example #1 Fetch a row into an associative array
See Also
* ingres_query() - Send an SQL query to Ingres
* ingres_num_fields() - Get the number of fields returned by the last
query
* ingres_field_name() - Get the name of a field in a query result
* ingres_fetch_array() - Fetch a row of result into an array
* ingres_fetch_object() - Fetch a row of result into an object
* ingres_fetch_row() - Fetch a row of result into an enumerated array
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_fetch_object
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)
ingres_fetch_object - Fetch a row of result into an object
Description
object ingres_fetch_object ( resource $result [, int $result_type ] )
This function is similar to ingres_fetch_array(), with one difference - an
object is returned instead of an array. Indirectly, this means that you
can access the data only by the field names and not by their offsets
(numbers are illegal property names).
With regard to speed, the function is identical to ingres_fetch_array(),
and almost as quick as ingres_fetch_row() (the difference is
insignificant).
Note: Related Configurations
See also the ingres.fetch_buffer_size and ingres.utf8 directives in
Runtime Configuration.
Parameters
link
The query result identifier
result_type
(Optional argument.) result_type is a constant and can take the
following values: INGRES_ASSOC, INGRES_NUM, and INGRES_BOTH.
Return Values
Returns an object that corresponds to the fetched row, or FALSE if there
are no more rows
Examples
Example #1 Fetch a row into an object
user_id;
echo $row->fullname;
}
?>
See Also
* ingres_query() - Send an SQL query to Ingres
* ingres_num_fields() - Get the number of fields returned by the last
query
* ingres_field_name() - Get the name of a field in a query result
* ingres_fetch_array() - Fetch a row of result into an array
* ingres_fetch_assoc() - Fetch a row of result into an associative array
* ingres_fetch_row() - Fetch a row of result into an enumerated array
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_fetch_proc_return
(PECL ingres >= 1.4.0)
ingres_fetch_proc_return - Get the return value from a procedure call
Description
int ingres_fetch_proc_return ( resource $result )
This function is used to retrieve the return value following the execution
of an Ingres database procedure (stored procedure).
Note:
If used with a row-producing procedure, this function should be called
after all the rows from the procedure have been fetched using
ingres_fetch_array(), ingres_fetch_object() or ingres_fetch_row(). This
function will eliminate any rows yet to be fetched should there be any
left over.
Parameters
result
The result identifier for a query
Return Values
Returns an integer if there is a return value otherwise it will return
NULL.
Examples
Example #1 Get the return value from a procedure call
See Also
* ingres_query() - Send an SQL query to Ingres
* ingres_fetch_array() - Fetch a row of result into an array
* ingres_fetch_object() - Fetch a row of result into an object
* ingres_fetch_row() - Fetch a row of result into an enumerated array
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_fetch_row
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)
ingres_fetch_row - Fetch a row of result into an enumerated array
Description
array ingres_fetch_row ( resource $result )
ingres_fetch_row() returns an array that corresponds to the fetched row,
or FALSE if there are no more rows. Each result column is stored in an
array offset, starting at offset 1.
Subsequent calls to ingres_fetch_row() return the next row in the result
set, or FALSE if there are no more rows.
By default, arrays created by ingres_fetch_row() start from position 1 and
not 0 as with other DBMS extensions. The starting position can be adjusted
to 0 using the configuration parameter ingres.array_index_start.
Note: Related Configurations
See also the ingres.array_index_start, ingres.fetch_buffer_size and
ingres.utf8 directives in Runtime Configuration.
Parameters
result
The query result identifier
Return Values
Returns an array that corresponds to the fetched row, or FALSE if there
are no more rows
Examples
Example #1 Fetch a row of result into an enumerated array
See Also
* ingres_num_fields() - Get the number of fields returned by the last
query
* ingres_query() - Send an SQL query to Ingres
* ingres_fetch_array() - Fetch a row of result into an array
* ingres_fetch_assoc() - Fetch a row of result into an associative array
* ingres_fetch_object() - Fetch a row of result into an object
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_field_length
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)
ingres_field_length - Get the length of a field
Description
int ingres_field_length ( resource $result , int $index )
ingres_field_length() returns the length of a field. This is the number of
bytes the server uses to store the field. For detailed information, see
the Ingres OpenAPI User Guide, Appendix "Data Types" in the Ingres
documentation.
Note: Related Configurations
See ingres.array_index_start in Runtime Configuration
Parameters
result
The query result identifier
index
index is the column number whose length will be retrieved.
The possible values of index depend upon the value of
ingres.array_index_start. If ingres.array_index_start is 1 (the
default) then index must be between 1 and the value returned by
ingres_num_fields(). If ingres.array_index_start is 0 then index
must be between 0 and ingres_num_fields() - 1.
Return Values
Returns the length of a field.
See Also
* ingres_query() - Send an SQL query to Ingres
* ingres_fetch_array() - Fetch a row of result into an array
* ingres_fetch_assoc() - Fetch a row of result into an associative array
* ingres_fetch_object() - Fetch a row of result into an object
* ingres_fetch_row() - Fetch a row of result into an enumerated array
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_field_name
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)
ingres_field_name - Get the name of a field in a query result
Description
string ingres_field_name ( resource $result , int $index )
ingres_field_name() returns the name of a field in a query result.
Note: Related Configurations
See ingres.array_index_start in Runtime Configuration
Parameters
result
The query result identifier
index
index is the field whose name will be retrieved.
The possible values of index depend upon the value of
ingres.array_index_start. If ingres.array_index_start is 1 (the
default) then index must be between 1 and the value returned by
ingres_num_fields(). If ingres.array_index_start is 0 then index
must be between 0 and ingres_num_fields() - 1.
Return Values
Returns the name of a field in a query result or FALSE on failure
See Also
* ingres_query() - Send an SQL query to Ingres
* ingres_fetch_array() - Fetch a row of result into an array
* ingres_fetch_assoc() - Fetch a row of result into an associative array
* ingres_fetch_object() - Fetch a row of result into an object
* ingres_fetch_row() - Fetch a row of result into an enumerated array
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_field_nullable
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)
ingres_field_nullable - Test if a field is nullable
Description
bool ingres_field_nullable ( resource $result , int $index )
Test if a field is nullable.
Note: Related Configurations
See ingres.array_index_start in Runtime Configuration
Parameters
result
The query result identifier
index
index is the field whose nullability will be retrieved.
The possible values of index depend upon the value of
ingres.array_index_start. If ingres.array_index_start is 1 (the
default) then index must be between 1 and the value returned by
ingres_num_fields(). If ingres.array_index_start is 0 then index
must be between 0 and ingres_num_fields() - 1.
Return Values
ingres_field_nullable() returns TRUE if the field can be set to the NULL
value and FALSE if it cannot
See Also
* ingres_query() - Send an SQL query to Ingres
* ingres_fetch_array() - Fetch a row of result into an array
* ingres_fetch_assoc() - Fetch a row of result into an associative array
* ingres_fetch_object() - Fetch a row of result into an object
* ingres_fetch_row() - Fetch a row of result into an enumerated array
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_field_precision
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)
ingres_field_precision - Get the precision of a field
Description
int ingres_field_precision ( resource $result , int $index )
ingres_field_precision() returns the precision of a field. This value is
used only for decimal, float, and money SQL data types. For detailed
information, see the Ingres OpenAPI User Guide, Appendix "Data Types" in
the Ingres documentation.
Note: Related Configurations
See ingres.array_index_start in Runtime Configuration
Parameters
result
The query result identifier
index
index is the field whose precision will be retrieved.
The possible values of index depend upon the value of
ingres.array_index_start. If ingres.array_index_start is 1 (the
default) then index must be between 1 and the value returned by
ingres_num_fields(). If ingres.array_index_start is 0 then index
must be between 0 and ingres_num_fields() - 1.
Return Values
Returns the field precision as an integer
See Also
* ingres_query() - Send an SQL query to Ingres
* ingres_fetch_array() - Fetch a row of result into an array
* ingres_fetch_assoc() - Fetch a row of result into an associative array
* ingres_fetch_object() - Fetch a row of result into an object
* ingres_fetch_row() - Fetch a row of result into an enumerated array
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_field_scale
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)
ingres_field_scale - Get the scale of a field
Description
int ingres_field_scale ( resource $result , int $index )
ingres_field_scale() returns the scale of a field. This value is used only
for the decimal SQL data type. For detailed information, see the Ingres
OpenAPI User Guide, Appendix "Data Types" in the Ingres documentation.
Note: Related Configurations
See ingres.array_index_start in Runtime Configuration
Parameters
result
The query result identifier
index
index is the field whose scale will be retrieved.
The possible values of index depend upon the value of
ingres.array_index_start. If ingres.array_index_start is 1 (the
default) then index must be between 1 and the value returned by
ingres_num_fields(). If ingres.array_index_start is 0 then index
must be between 0 and ingres_num_fields() - 1.
Return Values
Returns the scale of the field, as an integer
See Also
* ingres_query() - Send an SQL query to Ingres
* ingres_fetch_array() - Fetch a row of result into an array
* ingres_fetch_assoc() - Fetch a row of result into an associative array
* ingres_fetch_object() - Fetch a row of result into an object
* ingres_fetch_row() - Fetch a row of result into an enumerated array
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_field_type
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)
ingres_field_type - Get the type of a field in a query result
Description
string ingres_field_type ( resource $result , int $index )
Get the type of a field in a query result.
Note: Related Configurations
See ingres.array_index_start in Runtime Configuration
Parameters
result
The query result identifier
index
index is the field whose type will be retrieved.
The possible values of index depend upon the value of
ingres.array_index_start. If ingres.array_index_start is 1 (the
default) then index must be between 1 and the value returned by
ingres_num_fields(). If ingres.array_index_start is 0 then index
must be between 0 and ingres_num_fields() - 1.
Return Values
ingres_field_type() returns the type of a field in a query result or FALSE
on failure. Examples of types returned are IIAPI_BYTE_TYPE,
IIAPI_CHA_TYPE, IIAPI_DTE_TYPE, IIAPI_FLT_TYPE, IIAPI_INT_TYPE,
IIAPI_VCH_TYPE. Some of these types can map to more than one SQL type
depending on the length of the field (see ingres_field_length()). For
example IIAPI_FLT_TYPE can be a float4 or a float8. For detailed
information, see the Ingres OpenAPI User Guide, Appendix "Data Types" in
the Ingres documentation.
See Also
* ingres_query() - Send an SQL query to Ingres
* ingres_fetch_array() - Fetch a row of result into an array
* ingres_fetch_assoc() - Fetch a row of result into an associative array
* ingres_fetch_object() - Fetch a row of result into an object
* ingres_fetch_row() - Fetch a row of result into an enumerated array
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_free_result
(PECL ingres >= 2.0.0)
ingres_free_result - Free the resources associated with a result
identifier
Description
bool ingres_free_result ( resource $result )
Parameters
result
The query result identifier
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Free a result resource
See Also
* ingres_query() - Send an SQL query to Ingres
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_next_error
(PECL ingres >= 2.0.0)
ingres_next_error - Get the next Ingres error
Description
bool ingres_next_error ([ resource $link ] )
Get the next Ingres error for the last executed query. Each call to
ingres_next_error() can be followed by a call to ingres_errno(),
ingres_error() or ingres_errsqlstate() to get the respective error number,
error text, or SQL STATE. While ingres_next_error() returns TRUE, there
are more errors to fetch.
Parameters
link
The connection link identifier
Return Values
ingres_next_error() returns TRUE if there is another error to retrieve or
FALSE when there are no more errors
See Also
* ingres_errno() - Get the last Ingres error number generated
* ingres_error() - Get a meaningful error message for the last error
generated
* ingres_errsqlstate() - Get the last SQLSTATE error code generated
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_num_fields
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)
ingres_num_fields - Get the number of fields returned by the last query
Description
int ingres_num_fields ( resource $result )
ingres_num_fields() returns the number of fields in the results returned
by the Ingres server after a call to ingres_query().
Parameters
result
The query result identifier
Return Values
Returns the number of fields
See Also
* ingres_query() - Send an SQL query to Ingres
* ingres_fetch_array() - Fetch a row of result into an array
* ingres_fetch_assoc() - Fetch a row of result into an associative array
* ingres_fetch_object() - Fetch a row of result into an object
* ingres_fetch_row() - Fetch a row of result into an enumerated array
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_num_rows
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)
ingres_num_rows - Get the number of rows affected or returned by a query
Description
int ingres_num_rows ( resource $result )
This function primarily is meant to get the number of rows modified in the
database. However, it can be used to retrieve the number of rows to fetch
for a SELECT statement.
Note:
If scrollable cursors are disabled and this function is called before
using ingres_fetch_array(), ingres_fetch_object(), or
ingres_fetch_row(), the server will delete the result's data and the
script will be unable to get them.
Instead, you should retrieve the result's data using one of these fetch
functions in a loop until it returns FALSE, indicating that no more
results are available.
Parameters
result
The result identifier for a query
Return Values
For delete, insert, or update queries, ingres_num_rows() returns the
number of rows affected by the query. For other queries, ingres_num_rows()
returns the number of rows in the query's result.
See Also
* ingres_query() - Send an SQL query to Ingres
* ingres_fetch_array() - Fetch a row of result into an array
* ingres_fetch_assoc() - Fetch a row of result into an associative array
* ingres_fetch_object() - Fetch a row of result into an object
* ingres_fetch_row() - Fetch a row of result into an enumerated array
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_pconnect
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)
ingres_pconnect - Open a persistent connection to an Ingres database
Description
resource ingres_pconnect ([ string $database [, string $username [, string
$password [, array $options ]]]] )
Open a persistent connection to an Ingres database.
There are only two differences between this function and ingres_connect():
First, when connecting, the function will initially try to find a
(persistent) link that is already opened with the same parameters. If one
is found, an identifier for it will be returned instead of opening a new
connection. Second, the connection to the Ingres server will not be closed
when the execution of the script ends. Instead, the link will remain open
for future use (ingres_close() will not close links established by
ingres_pconnect()). This type of link is therefore called "persistent".
Parameters
database
The database name. Must follow the syntax:
[vnode::]dbname[/svr_class]
username
The Ingres user name
password
The password associated with username
options
See ingres_connect() for the list of options that can be passed
Return Values
Returns an Ingres link resource on success or FALSE on failure
See Also
* ingres_connect() - Open a connection to an Ingres database
* ingres_close() - Close an Ingres database connection
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_prepare
(PECL ingres >= 1.1.0)
ingres_prepare - Prepare a query for later execution
Description
mixed ingres_prepare ( resource $link , string $query )
Prepares a query for execution by ingres_execute().
The query becomes part of the currently open transaction. If there is no
open transaction, ingres_query() opens a new transaction. To close the
transaction, you can call either ingres_commit() to commit the changes
made to the database or ingres_rollback() to cancel these changes. When
the script ends, any open transaction is rolled back (by calling
ingres_rollback()). You can also use ingres_autocommit() before opening a
new transaction to have every SQL query immediately committed.
Note: Related Configurations
See also the ingres.describe, ingres.scrollable and ingres.utf8
directives in Runtime Configuration.
Parameters
link
The connection link identifier
query
A valid SQL query (see the Ingres SQL reference guide) in the
Ingres documentation. See the query parameter in ingres_query()
for a list of SQL statements which cannot be executed using
ingres_prepare()
Return Values
ingres_prepare() returns a query result identifier that is used with
ingres_execute() to execute the query. To see if an error occurred, use
ingres_errno(), ingres_error(), or ingres_errsqlstate().
See Also
* ingres_unbuffered_query() - Send an unbuffered SQL query to Ingres
* ingres_fetch_array() - Fetch a row of result into an array
* ingres_fetch_assoc() - Fetch a row of result into an associative array
* ingres_fetch_object() - Fetch a row of result into an object
* ingres_fetch_row() - Fetch a row of result into an enumerated array
* ingres_commit() - Commit a transaction
* ingres_rollback() - Roll back a transaction
* ingres_autocommit() - Switch autocommit on or off
* ingres_set_environment() - Set environment features controlling output
options
* ingres_errno() - Get the last Ingres error number generated
* ingres_error() - Get a meaningful error message for the last error
generated
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_query
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)
ingres_query - Send an SQL query to Ingres
Description
mixed ingres_query ( resource $link , string $query [, array $params [,
string $types ]] )
ingres_query() sends the given query to the Ingres server.
The query becomes part of the currently open transaction. If there is no
open transaction, ingres_query() opens a new transaction. To close the
transaction, you can call either ingres_commit() to commit the changes
made to the database or ingres_rollback() to cancel these changes. When
the script ends, any open transaction is rolled back (by calling
ingres_rollback()). You can also use ingres_autocommit() before opening a
new transaction to have every SQL query immediately committed.
Note: Related Configurations
See also the ingres.describe, ingres.scrollable and ingres.utf8
directives in Runtime Configuration
Parameters
link
The connection link identifier.
query
A valid SQL query (see the Ingres SQL reference guide) in the
Ingres documentation.
Data inside the query should be properly escaped.
The following types of SQL queries cannot be sent with this
function:
* close (see ingres_close())
* commit (see ingres_commit())
* connect (see ingres_connect())
* disconnect (see ingres_close())
* get dbevent
* prepare to commit
* rollback (see ingres_rollback())
* savepoint
* set autocommit (see ingres_autocommit())
* all cursor-related queries are unsupported
params
An array of parameter values to be used with the query
types
A string containing a sequence of types for the parameter values
passed. When ingres.describe is enabled, this parameter can be
ignored as the driver automatically fetches the expected parameter
types from the server.
Type code Ingres type
a BOOLEAN
b BYTE
B LONG BYTE/BLOB
c CHAR
d DATE/ANSIDATE/TIMESTAMP/TIME
f FLOAT
i INTEGER
L LONG TEXT
m MONEY
M LONG NVARCHAR
n NCHAR
N NVARCHAR
t TEXT
v VARCHAR
V LONG VARCHAR
Return Values
ingres_query() returns a query result identifier on success else it
returns FALSE. To see if an error occurred use ingres_errno(),
ingres_error() or ingres_errsqlstate().
Examples
Example #1 Send a simple select
Example #2 Passing query parameters to ingres_query()
Example #3 Inserting a BLOB with parameter types
See Also
* ingres_unbuffered_query() - Send an unbuffered SQL query to Ingres
* ingres_fetch_array() - Fetch a row of result into an array
* ingres_fetch_assoc() - Fetch a row of result into an associative array
* ingres_fetch_object() - Fetch a row of result into an object
* ingres_fetch_row() - Fetch a row of result into an enumerated array
* ingres_commit() - Commit a transaction
* ingres_rollback() - Roll back a transaction
* ingres_autocommit() - Switch autocommit on or off
* ingres_set_environment() - Set environment features controlling output
options
* ingres_errno() - Get the last Ingres error number generated
* ingres_error() - Get a meaningful error message for the last error
generated
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_result_seek
(PECL ingres >= 2.1.0)
ingres_result_seek - Set the row position before fetching data
Description
bool ingres_result_seek ( resource $result , int $position )
This function is used to position the cursor associated with the result
resource before issuing a fetch. If ingres.array_index_start is set to 0
then the first row is 0 else it is 1. ingres_result_seek() can be used
only with queries that make use of scrollable cursors. It cannot be used
with ingres_unbuffered_query().
Note: Related Configurations
See also the ingres.scrollable and ingres.array_index_start directives
in Runtime Configuration.
Parameters
result
The result identifier for a query
position
The row to position the cursor on. If ingres.array_index_start is
set to 0, then the first row is 0, else it is 1
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Position the cursor on the 3rd row
ap_iatacode . " - " . $airport->ap_name . "\n";
}
}
ingres_commit($link);
?>
See Also
* ingres_query() - Send an SQL query to Ingres
* ingres_fetch_array() - Fetch a row of result into an array
* ingres_fetch_assoc() - Fetch a row of result into an associative array
* ingres_fetch_object() - Fetch a row of result into an object
* ingres_fetch_row() - Fetch a row of result into an enumerated array
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_rollback
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)
ingres_rollback - Roll back a transaction
Description
bool ingres_rollback ( resource $link )
ingres_rollback() rolls back the currently open transaction, actually
cancelling all changes made to the database during the transaction.
This closes the transaction. A new transaction can be opened by sending a
query with ingres_query().
Parameters
link
The connection link identifier
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ingres_query() - Send an SQL query to Ingres
* ingres_commit() - Commit a transaction
* ingres_autocommit() - Switch autocommit on or off
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_set_environment
(PECL ingres >= 1.2.0)
ingres_set_environment - Set environment features controlling output
options
Description
bool ingres_set_environment ( resource $link , array $options )
ingres_set_environment() is called to set environmental options that
affect the output of certain values from Ingres, such as the timezone,
date format, decimal character separator, and float precision.
Parameters
link
The connection link identifier
options
An enumerated array of option name/value pairs. The following
table lists the option name and the expected type
Option name Option Description Example
type
date_century_boundary integer The threshold by which a 50
2-digit year is determined to
be in the current century or
in the next century.
Equivalent to
II_DATE_CENTURY_BOUNDARY
timezone string Controls the timezone of the UNITED-KINGDOM
session. If not set, it will
default the value defined by
II_TIMEZONE_NAME. If
II_TIMEZONE_NAME is not
defined, NA-PACIFIC (GMT-8
with Daylight Savings) is
used.
date_format integer Sets the allowable input and INGRES_DATE_ISO4
output format for Ingres
dates. Defaults to the value
defined by II_DATE_FORMAT. If
II_DATE_FORMAT is not set, the
default date format is US, for
example mm/dd/yy. Valid values
for date_format are:
* INGRES_DATE_DMY
* INGRES_DATE_FINISH
* INGRES_DATE_GERMAN
* INGRES_DATE_ISO
* INGRES_DATE_ISO4
* INGRES_DATE_MDY
* INGRES_DATE_MULTINATIONAL
* INGRES_DATE_MULTINATIONAL4
* INGRES_DATE_YMD
* INGRES_DATE_US
decimal_separator string The character identifier for ","
decimal data
money_lort integer Leading or trailing currency INGRES_MONEY_LEADING
sign. Valid values for
money_lort are:
* INGRES_MONEY_LEADING
* INGRES_MONEY_TRAILING
money_sign string The currency symbol to be used EUR
with the MONEY datatype
money_precision integer The precision of the MONEY 2
datatype
float4_precision integer Precision of the FLOAT4 10
datatype
float8_precision integer Precision of the FLOAT8 data 10
blob_segment_length integer The amount of data in bytes to 8192
fetch at a time when
retrieving BLOB or CLOB data.
Defaults to 4096 bytes when
not set explicitly
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Set date_format to ISO4
INGRES_DATE_ISO4 );
if (ingres_set_environment($link, $options))
{
$result=ingres_query($link,"select date('now') as date");
while ( $object = ingres_fetch_object ($result) ) {
echo $object->date."\n";
}
}
?>
Example #2 Set timezone to HONG-KONG
"HONG-KONG");
if (ingres_set_environment($link, $options))
{
$result=ingres_query($link,"select date('now') as date");
while ( $object = ingres_fetch_object ($result) ) {
echo $object->date."\n";
}
}
?>
See Also
* ingres_connect() - Open a connection to an Ingres database
* ingres_query() - Send an SQL query to Ingres
----------------------------------------------------------------------
----------------------------------------------------------------------
ingres_unbuffered_query
(No version information available, might only be in SVN)
ingres_unbuffered_query - Send an unbuffered SQL query to Ingres
Description
mixed ingres_unbuffered_query ( resource $link , string $query [, array
$params [, string $types ]] )
ingres_unbuffered_query() sends the given query to the Ingres server.
The query becomes part of the currently open transaction. If there is no
open transaction, ingres_unbuffered_query() opens a new transaction. To
close the transaction, you can call either ingres_commit() to commit the
changes made to the database or ingres_rollback() to cancel these changes.
When the script ends, any open transaction is rolled back (by calling
ingres_rollback()). You can also use ingres_autocommit() before opening a
new transaction to have every SQL query immediately committed. Ingres
allows only a single unbuffered statement to be active at any one time.
The extension will close any active unbuffered statements before executing
any SQL. In addition you cannot use ingres_result_seek() to position the
row before fetching.
Note: Related Configurations
See also the ingres.describe and ingres.utf8 directives in Runtime
Configuration.
Parameters
link
The connection link identifier
query
A valid SQL query (see the Ingres SQL reference guide) in the
Ingres documentation. See the query parameter in ingres_query()
for a list of SQL statements that cannot be executed via
ingres_unbuffered_query().
Data inside the query should be properly escaped.
params
An array of parameter values to be used with the query
types
A string containing a sequence of types for the parameter values
passed. See the types parameter in ingres_query() for the list of
type codes.
Return Values
ingres_unbuffered_query() returns a query result identifier when there are
rows to fetch; else it returns FALSE when there are no rows, as is the
case of an INSERT, UPDATE, or DELETE statement. To see if an error
occurred, use ingres_errno(), ingres_error(), or ingres_errsqlstate().
Examples
Example #1 Issue a simple un-buffered select
Example #2 Passing query parameters to ingres_unbuffered_query()
Example #3 Inserting a BLOB with parameter types
See Also
* ingres_query() - Send an SQL query to Ingres
* ingres_fetch_array() - Fetch a row of result into an array
* ingres_fetch_assoc() - Fetch a row of result into an associative array
* ingres_fetch_object() - Fetch a row of result into an object
* ingres_fetch_row() - Fetch a row of result into an enumerated array
* ingres_commit() - Commit a transaction
* ingres_rollback() - Roll back a transaction
* ingres_autocommit() - Switch autocommit on or off
* ingres_set_environment() - Set environment features controlling output
options
* ingres_errno() - Get the last Ingres error number generated
* ingres_error() - Get a meaningful error message for the last error
generated
----------------------------------------------------------------------
Table of Contents
* ingres_autocommit_state - Test if the connection is using autocommit
* ingres_autocommit - Switch autocommit on or off
* ingres_charset - Returns the installation character set
* ingres_close - Close an Ingres database connection
* ingres_commit - Commit a transaction
* ingres_connect - Open a connection to an Ingres database
* ingres_cursor - Get a cursor name for a given result resource
* ingres_errno - Get the last Ingres error number generated
* ingres_error - Get a meaningful error message for the last error
generated
* ingres_errsqlstate - Get the last SQLSTATE error code generated
* ingres_escape_string - Escape special characters for use in a query
* ingres_execute - Execute a prepared query
* ingres_fetch_array - Fetch a row of result into an array
* ingres_fetch_assoc - Fetch a row of result into an associative array
* ingres_fetch_object - Fetch a row of result into an object
* ingres_fetch_proc_return - Get the return value from a procedure call
* ingres_fetch_row - Fetch a row of result into an enumerated array
* ingres_field_length - Get the length of a field
* ingres_field_name - Get the name of a field in a query result
* ingres_field_nullable - Test if a field is nullable
* ingres_field_precision - Get the precision of a field
* ingres_field_scale - Get the scale of a field
* ingres_field_type - Get the type of a field in a query result
* ingres_free_result - Free the resources associated with a result
identifier
* ingres_next_error - Get the next Ingres error
* ingres_num_fields - Get the number of fields returned by the last
query
* ingres_num_rows - Get the number of rows affected or returned by a
query
* ingres_pconnect - Open a persistent connection to an Ingres database
* ingres_prepare - Prepare a query for later execution
* ingres_query - Send an SQL query to Ingres
* ingres_result_seek - Set the row position before fetching data
* ingres_rollback - Roll back a transaction
* ingres_set_environment - Set environment features controlling output
options
* ingres_unbuffered_query - Send an unbuffered SQL query to Ingres
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* Basic usage
* Ingres Functions
* ingres_autocommit_state - Test if the connection is using
autocommit
* ingres_autocommit - Switch autocommit on or off
* ingres_charset - Returns the installation character set
* ingres_close - Close an Ingres database connection
* ingres_commit - Commit a transaction
* ingres_connect - Open a connection to an Ingres database
* ingres_cursor - Get a cursor name for a given result resource
* ingres_errno - Get the last Ingres error number generated
* ingres_error - Get a meaningful error message for the last error
generated
* ingres_errsqlstate - Get the last SQLSTATE error code generated
* ingres_escape_string - Escape special characters for use in a
query
* ingres_execute - Execute a prepared query
* ingres_fetch_array - Fetch a row of result into an array
* ingres_fetch_assoc - Fetch a row of result into an associative
array
* ingres_fetch_object - Fetch a row of result into an object
* ingres_fetch_proc_return - Get the return value from a procedure
call
* ingres_fetch_row - Fetch a row of result into an enumerated array
* ingres_field_length - Get the length of a field
* ingres_field_name - Get the name of a field in a query result
* ingres_field_nullable - Test if a field is nullable
* ingres_field_precision - Get the precision of a field
* ingres_field_scale - Get the scale of a field
* ingres_field_type - Get the type of a field in a query result
* ingres_free_result - Free the resources associated with a result
identifier
* ingres_next_error - Get the next Ingres error
* ingres_num_fields - Get the number of fields returned by the last
query
* ingres_num_rows - Get the number of rows affected or returned by
a query
* ingres_pconnect - Open a persistent connection to an Ingres
database
* ingres_prepare - Prepare a query for later execution
* ingres_query - Send an SQL query to Ingres
* ingres_result_seek - Set the row position before fetching data
* ingres_rollback - Roll back a transaction
* ingres_set_environment - Set environment features controlling
output options
* ingres_unbuffered_query - Send an unbuffered SQL query to Ingres
----------------------------------------------------------------------
----------------------------------------------------------------------
MaxDB
----------------------------------------------------------------------
Introduction
The MaxDB PHP extension allows you to access the functionality provided by
MaxDB 7.5.0 and above. More information about the MaxDB Database server
can be found at >> http://www.sdn.sap.com/irj/sdn/maxdb.
The MaxDB PHP extension is compatible to the MySQL mysqli extension. There
are only minor differences in the behaviour of some functions due to the
differences of the underlying database servers, MaxDB and MySQL.
The main differences to mysqli are in the following functions:
* maxdb_character_set_name() - Returns only ascii or unicode.
* maxdb_get_client_info() - Returns a different version string.
* maxdb_get_client_version() - Returns a different version string.
* maxdb_get_host_info() - Returns localhost or hostname.
* maxdb_get_server_info() - Returns a different version string.
* maxdb_get_server_version() - Returns a different version string.
* maxdb_kill() - Only disconnects the session.
* maxdb_multi_query() - Can not handle multiple SQL statements.
* maxdb_next_result() - Function returns always false.
* maxdb_options() - Supports a different set of options.
* maxdb_report() - Supports a different report mode.
* maxdb_stat() - Returns a different system status string.
* maxdb_stmt_store_result() - Is not necessary for MaxDB.
* maxdb_store_result() - Is not necessary for MaxDB.
Documentation for MaxDB can be found at
>> http://maxdb.sap.com/documentation/.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
In order to have these functions available, you must compile PHP with
MaxDB support. Additionally, you must have the MaxDB SQLDBC runtime
library available to access the MaxDB server.
Documentation for MaxDB SQLDBC can be found at
>> http://maxdb.sap.com/documentation/.
Download the MaxDB SQLDBC package from
>> http://www.sdn.sap.com/irj/sdn/maxdb-downloads.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
By using the --with-maxdb[=DIR] configuration option you enable PHP to
access MaxDB databases. [DIR] points to the directory that contains the
installed MaxDB SQLDBC package.
Windows users will need to enable php_maxdb.dll inside of php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
MaxDB Configuration Options
Name Default Changeable Changelog
maxdb.default_host NULL PHP_INI_ALL
maxdb.default_db NULL PHP_INI_ALL
maxdb.default_user NULL PHP_INI_ALL
maxdb.default_pw NULL PHP_INI_ALL
maxdb.long_readlen "200" PHP_INI_ALL
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
maxdb.default_host string
The default server host to use when connecting to the database
server if no other host is specified.
maxdb.default_db string
The default server database to use when connecting if no other
database is specified.
maxdb.default_user string
The default user name to use when connecting to the database
server if no other name is specified.
maxdb.default_pw string
The default password to use when connecting to the database server
if no other password is specified.
maxdb.long_readlen integer
The default maximum length of bytes that is transferred to the
client if long data is retrieved from the MaxDB database server.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension defines resources.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
The following constants to use with maxdb_options() are defined. For
further description of these constants see
>> http://maxdb.sap.com/documentation/.
MaxDB PHP client constants
Constant Description
MAXDB_COMPNAME The component name used to initialise the SQLDBC
runtime environment.
MAXDB_APPLICATION The application to be connected to the database.
MAXDB_APPVERSION The version of the application.
MAXDB_SQLMODE The SQL mode.
MAXDB_UNICODE TRUE, if the connection is an unicode (UCS2)
client or FALSE, if not.
The maximum allowed time of inactivity after
MAXDB_TIMEOUT which the connection to the database is closed by
the system.
Specifies whether and how shared locks and
MAXDB_ISOLATIONLEVEL exclusive locks are implicitly requested or
released.
MAXDB_PACKETCOUNT The number of different request packets used for
the connection.
MAXDB_STATEMENTCACHESIZE The number of prepared statements to be cached
for the connection for re-use.
MAXDB_CURSORPREFIX The prefix to use for result tables that are
automatically named.
The function maxdb_fetch_array() uses a constant for the different types
of result arrays. The following constants are defined:
MaxDB fetch constants
Constant Description
MAXDB_ASSOC Columns are returned into the array having the fieldname
as the array index.
MAXDB_ASSOC_UPPER Columns are returned into the array having the upper
case fieldname as the array index.
MAXDB_ASSOC_LOWER Columns are returned into the array having the lower
case fieldname as the array index.
MAXDB_BOTH Columns are returned into the array having both a
numerical index and the fieldname as the array index.
Columns are returned into the array having a numerical
MAXDB_NUM index to the fields. This index starts with 0, the first
field in the result.
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Table of Contents
* Basic usage
----------------------------------------------------------------------
Basic usage
All examples in the MaxDB PHP documentation use the HOTELDB demo database
from MaxDB. More about this database can be found at
>> http://maxdb.sap.com/doc/7_7/44/d8c25164bb38d0e10000000a1553f7/content.htm.
To use the examples in the MaxDB PHP documentation, you have to load the
tutorial data into your database. Then you have to set maxdb.default_db in
php.ini to the database that contains the tutorial data.
This simple example shows how to connect, execute a query, print resulting
rows and disconnect from a MaxDB database.
Example #1 MaxDB extension overview example
\n";
while ($line = maxdb_fetch_array($result, MAXDB_ASSOC)) {
echo " \n";
foreach ($line as $col_value) {
echo " $col_value \n";
}
echo " \n";
}
echo "
\n";
/* Free resultset */
maxdb_free_result($result);
/* Closing connection */
maxdb_close($link);
?>
The following example shows how to bind variables to a SELECT INTO
statement.
Example #2 Example for use of SELECT INTO statements
The following example shows how to use MaxDB database procedures.
Example #3 Example fore using database procedures
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
MaxDB Functions
Predefined Classes
maxdb
Represents a connection between PHP and a MaxDB database.
Constructor
* maxdb - construct a new maxdb object
Methods
* autocommit - turns on or off auto-commiting database modifications
* change_user - changes the user of the specified database connection
* character_set_name - returns the default character set for the
database connection
* close - closes a previously opened connection
* commit - commits the current transaction
* connect - opens a new connection to MaxDB database server
* debug - performs debugging operations
* dump_debug_info - dumps debug information
* get_client_info - returns client version
* get_host_info - returns type of connection used
* get_server_info - returns version of the MaxDB server
* get_server_version - returns version of the MaxDB server
* init - initializes maxdb object
* info - retrieves information about the most recently executed query
* kill - asks the server to kill a MaxDB thread
* multi_query - performs multiple queries
* more_results - check if more results exist from currently executed
multi-query
* next_result - reads next result from currently executed multi-query
* options - set options
* ping - pings a server connection or reconnects if there is no
connection
* prepare - prepares an SQL query
* query - performs a query
* real_connect - attempts to open a connection to MaxDB database server
* escape_string - escapes special characters in a string for use in an
SQL statement, taking into account the current charset of the
connection
* rollback - rolls back the current transaction
* select_db - selects the default database
* ssl_set - sets ssl parameters
* stat - gets the current system status
* stmt_init- initializes a statement for use with maxdb_stmt_prepare
* store_result - transfers a resultset from last query
* use_result - transfers an unbuffered resultset from last query
* thread-safe - returns whether thread safety is given or not
Properties
* affected_rows - gets the number of affected rows in a previous MaxDB
operation
* client_info - returns the MaxDB client version as a string
* client_version - returns the MaxDB client version as an integer
* errno - returns the error code for the most recent function call
* error - returns the error string for the most recent function call
* field_count - returns the number of columns for the most recent query
* host_info - returns a string representing the type of connection used
* info - retrieves information about the most recently executed query
* insert_id - returns the auto generated id used in the last query
* protocol_version - returns the version of the MaxDB protocol used
* sqlstate - returns a string containing the SQLSTATE error code for the
last error
* thread_id - returns the thread ID for the current connection
* warning_count - returns the number of warnings generated during
execution of the previous SQL statement
maxdb_stmt
Represents a prepared statement.
Methods
* bind_param - binds variables to a prepared statement
* bind_result - binds variables to a prepared statement for result
storage
* close - closes a prepared statement
* data-seek - seeks to an arbitrary row in a statement result set
* execute - executes a prepared statement
* fetch - fetches result from a prepared statement into bound variables
* free_result - frees stored result memory for the given statement
handle
* result_metadata - retrieves a resultset from a prepared statement for
metadata information
* prepare - prepares an SQL query
* send_long_data - sends data in chunks
* close_long_data - end sending long data
* reset - resets a prepared statement
* store_result - buffers complete resultset from a prepared statement
Properties
* affected_rows - returns affected rows from last statement execution
* errno - returns errorcode for last statement function
* errno - returns errormessage for last statement function
* param_count - returns number of parameter for a given prepare
statement
* sqlstate - returns a string containing the SQLSTATE error code for the
last statement function
maxdb_result
Represents the result set obtained from a query against the database.
Methods
* close - closes resultset
* data_seek - moves internal result pointer
* fetch_field - gets column information from a resultset
* fetch_fields - gets information for all columns from a resulset
* fetch_field_direct - gets column information for specified column
* fetch_array - fetches a result row as an associative array, a numeric
array, or both.
* fetch_assoc - fetches a result row as an associative array
* fetch_object - fetches a result row as an object
* fetch_row - gets a result row as an enumerated array
* close - frees result memory
* field_seek - set result pointer to a specified field offset
Properties
* current_field - returns offset of current fieldpointer
* field_count - returns number of fields in resultset
* lengths - returns an array of columnlengths
* num_rows - returns number of rows in resultset
----------------------------------------------------------------------
maxdb_affected_rows
maxdb->affected_rows
(PECL maxdb >= 1.0)
maxdb_affected_rows -- maxdb->affected_rows - Gets the number of affected
rows in a previous MaxDB operation
Description
Procedural style
int maxdb_affected_rows ( resource $link )
Object oriented style
int $maxdb->affected_rows;
maxdb_affected_rows() returns the number of rows affected by the last
INSERT, UPDATE, or DELETE query associated with the provided link
parameter. If this number cannot be determined, this function will return
-1.
Note:
For SELECT statements maxdb_affected_rows() works like maxdb_num_rows().
The maxdb_affected_rows() function only works with queries which modify a
table. In order to return the number of rows from a SELECT query, use the
maxdb_num_rows() function instead.
Return Values
An integer greater than zero indicates the number of rows affected or
retrieved. Zero indicates that no records where updated for an UPDATE
statement, no rows matched the WHERE clause in the query or that no query
has yet been executed. -1 indicates that the number of rows affected can
not be determined.
Examples
Example #1 Object oriented style
query("DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);
/* Insert rows */
$maxdb->query("CREATE TABLE mycustomer AS SELECT * from hotel.customer");
printf("Affected rows (INSERT): %d\n", $maxdb->affected_rows);
$maxdb->query("ALTER TABLE mycustomer ADD Status int default 0");
/* update rows */
$maxdb->query("UPDATE mycustomer SET Status=1 WHERE cno > 50");
printf("Affected rows (UPDATE): %d\n", $maxdb->affected_rows);
/* delete rows */
$maxdb->query("DELETE FROM mycustomer WHERE cno < 50");
printf("Affected rows (DELETE): %d\n", $maxdb->affected_rows);
/* select all rows */
$result = $maxdb->query("SELECT title FROM mycustomer");
printf("Affected rows (SELECT): %d\n", $maxdb->affected_rows);
$result->close();
/* Delete table Language */
$maxdb->query("DROP TABLE mycustomer");
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
50");
printf("Affected rows (UPDATE): %d\n", maxdb_affected_rows($link));
/* delete rows */
maxdb_query($link, "DELETE FROM mycustomer WHERE cno < 50");
printf("Affected rows (DELETE): %d\n", maxdb_affected_rows($link));
/* select all rows */
$result = maxdb_query($link, "SELECT title FROM mycustomer");
printf("Affected rows (SELECT): %d\n", maxdb_affected_rows($link));
maxdb_free_result($result);
/* Delete table Language */
maxdb_query($link, "DROP TABLE mycustomer");
/* close connection */
maxdb_close($link);
?>
The above example will output something similar to:
Affected rows (INSERT): 15
Affected rows (UPDATE): 15
Affected rows (DELETE): 0
Affected rows (SELECT): 15
See Also
* maxdb_num_rows() - Gets the number of rows in a result
* maxdb_info() - Retrieves information about the most recently executed
query
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_autocommit
maxdb::auto_commit
(PECL maxdb >= 1.0)
maxdb_autocommit -- maxdb::auto_commit - Turns on or off auto-commiting
database modifications
Description
Procedural style
bool maxdb_autocommit ( resource $link , bool $mode )
Object oriented style
bool maxdb::auto_commit ( bool $mode )
maxdb_autocommit() is used to turn on or off auto-commit mode on queries
for the database connection represented by the link resource.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Object oriented style
autocommit(TRUE);
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
See Also
* maxdb_commit() - Commits the current transaction
* maxdb_rollback() - Rolls back current transaction
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_bind_param
(PECL maxdb 1.0)
maxdb_bind_param - Alias of maxdb_stmt_bind_param()
Description
This function is an alias of: maxdb_stmt_bind_param()
This function alias is deprecated and only exists for backwards
compatibility reasons. The use of this function is not recommended, as it
may be removed from PHP in the future.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_bind_result
(PECL maxdb 1.0)
maxdb_bind_result - Alias of maxdb_stmt_bind_result()
Description
This function is an alias of: maxdb_stmt_bind_result().
This function alias is deprecated and only exists for backwards
compatibility reasons. The use of this function is not recommended, as it
may be removed from PHP in the future.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_change_user
maxdb::change_user
(PECL maxdb >= 1.0)
maxdb_change_user -- maxdb::change_user - Changes the user of the
specified database connection
Description
Procedural style
bool maxdb_change_user ( resource $link , string $user , string $password
, string $database )
Object oriented style
bool maxdb::change_user ( string $user , string $password , string
$database )
maxdb_change_user() is used to change the user of the specified database
connection as given by the link parameter and to set the current database
to that specified by the database parameter.
In order to successfully change users a valid username and password
parameters must be provided and that user must have sufficient permissions
to access the desired database. If for any reason authorization fails, the
current user authentication will remain.
Note:
Using this command will always cause the current database connection to
behave as if was a completely new database connection, regardless of if
the operation was completed successfully. This reset includes performing
a rollback on any active transactions, closing all temporary tables, and
unlocking all locked tables.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Object oriented style
query("SELECT * FROM dual")) {
$row = $result->fetch_row();
printf("Result: %s\n", $row[0]);
$result->free();
}
/* reset all and select a new database */
if (!$maxdb->change_user("DBADMIN", "SECRET", "DEMODB")) {
printf("Database not running\n");
} else {
printf("Database running\n");
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Result: a
Database running
See Also
* maxdb_connect() - Open a new connection to the MaxDB server
* maxdb_select_db() - Selects the default database for database queries
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_character_set_name
maxdb::character_set_name
(PECL maxdb >= 1.0)
maxdb_character_set_name -- maxdb::character_set_name - Returns the
default character set for the database connection
Description
Procedural style
string maxdb_character_set_name ( resource $link )
Object oriented style
string maxdb::character_set_name ( void )
Returns the current character set for the database connection specified by
the link parameter.
Return Values
The default character set for the current connection, either ascii or
unicode.
Examples
Example #1 Object oriented style
character_set_name();
printf ("Current character set is %s\n", $charset);
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Current character set is ascii
See Also
* maxdb_client_encoding() - Alias of maxdb_character_set_name
* maxdb_real_escape_string() - Escapes special characters in a string
for use in an SQL statement, taking into account the current charset
of the connection
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_client_encoding
(PECL maxdb 1.0)
maxdb_client_encoding - Alias of maxdb_character_set_name()
Description
This function is an alias of: maxdb_character_set_name().
This function alias is deprecated and only exists for backwards
compatibility reasons. The use of this function is not recommended, as it
may be removed from PHP in the future.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_close_long_data
maxdb->close_long_data
(PECL maxdb >= 1.0)
maxdb_close_long_data -- maxdb->close_long_data - Alias of
maxdb_stmt_close_long_data()
Description
This function is an alias of: maxdb_stmt_close_long_data().
This function alias is deprecated and only exists for backwards
compatibility reasons. The use of this function is not recommended, as it
may be removed from PHP in the future.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_close
maxdb::close
(PECL maxdb >= 1.0)
maxdb_close -- maxdb::close - Closes a previously opened database
connection
Description
Procedural style
bool maxdb_close ( resource $link )
Object oriented style
bool maxdb::close ( void )
The maxdb_close() function closes a previously opened database connection
specified by the link parameter.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* maxdb_connect() - Open a new connection to the MaxDB server
* maxdb_init() - Initializes MaxDB and returns an resource for use with
maxdb_real_connect
* maxdb_real_connect() - Opens a connection to a MaxDB server
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_commit
maxdb::commit
(PECL maxdb >= 1.0)
maxdb_commit -- maxdb::commit - Commits the current transaction
Description
Procedural style
bool maxdb_commit ( resource $link )
Object oriented style
bool maxdb::commit ( void )
Commits the current transaction for the database connection specified by
the link parameter.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Object oriented style
autocommit(FALSE);
maxdb_report (MAXDB_REPORT_OFF);
$maxdb->query("DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);
$maxdb->query("CREATE TABLE mycustomer LIKE hotel.customer");
/* Insert some values */
$maxdb->query("INSERT INTO mycustomer VALUES (3000,'Mrs','Jenny','Porter','10580','1340 N.Ash Street, #3')");
$maxdb->query("INSERT INTO mycustomer VALUES (3100,'Mr','Peter','Brown','48226','1001 34th Str., APT.3')");
/* commit transaction */
$maxdb->commit();
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above examples produces no output.
See Also
* maxdb_autocommit() - Turns on or off auto-commiting database
modifications
* maxdb_rollback() - Rolls back current transaction
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_connect_errno
(PECL maxdb >= 1.0)
maxdb_connect_errno - Returns the error code from last connect call
Description
int maxdb_connect_errno ( void )
The maxdb_connect_errno() function will return the last error code number
for last call to maxdb_connect(). If no errors have occured, this function
will return zero.
Return Values
An error code value for the last call to maxdb_connect(), if it failed.
zero means no error occurred.
Examples
Example #1 maxdb_connect_errno sample
The above example will output something similar to:
PHP Warning: maxdb_connect(): -4008 POS(1) Unknown user name/password combination [08004] <...>
Can't connect to localhost. Errorcode: -4008
See Also
* maxdb_connect() - Open a new connection to the MaxDB server
* maxdb_connect_error() - Returns a string description of the last
connect error
* maxdb_errno() - Returns the error code for the most recent function
call
* maxdb_error() - Returns a string description of the last error
* maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB
operation
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_connect_error
(PECL maxdb >= 1.0)
maxdb_connect_error - Returns a string description of the last connect
error
Description
string maxdb_connect_error ( void )
The maxdb_connect_error() function is identical to the corresponding
maxdb_connect_errno() function in every way, except instead of returning
an integer error code the maxdb_connect_error() function will return a
string representation of the last error to occur for the last
maxdb_connect() call. If no error has occured, this function will return
an empty string.
Return Values
A string that describes the error. An empty string if no error occurred.
Examples
Example #1 maxdb_connect_error sample
The above example will output something similar to:
PHP Warning: maxdb_connect(): -4008 POS(1) Unknown user name/password combination <...>
Can't connect to localhost. Error: POS(1) Unknown user name/password combination
See Also
* maxdb_connect() - Open a new connection to the MaxDB server
* maxdb_connect_errno() - Returns the error code from last connect call
* maxdb_errno() - Returns the error code for the most recent function
call
* maxdb_error() - Returns a string description of the last error
* maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB
operation
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_connect
maxdb::__construct
(PECL maxdb >= 1.0)
maxdb_connect -- maxdb::__construct - Open a new connection to the MaxDB
server
Description
Procedural style
resource maxdb_connect ([ string $host [, string $username [, string
$passwd [, string $dbname [, int $port = 0 [, string $socket ]]]]]] )
Object oriented style
maxdb::__construct() ([ string $host [, string $username [, string $passwd
[, string $dbname [, int $port = 0 [, string $socket ]]]]]] )
The maxdb_connect() function attempts to open a connection to the MaxDB
Server running on host which can be either a host name or an IP address.
Passing the string "localhost" to this parameter, the local host is
assumed. If successful, the maxdb_connect() will return an resource
representing the connection to the database or FALSE on failure.
The username and password parameters specify the username and password
under which to connect to the MaxDB server. If the password is not
provided (the NULL value is passed), the MaxDB server will attempt to
authenticate the user against the maxdb.default_pw in php.ini.
The dbname parameter if provided will specify the default database to be
used when performing queries. If not provied, the entry maxdb.default_db
in php.ini is used.
The port and socket parameters are ignored for the MaxDB server.
Return Values
Returns a resource which represents the connection to a MaxDB Server or
FALSE if the connection failed.
Examples
Example #1 Object oriented style
host_info);
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Host information: localhost
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_data_seek
maxdb_result::data_seek
(PECL maxdb >= 1.0)
maxdb_data_seek -- maxdb_result::data_seek - Adjusts the result pointer to
an arbitary row in the result
Description
Procedural style
bool maxdb_data_seek ( resource $result , int $offset )
Object oriented style
bool maxdb_result::data_seek ( int $offset )
The maxdb_data_seek() function seeks to an arbitrary result pointer
specified by the offset in the result set represented by result. The
offset parameter must be between zero and the total number of rows minus
one (0..maxdb_num_rows() - 1).
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Object oriented style
query( $query)) {
/* seek to row no. 10 */
$result->data_seek(10);
/* fetch row */
$row = $result->fetch_row();
printf ("City: %s State: %s\n", $row[0], $row[1]);
/* free result set*/
$result->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
City: Irvine State: CA
See Also
* maxdb_store_result() - Transfers a result set from the last query
* maxdb_fetch_row() - Get a result row as an enumerated array
* maxdb_num_rows() - Gets the number of rows in a result
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_debug
(PECL maxdb >= 1.0)
maxdb_debug - Performs debugging operations
Description
void maxdb_debug ( string $debug )
The maxdb_debug() can be used to trace the SQLDBC communication. The
following strings can be used as a parameter to maxdb_debug():
* TRACE SHORT ON|OFF - Enables/disables method call trace.
* TRACE LONG ON|OFF - Enables/disables method argument and detail debug
trace.
* TRACE PACKET ON|OFF| - Enables/disables packet trace, limiting
the size of the traced object to the specified number of bytes, or
1000 if no size is specified.
* TRACE SQL ON|OFF - Enables/disables high level api trace.
* TRACE TIMESTAMP ON|OFF - Enables/disables a timestamp prefix on each
line that is traced.
* TRACE SIZE - Limits the size of the trace file to bytes,
at least 8192 bytes are required.
Return Values
maxdb_debug() doesn't return any value.
Examples
Example #1 Procedural style
The above example produces no output.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_disable_reads_from_master
maxdb::disable_reads_from_master
(PECL maxdb >= 1.0)
maxdb_disable_reads_from_master -- maxdb::disable_reads_from_master -
Disable reads from master
Description
Procedural style
bool maxdb_disable_reads_from_master ( resource $link )
Object oriented style
void maxdb::disable_reads_from_master ( void )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_disable_rpl_parse
(PECL maxdb >= 1.0)
maxdb_disable_rpl_parse - Disable RPL parse
Description
bool maxdb_disable_rpl_parse ( resource $link )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_dump_debug_info
(PECL maxdb >= 1.0)
maxdb_dump_debug_info - Dump debugging information into the log
Description
bool maxdb_dump_debug_info ( resource $link )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_embedded_connect
(PECL maxdb >= 1.0)
maxdb_embedded_connect - Open a connection to an embedded MaxDB server
Description
resource maxdb_embedded_connect ([ string $dbname ] )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_enable_reads_from_master
(PECL maxdb >= 1.0)
maxdb_enable_reads_from_master - Enable reads from master
Description
bool maxdb_enable_reads_from_master ( resource $link )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_enable_rpl_parse
(PECL maxdb >= 1.0)
maxdb_enable_rpl_parse - Enable RPL parse
Description
bool maxdb_enable_rpl_parse ( resource $link )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_errno
maxdb->errno
(PECL maxdb >= 1.0)
maxdb_errno -- maxdb->errno - Returns the error code for the most recent
function call
Description
Procedural style
int maxdb_errno ( resource $link )
Object oriented style
int $maxdb->errno;
The maxdb_errno() function will return the last error code for the most
recent MaxDB function call that can succeed or fail with respect to the
database link defined by the link parameter. If no errors have occured,
this function will return zero.
Return Values
An error code value for the last call, if it failed. zero means no error
occurred.
Examples
Example #1 Object oriented style
query("SELECT xxx FROM hotel.city")) {
printf("Errorcode: %d\n", $maxdb->errno);
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
PHP Warning: maxdb_query(): -4005 POS(8) Unknown column name:XXX [42000] <...>
Errorcode: -4005
See Also
* maxdb_connect_errno() - Returns the error code from last connect call
* maxdb_connect_error() - Returns a string description of the last
connect error
* maxdb_error() - Returns a string description of the last error
* maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB
operation
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_error
maxdb->error
(PECL maxdb >= 1.0)
maxdb_error -- maxdb->error - Returns a string description of the last
error
Description
Procedural style
string maxdb_error ( resource $link )
Object oriented style
string $maxdb->error;
The maxdb_error() function is identical to the corresponding maxdb_errno()
function in every way, except instead of returning an integer error code
the maxdb_error() function will return a string representation of the last
error to occur for the database connection represented by the link
parameter. If no error has occured, this function will return an empty
string.
Return Values
A string that describes the error. An empty string if no error occurred.
Examples
Example #1 Object oriented style
query("SELECT xxx FROM hotel.city")) {
printf("Errormessage: %s\n", $maxdb->error);
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
PHP Warning: maxdb_query(): -4005 POS(8) Unknown column name:XXX [42000]
Errormessgae: POS(8) Unknown column name:XXX
See Also
* maxdb_connect_errno() - Returns the error code from last connect call
* maxdb_connect_error() - Returns a string description of the last
connect error
* maxdb_errno() - Returns the error code for the most recent function
call
* maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB
operation
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_escape_string
(PECL maxdb 1.0)
maxdb_escape_string - Alias of maxdb_real_escape_string()
Description
This function is an alias of: maxdb_real_escape_string().
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_execute
(PECL maxdb 1.0)
maxdb_execute - Alias of maxdb_stmt_execute()
Description
This function is an alias of: maxdb_stmt_execute().
This function alias is deprecated and only exists for backwards
compatibility reasons. The use of this function is not recommended, as it
may be removed from PHP in the future.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_fetch_array
maxdb_result::fetch_array
(PECL maxdb >= 1.0)
maxdb_fetch_array -- maxdb_result::fetch_array - Fetch a result row as an
associative, a numeric array, or both
Description
Procedural style
mixed maxdb_fetch_array ( resource $result [, int $resulttype ] )
Object oriented style
mixed maxdb_result::fetch_array ([ int $resulttype ] )
Returns an array that corresponds to the fetched row or NULL if there are
no more rows for the resultset represented by the result parameter.
maxdb_fetch_array() is an extended version of the maxdb_fetch_row()
function. In addition to storing the data in the numeric indices of the
result array, the maxdb_fetch_array() function can also store the data in
associative indices, using the field names of the result set as keys.
Note: Field names returned by this function are case-sensitive.
Note: This function sets NULL fields to the PHP NULL value.
If two or more columns of the result have the same field names, the last
column will take precedence and overwrite the earlier data. In order to
access multiple columns with the same name, the numerically indexed
version of the row must be used.
The optional second argument resulttype is a constant indicating what type
of array should be produced from the current row data. The possible values
for this parameter are the constants MAXDB_ASSOC, MAXDB_ASSOC_UPPER,
MAXDB_ASSOC_LOWER, MAXDB_NUM, or MAXDB_BOTH. By default the
maxdb_fetch_array() function will assume MAXDB_BOTH, which is a
combination of MAXDB_NUM and MAXDB_ASSOC for this parameter.
By using the MAXDB_ASSOC constant this function will behave identically to
the maxdb_fetch_assoc(), while MAXDB_NUM will behave identically to the
maxdb_fetch_row() function. The final option MAXDB_BOTH will create a
single array with the attributes of both.
By using the MAXDB_ASSOC_UPPER constant, the behaviour of this function is
identical to the use of MAXDB_ASSOC except the array index of a column is
the fieldname in upper case.
By using the MAXDB_ASSOC_LOWER constant, the behaviour of this function is
identical to the use of MAXDB_ASSOC except the array index of a column is
the fieldname in lower case.
Return Values
Returns an array that corresponds to the fetched row or NULL if there are
no more rows in resultset.
Examples
Example #1 Object oriented style
query($query);
/* numeric array */
$row = $result->fetch_array(MAXDB_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);
/* associative array */
$row = $result->fetch_array(MAXDB_ASSOC);
printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);
/* associative and numeric array */
$row = $result->fetch_array(MAXDB_BOTH);
printf ("%s (%s)\n", $row[0], $row["STATE"]);
/* free result set */
$result->close();
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
New York (NY)
New York (NY)
Long Island (NY)
See Also
* maxdb_fetch_assoc() - Fetch a result row as an associative array
* maxdb_fetch_row() - Get a result row as an enumerated array
* maxdb_fetch_resource()
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_fetch_assoc
maxdb_result::fetch_assoc
(PECL maxdb >= 1.0)
maxdb_fetch_assoc -- maxdb_result::fetch_assoc - Fetch a result row as an
associative array
Description
Procedural style
array maxdb_fetch_assoc ( resource $result )
Object oriented style
array maxdb_result::fetch_assoc ( void )
Returns an associative array that corresponds to the fetched row or NULL
if there are no more rows.
The maxdb_fetch_assoc() function is used to return an associative array
representing the next row in the result set for the result represented by
the result parameter, where each key in the array represents the name of
one of the result set's columns.
If two or more columns of the result have the same field names, the last
column will take precedence. To access the other column(s) of the same
name, you either need to access the result with numeric indices by using
maxdb_fetch_row() or add alias names.
Note: Field names returned by this function are case-sensitive.
Note: This function sets NULL fields to the PHP NULL value.
Return Values
Returns an array that corresponds to the fetched row or NULL if there are
no more rows in resultset.
Examples
Example #1 Object oriented style
query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);
}
/* free result set */
$result->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
New York (NY)
New York (NY)
Long Island (NY)
Albany (NY)
Washington (DC)
Washington (DC)
Washington (DC)
Silver Spring (MD)
Daytona Beach (FL)
Deerfield Beach (FL)
Clearwater (FL)
Cincinnati (OH)
Detroit (MI)
Rosemont (IL)
Chicago (IL)
Chicago (IL)
New Orleans (LA)
Dallas (TX)
Los Angeles (CA)
Hollywood (CA)
Long Beach (CA)
Palm Springs (CA)
Irvine (CA)
Santa Clara (CA)
Portland (OR)
See Also
* maxdb_fetch_array() - Fetch a result row as an associative, a numeric
array, or both
* maxdb_fetch_row() - Get a result row as an enumerated array
* maxdb_fetch_resource()
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_fetch_field_direct
maxdb_result::fetch_field_direct
(PECL maxdb >= 1.0)
maxdb_fetch_field_direct -- maxdb_result::fetch_field_direct - Fetch
meta-data for a single field
Description
Procedural style
mixed maxdb_fetch_field_direct ( resource $result , int $fieldnr )
Object oriented style
mixed maxdb_result::fetch_field_direct ( int $fieldnr )
maxdb_fetch_field_direct() returns an resource which contains field
definition information from specified resultset. The value of fieldnr must
be in the range from 0 to number of fields - 1.
Return Values
Returns an resource which contains field definition information or FALSE
if no field information for specified fieldnr is available.
Object attributes
Attribute Description
name The name of the column
max_length The maximum width of the field for the result set.
type The data type used for this field
decimals The number of decimals used (for integer fields)
Examples
Example #1 Object oriented style
query($query)) {
/* Get field information for column 'SurfaceArea' */
$finfo = $result->fetch_field_direct(1);
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n", $finfo->type);
$result->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n", $finfo->type);
maxdb_free_result($result);
}
/* close connection */
maxdb_close($link);
?>
The above example will output something similar to:
Name: CNO
Table:
max. Len: 4
Flags: -1
Type: 0
See Also
* maxdb_num_fields() - Get the number of fields in a result
* maxdb_fetch_field() - Returns the next field in the result set
* maxdb_fetch_fields() - Returns an array of resources representing the
fields in a result set
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_fetch_field
maxdb_result::fetch_field
(PECL maxdb >= 1.0)
maxdb_fetch_field -- maxdb_result::fetch_field - Returns the next field in
the result set
Description
Procedural style
mixed maxdb_fetch_field ( resource $result )
Object oriented style
mixed maxdb_result::fetch_field ( void )
The maxdb_fetch_field() returns the definition of one column of a result
set as an resource. Call this function repeatedly to retrieve information
about all columns in the result set. maxdb_fetch_field() returns FALSE
when no more fields are left.
Return Values
Returns an resource which contains field definition information or FALSE
if no field information is available.
Object properties
Property Description
name The name of the column
max_length The maximum width of the field for the result set.
type The data type used for this field
decimals The number of decimals used (for integer fields)
Examples
Example #1 Object oriented style
query($query)) {
/* Get field information for all columns */
while ($finfo = $result->fetch_field()) {
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
$result->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
maxdb_free_result($result);
}
/* close connection */
maxdb_close($link);
?>
The above example will output something similar to:
Name: NAME
Table:
max. Len: 10
Flags: -1
Type: 2
Name: CNO
Table:
max. Len: 4
Flags: -1
Type: 0
See Also
* maxdb_num_fields() - Get the number of fields in a result
* maxdb_fetch_field_direct() - Fetch meta-data for a single field
* maxdb_fetch_fields() - Returns an array of resources representing the
fields in a result set
* maxdb_field_seek() - Set result pointer to a specified field offset
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_fetch_fields
maxdb_result::fetch_fields
(PECL maxdb >= 1.0)
maxdb_fetch_fields -- maxdb_result::fetch_fields - Returns an array of
resources representing the fields in a result set
Description
Procedural style
mixed maxdb_fetch_fields ( resource $result )
Object oriented style
mixed maxdb_result::fetch_fields ( void )
This function serves an identical purpose to the maxdb_fetch_field()
function with the single difference that, instead of returning one
resource at a time for each field, the columns are returned as an array of
resources.
Return Values
Returns an array of resources which contains field definition information
or FALSE if no field information is available.
Object properties
Property Description
name The name of the column
max_length The maximum width of the field for the result set.
type The data type used for this field
decimals The number of decimals used (for integer fields)
Examples
Example #1 Object oriented style
query($query)) {
/* Get field information for all columns */
$finfo = $result->fetch_fields();
foreach ($finfo as $val) {
printf("Name: %s\n", $val->name);
printf("Table: %s\n", $val->table);
printf("max. Len: %d\n", $val->max_length);
printf("Flags: %d\n", $val->flags);
printf("Type: %d\n\n", $val->type);
}
$result->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
name);
printf("Table: %s\n", $val->table);
printf("max. Len: %d\n", $val->max_length);
printf("Flags: %d\n", $val->flags);
printf("Type: %d\n\n", $val->type);
}
maxdb_free_result($result);
}
/* close connection */
maxdb_close($link);
?>
The above example will output something similar to:
Name: NAME
Table:
max. Len: 10
Flags: -1
Type: 2
Name: CNO
Table:
max. Len: 4
Flags: -1
Type: 0
See Also
* maxdb_num_fields() - Get the number of fields in a result
* maxdb_fetch_field() - Returns the next field in the result set
* maxdb_fetch_field_direct() - Fetch meta-data for a single field
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_fetch_lengths
maxdb_result->lengths
(PECL maxdb >= 1.0)
maxdb_fetch_lengths -- maxdb_result->lengths - Returns the lengths of the
columns of the current row in the result set
Description
Procedural style
array maxdb_fetch_lengths ( resource $result )
Object oriented style
array $maxdb_result->lengths;
The maxdb_fetch_lengths() function returns an array containing the lengths
of every column of the current row within the result set represented by
the result parameter. If successful, a numerically indexed array
representing the lengths of each column is returned or FALSE on failure.
Return Values
An array of integers representing the size of each column (not including
any terminating null characters). FALSE if an error occurred.
maxdb_fetch_lengths() is valid only for the current row of the result set.
It returns FALSE if you call it before calling
maxdb_fetch_row/array/resource or after retrieving all rows in the result.
Examples
Example #1 Object oriented style
query($query)) {
$row = $result->fetch_row();
/* display column lengths */
foreach ($result->lengths as $i => $val) {
printf("Field %2d has Length %2d\n", $i+1, $val);
}
$result->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
$val) {
printf("Field %2d has Length %2d\n", $i+1, $val);
}
maxdb_free_result($result);
}
/* close connection */
maxdb_close($link);
?>
The above example will output something similar to:
Field 1 has Length 4
Field 2 has Length 3
Field 3 has Length 5
Field 4 has Length 6
Field 5 has Length 5
Field 6 has Length 21
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_fetch_object
maxdb_result::fetch_object
(PECL maxdb >= 1.0)
maxdb_fetch_object -- maxdb_result::fetch_object - Returns the current row
of a result set as an object
Description
Procedural style
object maxdb_fetch_object ( object $result )
Object oriented style
object maxdb_result::fetch_object ( void )
The maxdb_fetch_object() will return the current row result set as an
object where the attributes of the object represent the names of the
fields found within the result set. If no more rows exist in the current
result set, NULL is returned.
Return Values
Returns an object that corresponds to the fetched row or NULL if there are
no more rows in resultset.
Note: Field names returned by this function are case-sensitive.
Note: This function sets NULL fields to the PHP NULL value.
Examples
Example #1 Object oriented style
query($query)) {
/* fetch object array */
while ($obj = $result->fetch_object()) {
printf ("%s (%s)\n", $obj->NAME, $obj->STATE);
}
/* free result set */
$result->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
NAME, $obj->STATE);
}
/* free result set */
maxdb_free_result($result);
}
/* close connection */
maxdb_close($link);
?>
The above example will output something similar to:
New York (NY)
New York (NY)
Long Island (NY)
Albany (NY)
Washington (DC)
Washington (DC)
Washington (DC)
Silver Spring (MD)
Daytona Beach (FL)
Deerfield Beach (FL)
Clearwater (FL)
Cincinnati (OH)
Detroit (MI)
Rosemont (IL)
Chicago (IL)
Chicago (IL)
New Orleans (LA)
Dallas (TX)
Los Angeles (CA)
Hollywood (CA)
Long Beach (CA)
Palm Springs (CA)
Irvine (CA)
Santa Clara (CA)
Portland (OR)
See Also
* maxdb_fetch_array() - Fetch a result row as an associative, a numeric
array, or both
* maxdb_fetch_assoc() - Fetch a result row as an associative array
* maxdb_fetch_row() - Get a result row as an enumerated array
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_fetch_row
maxdb_result::fetch_row
(PECL maxdb >= 1.0)
maxdb_fetch_row -- maxdb_result::fetch_row - Get a result row as an
enumerated array
Description
Procedural style
mixed maxdb_fetch_row ( resource $result )
Object oriented style
mixed maxdb_result::fetch_row ( void )
Returns an array that corresponds to the fetched row, or NULL if there are
no more rows.
maxdb_fetch_row() fetches one row of data from the result set represented
by result and returns it as an enumerated array, where each column is
stored in an array offset starting from 0 (zero). Each subsequent call to
the maxdb_fetch_row() function will return the next row within the result
set, or FALSE if there are no more rows.
Return Values
maxdb_fetch_row() returns an array that corresponds to the fetched row or
NULL if there are no more rows in result set.
Note: This function sets NULL fields to the PHP NULL value.
Examples
Example #1 Object oriented style
query($query)) {
/* fetch enumerated array */
while ($row = $result->fetch_row()) {
printf ("%s (%s)\n", $row[0], $row[1]);
}
/* free result set */
$result->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
New York (NY)
New York (NY)
Long Island (NY)
Albany (NY)
Washington (DC)
Washington (DC)
Washington (DC)
Silver Spring (MD)
Daytona Beach (FL)
Deerfield Beach (FL)
Clearwater (FL)
Cincinnati (OH)
Detroit (MI)
Rosemont (IL)
Chicago (IL)
Chicago (IL)
New Orleans (LA)
Dallas (TX)
Los Angeles (CA)
Hollywood (CA)
Long Beach (CA)
Palm Springs (CA)
Irvine (CA)
Santa Clara (CA)
Portland (OR)
See Also
* maxdb_fetch_array() - Fetch a result row as an associative, a numeric
array, or both
* maxdb_fetch_assoc() - Fetch a result row as an associative array
* maxdb_fetch_resource()
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_fetch
(PECL maxdb 1.0)
maxdb_fetch - Alias of maxdb_stmt_fetch()
Description
This function is an alias of: maxdb_stmt_fetch().
This function alias is deprecated and only exists for backwards
compatibility reasons. The use of this function is not recommended, as it
may be removed from PHP in the future.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_field_count
maxdb::field_count
(PECL maxdb >= 1.0)
maxdb_field_count -- maxdb::field_count - Returns the number of columns
for the most recent query
Description
Procedural style
int maxdb_field_count ( resource $link )
Object oriented style
int maxdb::field_count ( void )
Returns the number of columns for the most recent query on the connection
represented by the link parameter. This function can be useful when using
the maxdb_store_result() function to determine if the query should have
produced a non-empty result set or not without knowing the nature of the
query.
Return Values
An integer representing the number of fields in a result set.
Examples
Example #1 Object oriented style
query("DROP TABLE friends");
maxdb_report (MAXDB_REPORT_ERROR);
$maxdb->query( "CREATE TABLE friends (id int, name varchar(20))");
$maxdb->query( "INSERT INTO friends VALUES (1,'Hartmut')");
$maxdb->query( "INSERT INTO friends VALUES (2, 'Ulf')");
if ($maxdb->field_count()) {
/* this was a select/show or describe query */
$result = $maxdb->store_result();
/* process resultset */
$row = $result->fetch_row();
/* free resultset */
$result->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example produces no output.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_field_seek
maxdb_result::field_seek
(PECL maxdb >= 1.0)
maxdb_field_seek -- maxdb_result::field_seek - Set result pointer to a
specified field offset
Description
Procedural style
bool maxdb_field_seek ( resource $result , int $fieldnr )
Object oriented style
bool maxdb_result::field_seek ( int $fieldnr )
Sets the field cursor to the given offset. The next call to
maxdb_fetch_field() will retrieve the field definition of the column
associated with that offset.
Note:
To seek to the beginning of a row, pass an offset value of zero.
Return Values
maxdb_field_seek() returns previuos value of field cursor.
Examples
Example #1 Object oriented style
query($query)) {
/* Get field information for 2nd column */
$result->field_seek(1);
$finfo = $result->fetch_field();
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
$result->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
maxdb_free_result($result);
}
/* close connection */
maxdb_close($link);
?>
The above example will output something similar to:
Name: NAME
Table:
max. Len: 10
Flags: -1
Type: 2
See Also
* maxdb_fetch_field() - Returns the next field in the result set
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_field_tell
maxdb_result->current_field
(PECL maxdb >= 1.0)
maxdb_field_tell -- maxdb_result->current_field - Get current field offset
of a result pointer
Description
Procedural style
int maxdb_field_tell ( resource $result )
Object oriented style
int $maxdb_result->current_field;
Returns the position of the field cursor used for the last
maxdb_fetch_field() call. This value can be used as an argument to
maxdb_field_seek().
Return Values
Returns current offset of field cursor.
Examples
Example #1 Object oriented style
query($query)) {
/* Get field information for all columns */
while ($finfo = $result->fetch_field()) {
/* get fieldpointer offset */
$currentfield = $result->current_field;
printf("Column %d:\n", $currentfield);
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
$result->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
maxdb_free_result($result);
}
/* close connection */
maxdb_close($link);
?>
The above example will output something similar to:
Column 1:
Name: NAME
Table:
max. Len: 10
Flags: -1
Type: 2
Column 2:
Name: CNO
Table:
max. Len: 4
Flags: -1
Type: 0
See Also
* maxdb_fetch_field() - Returns the next field in the result set
* maxdb_field_seek() - Set result pointer to a specified field offset
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_free_result
maxdb_result::free
(PECL maxdb >= 1.0)
maxdb_free_result -- maxdb_result::free - Frees the memory associated with
a result
Description
Procedural style
void maxdb_free_result ( resource $result )
Object oriented style
void maxdb_result::free ( void )
The maxdb_free_result() function frees the memory associated with the
result represented by the result parameter, which was allocated by
maxdb_query(), maxdb_store_result() or maxdb_use_result().
Note:
You should always free your result with maxdb_free_result(), when your
result resource is not needed anymore.
Return Values
This function doesn't return any value.
See Also
* maxdb_query() - Performs a query on the database
* maxdb_stmt_store_result() - Transfers a result set from a prepared
statement
* maxdb_store_result() - Transfers a result set from the last query
* maxdb_use_result() - Initiate a result set retrieval
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_get_client_info
(PECL maxdb >= 1.0)
maxdb_get_client_info - Returns the MaxDB client version as a string
Description
string maxdb_get_client_info ( void )
The maxdb_get_client_info() function is used to return a string
representing the client version being used in the MaxDB extension.
Return Values
A string that represents the MaxDB client library version
Examples
Example #1 maxdb_get_client_info
The above example will output something similar to:
Client library version: libSQLDBC <...>
See Also
* maxdb_get_client_version() - Get MaxDB client info
* maxdb_get_server_info() - Returns the version of the MaxDB server
* maxdb_get_server_version() - Returns the version of the MaxDB server
as an integer
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_get_client_version
(PECL maxdb >= 1.0)
maxdb_get_client_version - Get MaxDB client info
Description
int maxdb_get_client_version ( void )
Returns client version number as an integer.
Return Values
A number that represents the MaxDB client library version in format:
main_version*10000 + minor_version *100 + sub_version. For example, 7.5.0
is returned as 70500.
This is useful to quickly determine the version of the client library to
know if some capability exists.
Examples
Example #1 maxdb_get_client_version
The above example will output something similar to:
Client library version: 7.<...>
See Also
* maxdb_get_client_info() - Returns the MaxDB client version as a string
* maxdb_get_server_info() - Returns the version of the MaxDB server
* maxdb_get_server_version() - Returns the version of the MaxDB server
as an integer
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_get_host_info
maxdb->get_host_info
(PECL maxdb >= 1.0)
maxdb_get_host_info -- maxdb->get_host_info - Returns a string
representing the type of connection used
Description
Procedural style
string maxdb_get_host_info ( resource $link )
Object oriented style
string $maxdb->host_info;
The maxdb_get_host_info() function returns a string describing the
connection represented by the link parameter is using.
Return Values
A character string representing the server hostname and the connection
type.
Examples
Example #1 Object oriented style
host_info);
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Host info: localhost
See Also
* maxdb_get_proto_info() - Returns the version of the MaxDB protocol
used
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_get_metadata
(PECL maxdb 1.0)
maxdb_get_metadata - Alias of maxdb_stmt_result_metadata()
Description
This function is an alias of: maxdb_stmt_result_metadata().
This function alias is deprecated and only exists for backwards
compatibility reasons. The use of this function is not recommended, as it
may be removed from PHP in the future.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_get_proto_info
maxdb->protocol_version
(PECL maxdb >= 1.0)
maxdb_get_proto_info -- maxdb->protocol_version - Returns the version of
the MaxDB protocol used
Description
Procedural style
int maxdb_get_proto_info ( resource $link )
Object oriented style
string $maxdb->protocol_version;
Returns an integer representing the MaxDB protocol version used by the
connection represented by the link parameter.
Return Values
Returns an integer representing the protocol version (constant 10).
Examples
Example #1 Object oriented style
protocol_version);
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Protocol version: 10
See Also
* maxdb_get_host_info() - Returns a string representing the type of
connection used
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_get_server_info
maxdb->server_info
(PECL maxdb >= 1.0)
maxdb_get_server_info -- maxdb->server_info - Returns the version of the
MaxDB server
Description
Procedural style
string maxdb_get_server_info ( resource $link )
Object oriented style
string $maxdb->server_info;
Returns a string representing the version of the MaxDB server that the
MaxDB extension is connected to (represented by the link parameter).
Return Values
A character string representing the server version.
Examples
Example #1 Object oriented style
server_info);
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Server version: Kernel 7<...>
See Also
* maxdb_get_client_info() - Returns the MaxDB client version as a string
* maxdb_get_client_version() - Get MaxDB client info
* maxdb_get_server_version() - Returns the version of the MaxDB server
as an integer
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_get_server_version
maxdb->server_version
(PECL maxdb >= 1.0)
maxdb_get_server_version -- maxdb->server_version - Returns the version of
the MaxDB server as an integer
Description
Procedural style
int maxdb_get_server_version ( resource $link )
Object oriented style
int $maxdb->server_version;
The maxdb_get_server_version() function returns the version of the server
connected to (represented by the link parameter) as an integer.
The form of this version number is main_version * 10000 + minor_version *
100 + sub_version (i.e. version 7.5.0 is 70500).
Return Values
An integer representing the server version.
Examples
Example #1 Object oriented style
server_version);
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Server version: 7<...>
See Also
* maxdb_get_client_info() - Returns the MaxDB client version as a string
* maxdb_get_client_version() - Get MaxDB client info
* maxdb_get_server_info() - Returns the version of the MaxDB server
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_info
maxdb->info
(PECL maxdb >= 1.0)
maxdb_info -- maxdb->info - Retrieves information about the most recently
executed query
Description
Procedural style
string maxdb_info ( resource $link )
Object oriented style
string $maxdb->info;
The maxdb_info() function returns a string providing information about the
last query executed. The nature of this string is provided below:
Possible maxdb_info return values
Query type Example result string
INSERT INTO...SELECT... Records: 100 Duplicates: 0
Warnings: 0
INSERT INTO...VALUES (...),(...),(...) Records: 3 Duplicates: 0 Warnings:
0
LOAD DATA INFILE ... Records: 1 Deleted: 0 Skipped: 0
Warnings: 0
ALTER TABLE ... Records: 3 Duplicates: 0 Warnings:
0
UPDATE ... Rows matched: 40 Changed: 40
Warnings: 0
Note:
Queries which do not fall into one of the above formats are not
supported. In these situations, maxdb_info() will return an empty
string.
Return Values
A character string representing additional information about the most
recently executed query.
Examples
Example #1 Object oriented style
query("CREATE TABLE temp.t1 LIKE hotel.city");
/* INSERT INTO .. SELECT */
$maxdb->query("INSERT INTO temp.t1 SELECT * FROM hotel.city");
printf("%s\n", $maxdb->info);
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Records: 25 Duplicates: 0 Warnings: 0
See Also
* maxdb_affected_rows() - Gets the number of affected rows in a previous
MaxDB operation
* maxdb_warning_count() - Returns the number of warnings from the last
query for the given link
* maxdb_num_rows() - Gets the number of rows in a result
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_init
(PECL maxdb >= 1.0)
maxdb_init - Initializes MaxDB and returns an resource for use with
maxdb_real_connect
Description
resource maxdb_init ( void )
Allocates or initializes a MaxDB resource suitable for maxdb_options() and
maxdb_real_connect().
Note:
Any subsequent calls to any maxdb function (except maxdb_options()) will
fail until maxdb_real_connect() was called.
Return Values
Returns an resource.
See Also
* maxdb_options() - Set options
* maxdb_close() - Closes a previously opened database connection
* maxdb_real_connect() - Opens a connection to a MaxDB server
* maxdb_connect() - Open a new connection to the MaxDB server
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_insert_id
maxdb->insert_id
(PECL maxdb >= 1.0)
maxdb_insert_id -- maxdb->insert_id - Returns the auto generated id used
in the last query
Description
Procedural style
mixed maxdb_insert_id ( resource $link )
Object oriented style
mixed $maxdb->insert_id;
The maxdb_insert_id() function returns the ID generated by a query on a
table with a column having the DEFAULT SERIAL attribute. If the last query
wasn't an INSERT or UPDATE statement or if the modified table does not
have a column with the DEFAULT SERIAL attribute, this function will return
zero.
Return Values
The value of the DEFAULT SERIAL field that was updated by the previous
query. Returns zero if there was no previous query on the connection or if
the query did not update an DEFAULT_SERIAL value.
Note:
If the number is greater than maximal int value, maxdb_insert_id() will
return a string.
Examples
Example #1 Object oriented style
query("DROP TABLE mycity");
maxdb_report (MAXDB_REPORT_ERROR);
$maxdb->query("CREATE TABLE mycity LIKE hotel.city");
$maxdb->query("ALTER TABLE mycity ADD id FIXED(11) DEFAULT SERIAL");
$query = "INSERT INTO mycity (zip,name,state) VALUES ('12203','Albany' ,'NY')";
$maxdb->query($query);
printf ("New Record has id %d.\n", $maxdb->insert_id);
/* drop table */
$maxdb->query("DROP TABLE mycity");
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
New Record has id 1.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_kill
maxdb::kill
(PECL maxdb >= 1.0)
maxdb_kill -- maxdb::kill - Disconnects from a MaxDB server
Description
Procedural style
bool maxdb_kill ( resource $link , int $processid )
Object oriented style
bool maxdb::kill ( int $processid )
This function is used to disconnect from a MaxDB server specified by the
processid parameter.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Object oriented style
thread_id;
/* Kill connection */
$maxdb->kill($thread_id);
/* This should produce an error */
if (!$maxdb->query("CREATE TABLE myCity LIKE City")) {
printf("Error: %s\n", $maxdb->error);
exit;
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Error: Session not connected
See Also
* maxdb_thread_id() - Returns the thread ID for the current connection
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_master_query
(PECL maxdb >= 1.0)
maxdb_master_query - Enforce execution of a query on the master in a
master/slave setup
Description
bool maxdb_master_query ( resource $link , string $query )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_more_results
maxdb->more_results
(PECL maxdb >= 1.0)
maxdb_more_results -- maxdb->more_results - Check if there any more query
results from a multi query
Description
bool maxdb_more_results ( resource $link )
maxdb_more_results() indicates if one or more result sets are available
from a previous call to maxdb_multi_query().
Return Values
Always FALSE.
Examples
See maxdb_multi_query().
See Also
* maxdb_multi_query() - Performs a query on the database
* maxdb_next_result() - Prepare next result from multi_query
* maxdb_store_result() - Transfers a result set from the last query
* maxdb_use_result() - Initiate a result set retrieval
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_multi_query
maxdb::multi_query
(PECL maxdb >= 1.0)
maxdb_multi_query -- maxdb::multi_query - Performs a query on the database
Description
Procedural style
bool maxdb_multi_query ( resource $link , string $query )
Object oriented style
bool maxdb::multi_query ( string $query )
The maxdb_multi_query() works like the function maxdb_query(). Multiple
queries are not yet supported.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Object oriented style
multi_query($query)) {
do {
/* store first result set */
if ($result = $maxdb->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->close();
}
/* print divider */
if ($maxdb->more_results()) {
printf("-----------------\n");
}
} while ($maxdb->next_result());
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
a
See Also
* maxdb_use_result() - Initiate a result set retrieval
* maxdb_store_result() - Transfers a result set from the last query
* maxdb_next_result() - Prepare next result from multi_query
* maxdb_more_results() - Check if there any more query results from a
multi query
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_next_result
maxdb->next_result
(PECL maxdb >= 1.0)
maxdb_next_result -- maxdb->next_result - Prepare next result from
multi_query
Description
bool maxdb_next_result ( resource $link )
Since multiple queries are not yet supported, maxdb_next_result() returns
always FALSE.
Return Values
Returns FALSE.
See Also
* maxdb_multi_query() - Performs a query on the database
* maxdb_more_results() - Check if there any more query results from a
multi query
* maxdb_store_result() - Transfers a result set from the last query
* maxdb_use_result() - Initiate a result set retrieval
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_num_fields
maxdb_result->field_count
(PECL maxdb >= 1.0)
maxdb_num_fields -- maxdb_result->field_count - Get the number of fields
in a result
Description
Procedural style
int maxdb_num_fields ( resource $result )
Object oriented style
int $maxdb_result->field_count;
maxdb_num_fields() returns the number of fields from specified result set.
Return Values
The number of fields from a result set
Examples
Example #1 Object oriented style
query("SELECT * FROM hotel.city ORDER BY zip")) {
/* determine number of fields in result set */
$field_cnt = $result->field_count;
printf("Result set has %d fields.\n", $field_cnt);
/* close result set */
$result->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Result set has 3 fields.
See Also
* maxdb_fetch_field() - Returns the next field in the result set
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_num_rows
maxdb->num_rows
(PECL maxdb >= 1.0)
maxdb_num_rows -- maxdb->num_rows - Gets the number of rows in a result
Description
Procedural style
int maxdb_num_rows ( resource $result )
Object oriented style
int $maxdb->num_rows;
Returns the number of rows in the result set.
The use of maxdb_num_rows() depends on whether you use buffered or
unbuffered result sets. In case you use unbuffered resultsets
maxdb_num_rows() will not correct the correct number of rows until all the
rows in the result have been retrieved.
Return Values
Returns number of rows in the result set.
Note:
If the number of rows is greater than maximal int value, the number will
be returned as a string.
Examples
Example #1 Object oriented style
query("SELECT cno, name FROM hotel.customer ORDER BY name")) {
/* determine number of rows result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
/* close result set */
$result->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Result set has 15 rows.
See Also
* maxdb_affected_rows() - Gets the number of affected rows in a previous
MaxDB operation
* maxdb_store_result() - Transfers a result set from the last query
* maxdb_use_result() - Initiate a result set retrieval
* maxdb_query() - Performs a query on the database
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_options
maxdb::options
(PECL maxdb >= 1.0)
maxdb_options -- maxdb::options - Set options
Description
Procedural style
bool maxdb_options ( resource $link , int $option , mixed $value )
Object oriented style
bool maxdb::options ( int $option , mixed $value )
maxdb_options() can be used to set extra connect options and affect
behavior for a connection.
This function may be called multiple times to set several options.
maxdb_options() should be called after maxdb_init() and before
maxdb_real_connect().
The parameter option is the option that you want to set, the value is the
value for the option. For detailed description of the options see
>> http://maxdb.sap.com/documentation/ The parameter option can be one of
the following values:
Valid options
Name Description
MAXDB_COMPNAME The component name used to initialise the SQLDBC
runtime environment.
MAXDB_APPLICATION The application to be connected to the database.
MAXDB_APPVERSION The version of the application.
MAXDB_SQLMODE The SQL mode.
MAXDB_UNICODE TRUE, if the connection is an unicode (UCS2)
client or FALSE, if not.
The maximum allowed time of inactivity after
MAXDB_TIMEOUT which the connection to the database is closed by
the system.
Specifies whether and how shared locks and
MAXDB_ISOLATIONLEVEL exclusive locks are implicitly requested or
released.
MAXDB_PACKETCOUNT The number of different request packets used for
the connection.
MAXDB_STATEMENTCACHESIZE The number of prepared statements to be cached
for the connection for re-use.
MAXDB_CURSORPREFIX The prefix to use for result tables that are
automatically named.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
See maxdb_real_connect().
See Also
* maxdb_init() - Initializes MaxDB and returns an resource for use with
maxdb_real_connect
* maxdb_real_connect() - Opens a connection to a MaxDB server
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_param_count
(PECL maxdb 1.0)
maxdb_param_count - Alias of maxdb_stmt_param_count()
Description
This function is an alias of: maxdb_stmt_param_count().
This function alias is deprecated and only exists for backwards
compatibility reasons. The use of this function is not recommended, as it
may be removed from PHP in the future.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_ping
maxdb::ping
(PECL maxdb >= 1.0)
maxdb_ping -- maxdb::ping - Pings a server connection, or tries to
reconnect if the connection has gone down
Description
Procedural style
bool maxdb_ping ( resource $link )
Object oriented style
bool maxdb::ping ( void )
Checks whether the connection to the server is working. If it has gone
down, and global option maxdb.reconnect is enabled an automatic
reconnection is attempted.
This function can be used by clients that remain idle for a long while, to
check whether the server has closed the connection and reconnect if
necessary.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Object oriented style
ping()) {
printf ("Our connection is ok!\n");
} else {
printf ("Error: %s\n", $maxdb->error);
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Our connection is ok!
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_prepare
maxdb::prepare
(PECL maxdb >= 1.0)
maxdb_prepare -- maxdb::prepare - Prepare an SQL statement for execution
Description
Procedural style
resource maxdb_prepare ( resource $link , string $query )
Object oriented style
maxdb_stmt maxdb::prepare ( string $query )
maxdb_prepare() prepares the SQL query pointed to by the null-terminated
string query, and returns a statement handle to be used for further
operations on the statement. The query must consist of a single SQL
statement.
Note:
You should not add a terminating semicolon or \g to the statement.
The parameter query can include one or more parameter markers in the SQL
statement by embedding question mark (?) characters at the appropriate
positions.
Note:
The markers are legal only in certain places in SQL statements. For
example, they are allowed in the VALUES() list of an INSERT statement
(to specify column values for a row), or in a comparison with a column
in a WHERE clause to specify a comparison value.
However, they are not allowed for identifiers (such as table or column
names), in the select list that names the columns to be returned by a
SELECT statement), or to specify both operands of a binary operator such
as the = equal sign. The latter restriction is necessary because it
would be impossible to determine the parameter type. In general,
parameters are legal only in Data Manipulation Languange (DML)
statements, and not in Data Defination Language (DDL) statements.
The parameter markers must be bound to application variables using
maxdb_stmt_bind_param() and/or maxdb_stmt_bind_result() before executing
the statement or fetching rows.
Return Values
maxdb_prepare() returns a statement resource or FALSE if an error occured.
Examples
Example #1 Object oriented style
prepare("SELECT state FROM hotel.city WHERE name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Rosemont is in district IL
See Also
* maxdb_stmt_execute() - Executes a prepared Query
* maxdb_stmt_fetch() - Fetch results from a prepared statement into the
bound variables
* maxdb_stmt_bind_param() - Binds variables to a prepared statement as
parameters
* maxdb_stmt_bind_result() - Binds variables to a prepared statement for
result storage
* maxdb_stmt_close() - Closes a prepared statement
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_query
maxdb::query
(PECL maxdb >= 1.0)
maxdb_query -- maxdb::query - Performs a query on the database
Description
Procedural style
mixed maxdb_query ( resource $link , string $query [, int $resultmode ] )
Object oriented style
mixed maxdb::query ( string $query )
The maxdb_query() function is used to simplify the act of performing a
query against the database represented by the link parameter.
Return Values
Returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or
EXPLAIN maxdb_query() will return a result resource.
Examples
Example #1 Object oriented style
query("CREATE TABLE temp.mycity LIKE hotel.city") === TRUE) {
printf("Table mycity successfully created.\n");
}
/* Select queries return a resultset */
if ($result = $maxdb->query("SELECT name FROM hotel.city")) {
printf("Select returned %d rows.\n", $result->num_rows);
/* free result set */
$result->close();
}
/* If we have to retrieve large amount of data we use MAXDB_USE_RESULT */
if ($result = $maxdb->query("SELECT * FROM hotel.city", MAXDB_USE_RESULT)) {
$result->close();
}
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Table mycity successfully created.
Select returned 25 rows.
See Also
* maxdb_real_query() - Execute an SQL query
* maxdb_multi_query() - Performs a query on the database
* maxdb_free_result() - Frees the memory associated with a result
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_real_connect
maxdb::real_connect
(PECL maxdb >= 1.0)
maxdb_real_connect -- maxdb::real_connect - Opens a connection to a MaxDB
server
Description
Procedural style
bool maxdb_real_connect ( resource $link [, string $hostname [, string
$username [, string $passwd [, string $dbname [, int $port = 0 [, string
$socket ]]]]]] )
Object oriented style
bool maxdb::real_connect ([ string $hostname [, string $username [, string
$passwd [, string $dbname [, int $port = 0 [, string $socket ]]]]]] )
maxdb_real_connect() attempts to establish a connection to a MaxDB
database engine running on hostname.
This function differs from maxdb_connect():
* maxdb_real_connect() needs a valid resource which has to be created by
function maxdb_init()
* With function maxdb_options() you can set various options for
connection.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Object oriented style
options(MAXDB_UNICODE, "FALSE");
$maxdb->options(MAXDB_TIMEOUT, 5);
/* connect to server */
$maxdb->real_connect('localhost', 'MONA', 'RED', 'DEMODB');
/* check connection */
if (maxdb_connect_errno()) {
printf("Connect failed: %s\n", maxdb_connect_error());
exit();
}
printf ("Connection: %s\n.", $maxdb->host_info);
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Connection: localhost <...>
See Also
* maxdb_connect() - Open a new connection to the MaxDB server
* maxdb_init() - Initializes MaxDB and returns an resource for use with
maxdb_real_connect
* maxdb_options() - Set options
* maxdb_ssl_set() - Used for establishing secure connections using SSL
* maxdb_close() - Closes a previously opened database connection
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_real_escape_string
maxdb::real_escape_string
(PECL maxdb >= 1.0)
maxdb_real_escape_string -- maxdb::real_escape_string - Escapes special
characters in a string for use in an SQL statement, taking into account
the current charset of the connection
Description
Procedural style
string maxdb_real_escape_string ( resource $link , string $escapestr )
Object oriented style
string maxdb::real_escape_sring ( string $escapestr )
This function is used to create a legal SQL string that you can use in an
SQL statement. The string escapestr is encoded to an escaped SQL string,
taking into account the current character set of the connection.
Characters encoded are ', ".
Return Values
Returns an escaped string.
Examples
Example #1 Object oriented style
query("CREATE TABLE temp.mycity LIKE hotel.city");
$city = "'s Hertogenbosch";
/* this query will fail, cause we didn't escape $city */
if (!$maxdb->query("INSERT into temp.mycity VALUES ('11111','$city','NY')")) {
printf("Error: %s\n", $maxdb->sqlstate);
}
$city = $maxdb->real_escape_string($city);
/* this query with escaped $city will work */
if ($maxdb->query("INSERT into temp.mycity VALUES ('22222','$city','NY')")) {
printf("%d Row inserted.\n", $maxdb->affected_rows);
}
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Warning: maxdb_query(): -5016 POS(43) Missing delimiter: ) <...>
Error: 42000
1 Row inserted.
See Also
* maxdb_character_set_name() - Returns the default character set for the
database connection
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_real_query
maxdb::real_query
(PECL maxdb >= 1.0)
maxdb_real_query -- maxdb::real_query - Execute an SQL query
Description
Procedural style
bool maxdb_real_query ( resource $link , string $query )
Object oriented style
bool maxdb::real_query ( string $query )
The maxdb_real_query() is functionally identical with the maxdb_query().
Note:
In order to determine if a given query should return a result set or
not, see maxdb_field_count().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* maxdb_query() - Performs a query on the database
* maxdb_store_result() - Transfers a result set from the last query
* maxdb_use_result() - Initiate a result set retrieval
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_report
(PECL maxdb 1.0)
maxdb_report - Enables or disables internal report functions
Description
bool maxdb_report ( int $flags )
Parameters
flags
One of the MAXDB_REPORT_XXX constants.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Procedural style
50000");
maxdb_close($link);
?>
The above example will output something similar to:
Warning: maxdb_query(): -4004 POS(18) Unknown table name:NONEXISTINGTABLE <...>
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_rollback
maxdb::rollback
(PECL maxdb >= 1.0)
maxdb_rollback -- maxdb::rollback - Rolls back current transaction
Description
Procedural style
bool maxdb_rollback ( resource $link )
Object oriented style
bool maxdb::rollback ( void )
Rollbacks the current transaction for the database specified by the link
parameter.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Object oriented style
autocommit(FALSE);
$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");
/* commit insert */
$maxdb->commit();
/* delete all rows */
$maxdb->query("DELETE FROM temp.mycity");
if ($result = $maxdb->query("SELECT COUNT(*) FROM temp.mycity")) {
$row = $result->fetch_row();
printf("%d rows in table mycity.\n", $row[0]);
/* Free result */
$result->close();
}
/* Rollback */
$maxdb->rollback();
if ($result = $maxdb->query("SELECT COUNT(*) FROM temp.mycity")) {
$row = $result->fetch_row();
printf("%d rows in table mycity (after rollback).\n", $row[0]);
/* Free result */
$result->close();
}
/* Drop table myCity */
$maxdb->query("DROP TABLE temp.mycity");
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
0 rows in table mycity.
25 rows in table mycity (after rollback).
See Also
* maxdb_commit() - Commits the current transaction
* maxdb_autocommit() - Turns on or off auto-commiting database
modifications
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_rpl_parse_enabled
(PECL maxdb >= 1.0)
maxdb_rpl_parse_enabled - Check if RPL parse is enabled
Description
int maxdb_rpl_parse_enabled ( resource $link )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_rpl_probe
(PECL maxdb >= 1.0)
maxdb_rpl_probe - RPL probe
Description
bool maxdb_rpl_probe ( resource $link )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_rpl_query_type
maxdb::rpl_query_type
(PECL maxdb >= 1.0)
maxdb_rpl_query_type -- maxdb::rpl_query_type - Returns RPL query type
Description
Procedural style
int maxdb_rpl_query_type ( resource $link )
Object oriented style
int maxdb::rpl_query_type ( void )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_select_db
maxdb->select_db
(PECL maxdb >= 1.0)
maxdb_select_db -- maxdb->select_db - Selects the default database for
database queries
Description
bool maxdb_select_db ( resource $link , string $dbname )
The maxdb_select_db() function selects the default database (specified by
the dbname parameter) to be used when performing queries against the
database connection represented by the link parameter.
Note:
This function should only be used to change the default database for the
connection. You can select the default database with 4th parameter in
maxdb_connect().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Object oriented style
query("SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
/* change db to non existing db */
$maxdb->select_db("XXXXXXXX");
/* return name of current default database */
if ($result = $maxdb->query("SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Default database is <...>.
Warning: maxdb_select_db(): -10709 Connection failed (RTE:database not running) <...>
Warning: maxdb_query(): -10821 Session not connected [] <...>
Warning: maxdb_close(): -10821 Session not connected [] <...>
See Also
* maxdb_connect() - Open a new connection to the MaxDB server
* maxdb_real_connect() - Opens a connection to a MaxDB server
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_send_long_data
(PECL maxdb >= 1.0)
maxdb_send_long_data - Alias of maxdb_stmt_send_long_data()
Description
This function is an alias of: maxdb_stmt_send_long_data().
This function alias is deprecated and only exists for backwards
compatibility reasons. The use of this function is not recommended, as it
may be removed from PHP in the future.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_send_query
maxdb::send_query
(PECL maxdb >= 1.0)
maxdb_send_query -- maxdb::send_query - Send the query and return
Description
Procedural style
bool maxdb_send_query ( resource $link , string $query )
Object oriented style
bool maxdb::send_query ( string $query )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_server_end
(PECL maxdb >= 1.0)
maxdb_server_end - Shut down the embedded server
Description
void maxdb_server_end ( void )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_server_init
(PECL maxdb >= 1.0)
maxdb_server_init - Initialize embedded server
Description
bool maxdb_server_init ([ array $server [, array $groups ]] )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_set_opt
(PECL maxdb 1.0)
maxdb_set_opt - Alias of maxdb_options()
Description
This function is an alias of: maxdb_options().
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_sqlstate
maxdb->sqlstate
(PECL maxdb >= 1.0)
maxdb_sqlstate -- maxdb->sqlstate - Returns the SQLSTATE error from
previous MaxDB operation
Description
Procedural style
string maxdb_sqlstate ( resource $link )
Object oriented style
string $maxdb->sqlstate;
Returns a string containing the SQLSTATE error code for the last error.
The error code consists of five characters. '00000' means no error. The
values are specified by ANSI SQL and ODBC.
Note:
Note that not all MaxDB errors are yet mapped to SQLSTATE's. The value
HY000 (general error) is used for unmapped errors.
Return Values
Returns a string containing the SQLSTATE error code for the last error.
The error code consists of five characters. '00000' means no error.
Examples
Example #1 Object oriented style
query("CREATE TABLE hotel.city (ID INT, Name VARCHAR(30))")) {
printf("Error - SQLSTATE %s.\n", $maxdb->sqlstate);
}
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Warning: maxdb_query(): -6000 POS(20) Duplicate table name:CITY [I6000] <...>
Error - SQLSTATE I6000.
See Also
* maxdb_errno() - Returns the error code for the most recent function
call
* maxdb_error() - Returns a string description of the last error
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_ssl_set
maxdb::ssl_set
(PECL maxdb >= 1.0)
maxdb_ssl_set -- maxdb::ssl_set - Used for establishing secure connections
using SSL
Description
Procedural style
bool maxdb_ssl_set ( resource $link , string $key , string $cert , string
$ca , string $capath , string $cipher )
Object oriented style
bool maxdb::ssl_set ( string $key , string $cert , string $ca , string
$capath , string $cipher )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_stat
maxdb::stat
(PECL maxdb >= 1.0)
maxdb_stat -- maxdb::stat - Gets the current system status
Description
Procedural style
string maxdb_stat ( resource $link )
Object oriented style
string maxdb::stat ( void )
maxdb_stat() returns a string containing several information about the
MaxDB server running.
Return Values
A string describing the server status. FALSE if an error occurred.
Examples
Example #1 Object oriented style
stat());
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
System status: Kernel 7<...>
See Also
* maxdb_get_server_info() - Returns the version of the MaxDB server
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_stmt_affected_rows
maxdb_stmt->affected_rows
(PECL maxdb >= 1.0)
maxdb_stmt_affected_rows -- maxdb_stmt->affected_rows - Returns the total
number of rows changed, deleted, or inserted by the last executed
statement
Description
Procedural style
int maxdb_stmt_affected_rows ( resource $stmt )
Object oriented style
int $maxdb_stmt->affected_rows;
maxdb_stmt_affected_rows() returns the number of rows affected by INSERT,
UPDATE, or DELETE query. If the last query was invalid or the number of
rows can not determined, this function will return -1.
Return Values
An integer greater than zero indicates the number of rows affected or
retrieved. Zero indicates that no records where updated for an
UPDATE/DELETE statement, no rows matched the WHERE clause in the query or
that no query has yet been executed. -1 indicates that the query has
returned an error or the number of rows can not determined.
Examples
Example #1 Object oriented style
query("CREATE TABLE temp.mycity LIKE hotel.city");
$query = "INSERT INTO temp.mycity SELECT * FROM hotel.city WHERE state LIKE ?";
/* prepare statement */
if ($stmt = $maxdb->prepare($query)) {
/* Bind variable for placeholder */
$code = 'N%';
$stmt->bind_param("s", $code);
/* execute statement */
$stmt->execute();
printf("rows inserted: %d\n", $stmt->affected_rows);
/* close statement */
$stmt->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
rows inserted: 4
See Also
* maxdb_stmt_num_rows() - Return the number of rows in statements result
set
* maxdb_prepare() - Prepare an SQL statement for execution
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_stmt_bind_param
maxdb_stmt::bind_param
(PECL maxdb >= 1.0)
maxdb_stmt_bind_param -- maxdb_stmt::bind_param - Binds variables to a
prepared statement as parameters
Description
Procedural style
bool maxdb_stmt_bind_param ( resource $stmt , string $types , mixed &$var1
[, mixed &$... ] )
Object oriented style
bool maxdb_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$...
] )
Procedural style (extended syntax):
bool maxdb_stmt_bind_param ( resource $stmt , string $types , array &$var
)
Object oriented style (extended syntax):
bool maxdb_stmt::bind_param ( string $types , array &$var )
maxdb_stmt_bind_param() is used to bind variables for the parameter
markers in the SQL statement that was passed to maxdb_prepare(). The
string types contains one or more characters which specify the types for
the corresponding bind variables.
The extended syntax of maxdb_stmt_bind_param() allows to give the
parameters as an array instead of a variable list of PHP variables to the
function. If the array variable has not been used before calling
maxdb_stmt_bind_param(), it has to be initialized as an emtpy array. See
the examples how to use maxdb_stmt_bind_param() with extended syntax.
Variables for SELECT INTO SQL statements can also be bound using
maxdb_stmt_bind_param(). Parameters for database procedures can be bound
using maxdb_stmt_bind_param(). See the examples how to use
maxdb_stmt_bind_param() in this cases.
If a variable bound as INTO variable to an SQL statement was used before,
the content of this variable is overwritten by the data of the SELECT INTO
statement. A reference to this variable will be invalid after a call to
maxdb_stmt_bind_param().
For INOUT parameters of database procedures the content of the bound INOUT
variable is overwritten by the output value of the database procedure. A
reference to this variable will be invalid after a call to
maxdb_stmt_bind_param().
Type specification chars
Character Description
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packages
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Object oriented style
query ("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query ("INSERT INTO temp.mycity SELECT * FROM hotel.city");
$stmt = $maxdb->prepare("INSERT INTO temp.mycity VALUES (?, ?, ?)");
$stmt->bind_param('sss', $zip, $name, $state);
$zip = '11111';
$name = 'Georgetown';
$state = 'NY';
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
/* Clean up table CountryLanguage */
$maxdb->query("DELETE FROM temp.mycity WHERE name='Georgetown'");
printf("%d Row deleted.\n", $maxdb->affected_rows);
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
1 Row inserted.
1 Row deleted.
Example #3 Procedural style (SELECT INTO)
The above example will output something similar to:
21.600000
Example #4 Procedural style (DB procedure)
The above example will output something similar to:
a
Example #5 Object oriented style (extended syntax)
query ("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query ("INSERT INTO temp.mycity SELECT * FROM hotel.city");
$stmt = $maxdb->prepare("INSERT INTO temp.mycity VALUES (?, ?, ?)");
$arr = array();
$stmt->bind_param('iss', $arr);
$arr[0] = 11111;
$arr[1] = 'Georgetown';
$arr[2] = 'NY';
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", maxdb_stmt_affected_rows($stmt));
$arr[0] = 22222;
$arr[1] = 'New Orleans';
$arr[2] = 'LA';
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
$result = $maxdb->query("SELECT * from temp.mycity WHERE zip = '11111' OR zip = '22222'");
if ($result) {
while ($row = $result->fetch_row()) {
printf ("%s %s %s\n", $row[0], $row[1], $row[2]);
}
}
/* Clean up table CountryLanguage */
$maxdb->query("DELETE FROM temp.mycity WHERE name='Georgetown'");
$maxdb->query("DELETE FROM temp.mycity WHERE name='New Orleans'");
printf("%d Rows deleted.\n", $maxdb->affected_rows);
/* close connection */
$maxdb->close();
?>
The above example will output something similar to:
1 Row inserted.
1 Row inserted.
11111 Georgetown NY
22222 New Orleans LA
2 Rows deleted.
See Also
* maxdb_stmt_bind_result() - Binds variables to a prepared statement for
result storage
* maxdb_stmt_execute() - Executes a prepared Query
* maxdb_stmt_fetch() - Fetch results from a prepared statement into the
bound variables
* maxdb_prepare() - Prepare an SQL statement for execution
* maxdb_stmt_send_long_data() - Send data in blocks
* maxdb_stmt_errno() - Returns the error code for the most recent
statement call
* maxdb_stmt_error() - Returns a string description for last statement
error
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_stmt_bind_result
maxdb_stmt::bind_result
(PECL maxdb >= 1.0)
maxdb_stmt_bind_result -- maxdb_stmt::bind_result - Binds variables to a
prepared statement for result storage
Description
Procedural style
bool maxdb_stmt_bind_result ( resource $stmt , mixed &$var1 [, mixed &$...
] )
Object oriented style
bool maxdb_stmt::bind_result ( mixed &$var1 [, mixed &$... ] )
maxdb_stmt_bind_result() is used to associate (bind) columns in the result
set to variables. When maxdb_stmt_fetch() is called to fetch data, the
MaxDB client/server protocol places the data for the bound columns into
the specified variables var1, ....
Note:
Note that all columns must be bound prior to calling maxdb_stmt_fetch().
Depending on column types bound variables can silently change to the
corresponding PHP type.
A column can be bound or rebound at any time, even after a result set
has been partially retrieved. The new binding takes effect the next time
maxdb_stmt_fetch() is called.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Object oriented style
prepare("SELECT zip, name FROM hotel.city ORDER BY name")) {
$stmt->execute();
/* bind variables to prepared statement */
$stmt->bind_result($col1, $col2);
/* fetch values */
while ($stmt->fetch()) {
printf("%s %s\n", $col1, $col2);
}
/* close statement */
$stmt->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
12203 Albany
60601 Chicago
60615 Chicago
45211 Cincinnati
33575 Clearwater
75243 Dallas
32018 Daytona Beach
33441 Deerfield Beach
48226 Detroit
90029 Hollywood
92714 Irvine
90804 Long Beach
11788 Long Island
90018 Los Angeles
70112 New Orleans
10019 New York
10580 New York
92262 Palm Springs
97213 Portland
60018 Rosemont
95054 Santa Clara
20903 Silver Spring
20005 Washington
20019 Washington
20037 Washington
See Also
* maxdb_stmt_bind_param() - Binds variables to a prepared statement as
parameters
* maxdb_stmt_execute() - Executes a prepared Query
* maxdb_stmt_fetch() - Fetch results from a prepared statement into the
bound variables
* maxdb_prepare() - Prepare an SQL statement for execution
* maxdb_stmt_prepare() - Prepare an SQL statement for execution
* maxdb_stmt_init() - Initializes a statement and returns an resource
for use with maxdb_stmt_prepare
* maxdb_stmt_errno() - Returns the error code for the most recent
statement call
* maxdb_stmt_error() - Returns a string description for last statement
error
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_stmt_close_long_data
maxdb_stmt::close_long_data
(PECL maxdb 1.0)
maxdb_stmt_close_long_data -- maxdb_stmt::close_long_data - Ends a
sequence of maxdb_stmt_send_long_data()
Description
Procedural style
bool maxdb_stmt_close_long_data ( resource $stmt , int $param_nr )
Object oriented style
bool maxdb_stmt::close_long_data ( void )
This function has to be called after a sequence of
maxdb_stmt_send_long_data(), that was started after maxdb_execute().
param_nr indicates which parameter to associate the end of data with.
Parameters are numbered beginning with 0.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* maxdb_prepare() - Prepare an SQL statement for execution
* maxdb_stmt_bind_param() - Binds variables to a prepared statement as
parameters
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_stmt_close
maxdb_stmt::close
(PECL maxdb >= 1.0)
maxdb_stmt_close -- maxdb_stmt::close - Closes a prepared statement
Description
Procedural style
bool maxdb_stmt_close ( resource $stmt )
Object oriented style
bool maxdb_stmt::close ( void )
Closes a prepared statement. maxdb_stmt_close() also deallocates the
statement handle pointed to by stmt. If the current statement has pending
or unread results, this function cancels them so that the next query can
be executed.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* maxdb_prepare() - Prepare an SQL statement for execution
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_stmt_data_seek
maxdb_stmt::data_seek
(PECL maxdb >= 1.0)
maxdb_stmt_data_seek -- maxdb_stmt::data_seek - Seeks to an arbitray row
in statement result set
Description
Procedural style
bool maxdb_stmt_data_seek ( resource $statement , int $offset )
Object oriented style
bool maxdb_stmt::data_seek ( int $offset )
The maxdb_stmt_data_seek() function seeks to an arbitrary result pointer
specified by the offset in the statement result set represented by
statement. The offset parameter must be between zero and the total number
of rows minus one (0..maxdb_stmt_num_rows() - 1).
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Object oriented style
prepare($query)) {
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($name, $code);
/* store result */
$stmt->store_result();
/* seek to row no. 5 */
$stmt->data_seek(5);
/* fetch values */
$stmt->fetch();
printf ("City: %s Zip: %s\n", $name, $code);
/* close statement */
$stmt->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
City: Dallas Zip: 75243
See Also
* maxdb_prepare() - Prepare an SQL statement for execution
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_stmt_errno
maxdb_stmt->errno
(PECL maxdb >= 1.0)
maxdb_stmt_errno -- maxdb_stmt->errno - Returns the error code for the
most recent statement call
Description
Procedural style
int maxdb_stmt_errno ( resource $stmt )
Object oriented style
int $maxdb_stmt->errno;
For the statement specified by stmt, maxdb_stmt_errno() returns the error
code for the most recently invoked statement function that can succeed or
fail.
Note:
For possible error codes see documentation of SQLDBC:
>> http://maxdb.sap.com/documentation/.
Return Values
An error code value. Zero means no error occurred.
Examples
Example #1 Object oriented style
query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");
$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {
/* drop table */
$maxdb->query("DROP TABLE temp.mycity");
/* execute query */
$stmt->execute();
printf("Error: %d.\n", $stmt->errno);
/* close statement */
$stmt->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: -4004.
See Also
* maxdb_stmt_error() - Returns a string description for last statement
error
* maxdb_stmt_sqlstate() - Returns SQLSTATE error from previous statement
operation
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_stmt_error
maxdb_stmt->error
(PECL maxdb >= 1.0)
maxdb_stmt_error -- maxdb_stmt->error - Returns a string description for
last statement error
Description
Procedural style
string maxdb_stmt_error ( resource $stmt )
Object oriented style
string $maxdb_stmt->error;
For the statement specified by stmt, maxdb_stmt_error() returns a
containing the error message for the most recently invoked statement
function that can succeed or fail.
Return Values
A string that describes the error. An empty string if no error occurred.
Examples
Example #1 Object oriented style
query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");
$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {
/* drop table */
$maxdb->query("DROP TABLE temp.mycity");
/* execute query */
$stmt->execute();
printf("Error: %s.\n", $stmt->error);
/* close statement */
$stmt->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: POS(23) Unknown table name:MYCITY.
See Also
* maxdb_stmt_errno() - Returns the error code for the most recent
statement call
* maxdb_stmt_sqlstate() - Returns SQLSTATE error from previous statement
operation
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_stmt_execute
maxdb_stmt::execute
(PECL maxdb >= 1.0)
maxdb_stmt_execute -- maxdb_stmt::execute - Executes a prepared Query
Description
Procedural style
bool maxdb_stmt_execute ( resource $stmt )
Object oriented style
bool maxdb_stmt::execute ( void )
The maxdb_stmt_execute() function executes a query that has been
previously prepared using the maxdb_prepare() function represented by the
stmt resource. When executed any parameter markers which exist will
automatically be replaced with the appropiate data.
If the statement is UPDATE, DELETE, or INSERT, the total number of
affected rows can be determined by using the maxdb_stmt_affected_rows()
function. Likewise, if the query yields a result set the maxdb_fetch()
function is used.
Note:
When using maxdb_stmt_execute(), the maxdb_fetch() function must be used
to fetch the data prior to preforming any additional queries.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Object oriented style
query("CREATE TABLE temp.mycity LIKE hotel.city");
/* Prepare an insert statement */
$query = "INSERT INTO temp.mycity (zip, name, state) VALUES (?,?,?)";
$stmt = $maxdb->prepare($query);
$stmt->bind_param("sss", $val1, $val2, $val3);
$val1 = '11111';
$val2 = 'Georgetown';
$val3 = 'NY';
/* Execute the statement */
$stmt->execute();
$val1 = '22222';
$val2 = 'Hubbatown';
$val3 = 'CA';
/* Execute the statement */
$stmt->execute();
/* close statement */
$stmt->close();
/* retrieve all rows from myCity */
$query = "SELECT zip, name, state FROM temp.mycity";
if ($result = $maxdb->query($query)) {
while ($row = $result->fetch_row()) {
printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
}
/* free result set */
$result->close();
}
/* remove table */
$maxdb->query("DROP TABLE temp.mycity");
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
11111 (Georgetown,NY)
22222 (Hubbatown,CA)
See Also
* maxdb_prepare() - Prepare an SQL statement for execution
* maxdb_stmt_bind_param() - Binds variables to a prepared statement as
parameters
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_stmt_fetch
maxdb_stmt::fetch
(PECL maxdb >= 1.0)
maxdb_stmt_fetch -- maxdb_stmt::fetch - Fetch results from a prepared
statement into the bound variables
Description
Procedural style
bool maxdb_stmt_fetch ( resource $stmt )
Object oriented style
bool maxdb_stmt::fetch ( void )
maxdb_stmt_fetch() returns row data using the variables bound by
maxdb_stmt_bind_result().
Note:
Note that all columns must be bound by the application before calling
maxdb_stmt_fetch().
Return Values
Return values
Value Description
TRUE Success. Data has been fetched
FALSE Error occured
NULL No more rows/data exists
Examples
Example #1 Object oriented style
prepare($query)) {
/* execute statement */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($name, $code);
/* fetch values */
while ($stmt->fetch()) {
printf ("%s (%s)\n", $name, $code);
}
/* close statement */
$stmt->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
12203 (Albany)
60601 (Chicago)
60615 (Chicago)
45211 (Cincinnati)
33575 (Clearwater)
75243 (Dallas)
32018 (Daytona Beach)
33441 (Deerfield Beach)
48226 (Detroit)
90029 (Hollywood)
92714 (Irvine)
90804 (Long Beach)
11788 (Long Island)
90018 (Los Angeles)
70112 (New Orleans)
10019 (New York)
10580 (New York)
92262 (Palm Springs)
97213 (Portland)
60018 (Rosemont)
95054 (Santa Clara)
20903 (Silver Spring)
20005 (Washington)
20019 (Washington)
20037 (Washington)
See Also
* maxdb_prepare() - Prepare an SQL statement for execution
* maxdb_stmt_errno() - Returns the error code for the most recent
statement call
* maxdb_stmt_error() - Returns a string description for last statement
error
* maxdb_stmt_bind_result() - Binds variables to a prepared statement for
result storage
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_stmt_free_result
maxdb_stmt::free_result
(PECL maxdb >= 1.0)
maxdb_stmt_free_result -- maxdb_stmt::free_result - Frees stored result
memory for the given statement handle
Description
Procedural style
void maxdb_stmt_free_result ( resource $stmt )
Object oriented style
void maxdb_stmt::free_result ( void )
The maxdb_stmt_free_result() function frees the result memory associated
with the statement represented by the stmt parameter, which was allocated
by maxdb_stmt_store_result().
Return Values
This function doesn't return any value.
See Also
* maxdb_stmt_store_result() - Transfers a result set from a prepared
statement
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_stmt_init
maxdb->stmt_init
(PECL maxdb >= 1.0)
maxdb_stmt_init -- maxdb->stmt_init - Initializes a statement and returns
an resource for use with maxdb_stmt_prepare
Description
Procedural style
resource maxdb_stmt_init ( resource $link )
Object oriented style
object maxdb::stmt_init ( void )
Allocates and initializes a statement resource suitable for
maxdb_stmt_prepare().
Note:
Any subsequent calls to any maxdb_stmt function will fail until
maxdb_stmt_prepare() was called.
Return Values
Returns an resource.
See Also
* maxdb_stmt_prepare() - Prepare an SQL statement for execution
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_stmt_num_rows
maxdb_stmt->num_rows
(PECL maxdb >= 1.0)
maxdb_stmt_num_rows -- maxdb_stmt->num_rows - Return the number of rows in
statements result set
Description
Procedural style
int maxdb_stmt_num_rows ( resource $stmt )
Object oriented style
int $maxdb_stmt->num_rows;
Returns the number of rows in the result set.
Return Values
An integer representing the number of rows in result set.
Examples
Example #1 Object oriented style
prepare($query)) {
/* execute query */
$stmt->execute();
/* store result */
$stmt->store_result();
printf("Number of rows: %d.\n", $stmt->num_rows);
/* close statement */
$stmt->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Number of rows: 25.
See Also
* maxdb_stmt_affected_rows() - Returns the total number of rows changed,
deleted, or inserted by the last executed statement
* maxdb_prepare() - Prepare an SQL statement for execution
* maxdb_stmt_store_result() - Transfers a result set from a prepared
statement
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_stmt_param_count
maxdb_stmt->param_count
(PECL maxdb >= 1.0)
maxdb_stmt_param_count -- maxdb_stmt->param_count - Returns the number of
parameter for the given statement
Description
Procedural style
int maxdb_stmt_param_count ( resource $stmt )
Object oriented style
int $maxdb_stmt->param_count;
maxdb_stmt_param_count() returns the number of parameter markers present
in the prepared statement.
Return Values
returns an integer representing the number of parameters.
Examples
Example #1 Object oriented style
prepare("SELECT name FROM hotel.city WHERE name=? OR state=?")) {
$marker = $stmt->param_count;
printf("Statement has %d markers.\n", $marker);
/* close statement */
$stmt->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Statement has 2 markers.
See Also
* maxdb_prepare() - Prepare an SQL statement for execution
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_stmt_prepare
maxdb_stmt::prepare
(PECL maxdb >= 1.0)
maxdb_stmt_prepare -- maxdb_stmt::prepare - Prepare an SQL statement for
execution
Description
Procedural style
bool maxdb_stmt_prepare ( resource $stmt , string $query )
Object oriented style
mixed maxdb_stmt::prepare ( string $query )
maxdb_stmt_prepare() prepares the SQL query pointed to by the
null-terminated string query. The statement resource has to be allocated
by maxdb_stmt_init(). The query must consist of a single SQL statement.
Note:
You should not add a terminating semicolon or \g to the statement.
The parameter query can include one or more parameter markers in the SQL
statement by embedding question mark (?) characters at the appropriate
positions.
Note:
The markers are legal only in certain places in SQL statements. For
example, they are allowed in the VALUES() list of an INSERT statement
(to specify column values for a row), or in a comparison with a column
in a WHERE clause to specify a comparison value.
However, they are not allowed for identifiers (such as table or column
names), in the select list that names the columns to be returned by a
SELECT statement), or to specify both operands of a binary operator such
as the = equal sign. The latter restriction is necessary because it
would be impossible to determine the parameter type. In general,
parameters are legal only in Data Manipulation Languange (DML)
statements, and not in Data Defination Language (DDL) statements.
The parameter markers must be bound to application variables using
maxdb_stmt_bind_param() and/or maxdb_stmt_bind_result() before executing
the statement or fetching rows.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Object oriented style
stmt_init();
if ($stmt->prepare("SELECT state FROM hotel.city WHERE name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Portland is in district OR
See Also
* maxdb_stmt_init() - Initializes a statement and returns an resource
for use with maxdb_stmt_prepare
* maxdb_stmt_execute() - Executes a prepared Query
* maxdb_stmt_fetch() - Fetch results from a prepared statement into the
bound variables
* maxdb_stmt_bind_param() - Binds variables to a prepared statement as
parameters
* maxdb_stmt_bind_result() - Binds variables to a prepared statement for
result storage
* maxdb_stmt_close() - Closes a prepared statement
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_stmt_reset
maxdb_stmt::reset
(PECL maxdb >= 1.0)
maxdb_stmt_reset -- maxdb_stmt::reset - Resets a prepared statement
Description
Procedural style
bool maxdb_stmt_reset ( resource $stmt )
Object oriented style
bool maxdb_stmt::reset ( void )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_stmt_result_metadata
maxdb_stmt::result_metadata
(PECL maxdb >= 1.0)
maxdb_stmt_result_metadata -- maxdb_stmt::result_metadata - Returns result
set metadata from a prepared statement
Description
Procedural style
resource maxdb_stmt_result_metadata ( resource $stmt )
Object oriented style
resource maxdb_stmt::result_metadata ( void )
If a statement passed to maxdb_prepare() is one that produces a result
set, maxdb_stmt_result_metadata() returns the result resource that can be
used to process the meta information such as total number of fields and
individual field information.
Note:
This result set pointer can be passed as an argument to any of the
field-based functions that process result set metadata, such as:
* maxdb_num_fields()
* maxdb_fetch_field()
* maxdb_fetch_field_direct()
* maxdb_fetch_fields()
* maxdb_field_count()
* maxdb_field_seek()
* maxdb_field_tell()
* maxdb_free_result()
The result set structure should be freed when you are done with it, which
you can do by passing it to maxdb_free_result()
Note:
The result set returned by maxdb_stmt_result_metadata() contains only
metadata. It does not contain any row results. The rows are obtained by
using the statement handle with maxdb_fetch().
Return Values
maxdb_stmt_result_metadata() returns a result resource or FALSE if an
error occured.
Examples
Example #1 Object oriented style
query("CREATE TABLE temp.friends (id int, name varchar(20))");
$maxdb->query("INSERT INTO temp.friends VALUES (1,'Hartmut')");
$maxdb->query("INSERT INTO temp.friends VALUES (2, 'Ulf')");
$stmt = $maxdb->prepare("SELECT id, name FROM temp.friends");
$stmt->execute();
/* get resultset for metadata */
$result = $stmt->result_metadata();
/* retrieve field information from metadata result set */
$field = $result->fetch_field();
printf("Fieldname: %s\n", $field->name);
/* close resultset */
$result->close();
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
name);
/* close resultset */
maxdb_free_result($result);
/* close connection */
maxdb_close($link);
?>
The above example will output something similar to:
Fieldname: ID
See Also
* maxdb_prepare() - Prepare an SQL statement for execution
* maxdb_free_result() - Frees the memory associated with a result
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_stmt_send_long_data
maxdb_stmt::send_long_data
(PECL maxdb 1.0)
maxdb_stmt_send_long_data -- maxdb_stmt::send_long_data - Send data in
blocks
Description
Procedural style
bool maxdb_stmt_send_long_data ( resource $stmt , int $param_nr , string
$data )
Object oriented style
bool maxdb_stmt::stmt_send_long_data ( int $param_nr , string $data )
Allows to send parameter data to the server in pieces (or chunks). This
function can be called multiple times to send the parts of a character or
binary data value for a column, which must be one of the TEXT or BLOB
datatypes.
param_nr indicates which parameter to associate the data with. Parameters
are numbered beginning with 0. data is a string containing data to be
sent.
Note:
For efficiency reasons, this function should be used after calling
maxdb_execute(). In this case, the data is not stored on the client
side. The end of the sequence must end with a call to
maxdb_stmt_close_long_data().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* maxdb_prepare() - Prepare an SQL statement for execution
* maxdb_stmt_bind_param() - Binds variables to a prepared statement as
parameters
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_stmt_sqlstate
(PECL maxdb >= 1.0)
maxdb_stmt_sqlstate - Returns SQLSTATE error from previous statement
operation
Description
string maxdb_stmt_sqlstate ( resource $stmt )
Returns a string containing the SQLSTATE error code for the most recently
invoked prepared statement function that can succeed or fail. The error
code consists of five characters. '00000' means no error. The values are
specified by ANSI SQL and ODBC.
Note:
Note that not all MaxDB errors are yet mapped to SQLSTATE's. The value
HY000 (general error) is used for unmapped errors.
Return Values
Returns a string containing the SQLSTATE error code for the last error.
The error code consists of five characters. '00000' means no error.
Examples
Example #1 Object oriented style
query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");
$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {
/* drop table */
$maxdb->query("DROP TABLE temp.mycity");
/* execute query */
$stmt->execute();
printf("Error: %s.\n", $stmt->sqlstate);
/* close statement */
$stmt->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: 42000.
See Also
* maxdb_stmt_errno() - Returns the error code for the most recent
statement call
* maxdb_stmt_error() - Returns a string description for last statement
error
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_stmt_store_result
maxdb::store_result
(PECL maxdb >= 1.0)
maxdb_stmt_store_result -- maxdb::store_result - Transfers a result set
from a prepared statement
Description
Procedural style
bool maxdb_stmt_store_result ( resource $stmt )
Object oriented style
object maxdb::store_result ( void )
maxdb_stmt_store_result() has no functionally effect and should not be
used for retrieving data from MaxDB server.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Object oriented style
prepare($query)) {
/* execute query */
$stmt->execute();
/* store result */
$stmt->store_result();
printf("Number of rows: %d.\n", $stmt->num_rows);
/* free result */
$stmt->free_result();
/* close statement */
$stmt->close();
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Number of rows: 25.
See Also
* maxdb_prepare() - Prepare an SQL statement for execution
* maxdb_stmt_result_metadata() - Returns result set metadata from a
prepared statement
* maxdb_fetch() - Alias of maxdb_stmt_fetch
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_store_result
maxdb::store_result
(PECL maxdb >= 1.0)
maxdb_store_result -- maxdb::store_result - Transfers a result set from
the last query
Description
Procedural style
resource maxdb_store_result ( resource $link )
Object oriented style
object maxdb::store_result ( void )
This function has no functionally effect.
Return Values
Returns a result resource or FALSE if an error occurred.
Examples
See maxdb_multi_query().
See Also
* maxdb_real_query() - Execute an SQL query
* maxdb_use_result() - Initiate a result set retrieval
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_thread_id
maxdb->thread_id
(PECL maxdb >= 1.0)
maxdb_thread_id -- maxdb->thread_id - Returns the thread ID for the
current connection
Description
Procedural style
int maxdb_thread_id ( resource $link )
Object oriented style
int $maxdb->thread_id;
The maxdb_thread_id() function returns the thread ID for the current
connection which can then be killed using the maxdb_kill() function. If
the connection is lost and you reconnect with maxdb_ping(), the thread ID
will be other. Therefore you should get the thread ID only when you need
it.
Note:
The thread ID is assigned on a connection-by-connection basis. Hence, if
the connection is broken and then re-established a new thread ID will be
assigned.
Return Values
maxdb_thread_id() returns the Thread ID for the current connection.
Examples
Example #1 Object oriented style
thread_id;
/* Kill connection */
$maxdb->kill($thread_id);
/* This should produce an error */
if (!$maxdb->query("CREATE TABLE mycity LIKE hotel.city")) {
printf("Error: %s\n", $maxdb->error);
exit;
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Warning: maxdb_query(): -10821 Session not connected <...>
Error: Session not connected
See Also
* maxdb_kill() - Disconnects from a MaxDB server
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_thread_safe
(PECL maxdb >= 7.6.06.04)
maxdb_thread_safe - Returns whether thread safety is given or not
Description
bool maxdb_thread_safe ( void )
maxdb_thread_safe() indicates whether the client library is compiled as
thread-safe.
Return Values
TRUE if the client library is thread-safe, otherwise FALSE.
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_use_result
maxdb::use_result
(PECL maxdb >= 1.0)
maxdb_use_result -- maxdb::use_result - Initiate a result set retrieval
Description
Procedural style
resource maxdb_use_result ( resource $link )
Object oriented style
resource maxdb::use_result ( void )
maxdb_use_result() has no effect.
Return Values
Returns result or FALSE on failure.
Examples
Example #1 Object oriented style
multi_query($query)) {
do {
/* store first result set */
if ($result = $maxdb->use_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->close();
}
/* print divider */
if ($maxdb->more_results()) {
printf("-----------------\n");
}
} while ($maxdb->next_result());
}
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
a
See Also
* maxdb_real_query() - Execute an SQL query
* maxdb_store_result() - Transfers a result set from the last query
----------------------------------------------------------------------
----------------------------------------------------------------------
maxdb_warning_count
maxdb->warning_count
(PECL maxdb >= 1.0)
maxdb_warning_count -- maxdb->warning_count - Returns the number of
warnings from the last query for the given link
Description
Procedural style
int maxdb_warning_count ( resource $link )
Object oriented style
int $maxdb->warning_count;
maxdb_warning_count() returns the number of warnings from the last query
in the connection represented by the link parameter.
Return Values
Number of warnings or zero if there are no warnings.
Examples
Example #1 Object oriented style
query("CREATE TABLE temp.mycity LIKE hotel.city");
/* a remarkable city in Wales */
$query = "INSERT INTO temp.mycity (zip, name) VALUES('11111',
'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";
$maxdb->query($query);
printf ("Number of warning: %d\n", $maxdb->warning_count);
/* close connection */
$maxdb->close();
?>
Example #2 Procedural style
The above example will output something similar to:
Warning: maxdb_query(): -8004 POS(62) Constant must be compatible with column type and length <...>
Number of warning: 0
See Also
* maxdb_errno() - Returns the error code for the most recent function
call
* maxdb_error() - Returns a string description of the last error
* maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB
operation
----------------------------------------------------------------------
Table of Contents
* maxdb_affected_rows - Gets the number of affected rows in a previous
MaxDB operation
* maxdb_autocommit - Turns on or off auto-commiting database
modifications
* maxdb_bind_param - Alias of maxdb_stmt_bind_param
* maxdb_bind_result - Alias of maxdb_stmt_bind_result
* maxdb_change_user - Changes the user of the specified database
connection
* maxdb_character_set_name - Returns the default character set for the
database connection
* maxdb_client_encoding - Alias of maxdb_character_set_name
* maxdb_close_long_data - Alias of maxdb_stmt_close_long_data
* maxdb_close - Closes a previously opened database connection
* maxdb_commit - Commits the current transaction
* maxdb_connect_errno - Returns the error code from last connect call
* maxdb_connect_error - Returns a string description of the last connect
error
* maxdb_connect - Open a new connection to the MaxDB server
* maxdb_data_seek - Adjusts the result pointer to an arbitary row in the
result
* maxdb_debug - Performs debugging operations
* maxdb_disable_reads_from_master - Disable reads from master
* maxdb_disable_rpl_parse - Disable RPL parse
* maxdb_dump_debug_info - Dump debugging information into the log
* maxdb_embedded_connect - Open a connection to an embedded MaxDB server
* maxdb_enable_reads_from_master - Enable reads from master
* maxdb_enable_rpl_parse - Enable RPL parse
* maxdb_errno - Returns the error code for the most recent function call
* maxdb_error - Returns a string description of the last error
* maxdb_escape_string - Alias of maxdb_real_escape_string
* maxdb_execute - Alias of maxdb_stmt_execute
* maxdb_fetch_array - Fetch a result row as an associative, a numeric
array, or both
* maxdb_fetch_assoc - Fetch a result row as an associative array
* maxdb_fetch_field_direct - Fetch meta-data for a single field
* maxdb_fetch_field - Returns the next field in the result set
* maxdb_fetch_fields - Returns an array of resources representing the
fields in a result set
* maxdb_fetch_lengths - Returns the lengths of the columns of the
current row in the result set
* maxdb_fetch_object - Returns the current row of a result set as an
object
* maxdb_fetch_row - Get a result row as an enumerated array
* maxdb_fetch - Alias of maxdb_stmt_fetch
* maxdb_field_count - Returns the number of columns for the most recent
query
* maxdb_field_seek - Set result pointer to a specified field offset
* maxdb_field_tell - Get current field offset of a result pointer
* maxdb_free_result - Frees the memory associated with a result
* maxdb_get_client_info - Returns the MaxDB client version as a string
* maxdb_get_client_version - Get MaxDB client info
* maxdb_get_host_info - Returns a string representing the type of
connection used
* maxdb_get_metadata - Alias of maxdb_stmt_result_metadata
* maxdb_get_proto_info - Returns the version of the MaxDB protocol used
* maxdb_get_server_info - Returns the version of the MaxDB server
* maxdb_get_server_version - Returns the version of the MaxDB server as
an integer
* maxdb_info - Retrieves information about the most recently executed
query
* maxdb_init - Initializes MaxDB and returns an resource for use with
maxdb_real_connect
* maxdb_insert_id - Returns the auto generated id used in the last query
* maxdb_kill - Disconnects from a MaxDB server
* maxdb_master_query - Enforce execution of a query on the master in a
master/slave setup
* maxdb_more_results - Check if there any more query results from a
multi query
* maxdb_multi_query - Performs a query on the database
* maxdb_next_result - Prepare next result from multi_query
* maxdb_num_fields - Get the number of fields in a result
* maxdb_num_rows - Gets the number of rows in a result
* maxdb_options - Set options
* maxdb_param_count - Alias of maxdb_stmt_param_count
* maxdb_ping - Pings a server connection, or tries to reconnect if the
connection has gone down
* maxdb_prepare - Prepare an SQL statement for execution
* maxdb_query - Performs a query on the database
* maxdb_real_connect - Opens a connection to a MaxDB server
* maxdb_real_escape_string - Escapes special characters in a string for
use in an SQL statement, taking into account the current charset of
the connection
* maxdb_real_query - Execute an SQL query
* maxdb_report - Enables or disables internal report functions
* maxdb_rollback - Rolls back current transaction
* maxdb_rpl_parse_enabled - Check if RPL parse is enabled
* maxdb_rpl_probe - RPL probe
* maxdb_rpl_query_type - Returns RPL query type
* maxdb_select_db - Selects the default database for database queries
* maxdb_send_long_data - Alias of maxdb_stmt_send_long_data
* maxdb_send_query - Send the query and return
* maxdb_server_end - Shut down the embedded server
* maxdb_server_init - Initialize embedded server
* maxdb_set_opt - Alias of maxdb_options
* maxdb_sqlstate - Returns the SQLSTATE error from previous MaxDB
operation
* maxdb_ssl_set - Used for establishing secure connections using SSL
* maxdb_stat - Gets the current system status
* maxdb_stmt_affected_rows - Returns the total number of rows changed,
deleted, or inserted by the last executed statement
* maxdb_stmt_bind_param - Binds variables to a prepared statement as
parameters
* maxdb_stmt_bind_result - Binds variables to a prepared statement for
result storage
* maxdb_stmt_close_long_data - Ends a sequence of
maxdb_stmt_send_long_data
* maxdb_stmt_close - Closes a prepared statement
* maxdb_stmt_data_seek - Seeks to an arbitray row in statement result
set
* maxdb_stmt_errno - Returns the error code for the most recent
statement call
* maxdb_stmt_error - Returns a string description for last statement
error
* maxdb_stmt_execute - Executes a prepared Query
* maxdb_stmt_fetch - Fetch results from a prepared statement into the
bound variables
* maxdb_stmt_free_result - Frees stored result memory for the given
statement handle
* maxdb_stmt_init - Initializes a statement and returns an resource for
use with maxdb_stmt_prepare
* maxdb_stmt_num_rows - Return the number of rows in statements result
set
* maxdb_stmt_param_count - Returns the number of parameter for the given
statement
* maxdb_stmt_prepare - Prepare an SQL statement for execution
* maxdb_stmt_reset - Resets a prepared statement
* maxdb_stmt_result_metadata - Returns result set metadata from a
prepared statement
* maxdb_stmt_send_long_data - Send data in blocks
* maxdb_stmt_sqlstate - Returns SQLSTATE error from previous statement
operation
* maxdb_stmt_store_result - Transfers a result set from a prepared
statement
* maxdb_store_result - Transfers a result set from the last query
* maxdb_thread_id - Returns the thread ID for the current connection
* maxdb_thread_safe - Returns whether thread safety is given or not
* maxdb_use_result - Initiate a result set retrieval
* maxdb_warning_count - Returns the number of warnings from the last
query for the given link
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* Basic usage
* MaxDB Functions
* maxdb_affected_rows - Gets the number of affected rows in a
previous MaxDB operation
* maxdb_autocommit - Turns on or off auto-commiting database
modifications
* maxdb_bind_param - Alias of maxdb_stmt_bind_param
* maxdb_bind_result - Alias of maxdb_stmt_bind_result
* maxdb_change_user - Changes the user of the specified database
connection
* maxdb_character_set_name - Returns the default character set for
the database connection
* maxdb_client_encoding - Alias of maxdb_character_set_name
* maxdb_close_long_data - Alias of maxdb_stmt_close_long_data
* maxdb_close - Closes a previously opened database connection
* maxdb_commit - Commits the current transaction
* maxdb_connect_errno - Returns the error code from last connect
call
* maxdb_connect_error - Returns a string description of the last
connect error
* maxdb_connect - Open a new connection to the MaxDB server
* maxdb_data_seek - Adjusts the result pointer to an arbitary row
in the result
* maxdb_debug - Performs debugging operations
* maxdb_disable_reads_from_master - Disable reads from master
* maxdb_disable_rpl_parse - Disable RPL parse
* maxdb_dump_debug_info - Dump debugging information into the log
* maxdb_embedded_connect - Open a connection to an embedded MaxDB
server
* maxdb_enable_reads_from_master - Enable reads from master
* maxdb_enable_rpl_parse - Enable RPL parse
* maxdb_errno - Returns the error code for the most recent function
call
* maxdb_error - Returns a string description of the last error
* maxdb_escape_string - Alias of maxdb_real_escape_string
* maxdb_execute - Alias of maxdb_stmt_execute
* maxdb_fetch_array - Fetch a result row as an associative, a
numeric array, or both
* maxdb_fetch_assoc - Fetch a result row as an associative array
* maxdb_fetch_field_direct - Fetch meta-data for a single field
* maxdb_fetch_field - Returns the next field in the result set
* maxdb_fetch_fields - Returns an array of resources representing
the fields in a result set
* maxdb_fetch_lengths - Returns the lengths of the columns of the
current row in the result set
* maxdb_fetch_object - Returns the current row of a result set as
an object
* maxdb_fetch_row - Get a result row as an enumerated array
* maxdb_fetch - Alias of maxdb_stmt_fetch
* maxdb_field_count - Returns the number of columns for the most
recent query
* maxdb_field_seek - Set result pointer to a specified field offset
* maxdb_field_tell - Get current field offset of a result pointer
* maxdb_free_result - Frees the memory associated with a result
* maxdb_get_client_info - Returns the MaxDB client version as a
string
* maxdb_get_client_version - Get MaxDB client info
* maxdb_get_host_info - Returns a string representing the type of
connection used
* maxdb_get_metadata - Alias of maxdb_stmt_result_metadata
* maxdb_get_proto_info - Returns the version of the MaxDB protocol
used
* maxdb_get_server_info - Returns the version of the MaxDB server
* maxdb_get_server_version - Returns the version of the MaxDB
server as an integer
* maxdb_info - Retrieves information about the most recently
executed query
* maxdb_init - Initializes MaxDB and returns an resource for use
with maxdb_real_connect
* maxdb_insert_id - Returns the auto generated id used in the last
query
* maxdb_kill - Disconnects from a MaxDB server
* maxdb_master_query - Enforce execution of a query on the master
in a master/slave setup
* maxdb_more_results - Check if there any more query results from a
multi query
* maxdb_multi_query - Performs a query on the database
* maxdb_next_result - Prepare next result from multi_query
* maxdb_num_fields - Get the number of fields in a result
* maxdb_num_rows - Gets the number of rows in a result
* maxdb_options - Set options
* maxdb_param_count - Alias of maxdb_stmt_param_count
* maxdb_ping - Pings a server connection, or tries to reconnect if
the connection has gone down
* maxdb_prepare - Prepare an SQL statement for execution
* maxdb_query - Performs a query on the database
* maxdb_real_connect - Opens a connection to a MaxDB server
* maxdb_real_escape_string - Escapes special characters in a string
for use in an SQL statement, taking into account the current
charset of the connection
* maxdb_real_query - Execute an SQL query
* maxdb_report - Enables or disables internal report functions
* maxdb_rollback - Rolls back current transaction
* maxdb_rpl_parse_enabled - Check if RPL parse is enabled
* maxdb_rpl_probe - RPL probe
* maxdb_rpl_query_type - Returns RPL query type
* maxdb_select_db - Selects the default database for database
queries
* maxdb_send_long_data - Alias of maxdb_stmt_send_long_data
* maxdb_send_query - Send the query and return
* maxdb_server_end - Shut down the embedded server
* maxdb_server_init - Initialize embedded server
* maxdb_set_opt - Alias of maxdb_options
* maxdb_sqlstate - Returns the SQLSTATE error from previous MaxDB
operation
* maxdb_ssl_set - Used for establishing secure connections using
SSL
* maxdb_stat - Gets the current system status
* maxdb_stmt_affected_rows - Returns the total number of rows
changed, deleted, or inserted by the last executed statement
* maxdb_stmt_bind_param - Binds variables to a prepared statement
as parameters
* maxdb_stmt_bind_result - Binds variables to a prepared statement
for result storage
* maxdb_stmt_close_long_data - Ends a sequence of
maxdb_stmt_send_long_data
* maxdb_stmt_close - Closes a prepared statement
* maxdb_stmt_data_seek - Seeks to an arbitray row in statement
result set
* maxdb_stmt_errno - Returns the error code for the most recent
statement call
* maxdb_stmt_error - Returns a string description for last
statement error
* maxdb_stmt_execute - Executes a prepared Query
* maxdb_stmt_fetch - Fetch results from a prepared statement into
the bound variables
* maxdb_stmt_free_result - Frees stored result memory for the given
statement handle
* maxdb_stmt_init - Initializes a statement and returns an resource
for use with maxdb_stmt_prepare
* maxdb_stmt_num_rows - Return the number of rows in statements
result set
* maxdb_stmt_param_count - Returns the number of parameter for the
given statement
* maxdb_stmt_prepare - Prepare an SQL statement for execution
* maxdb_stmt_reset - Resets a prepared statement
* maxdb_stmt_result_metadata - Returns result set metadata from a
prepared statement
* maxdb_stmt_send_long_data - Send data in blocks
* maxdb_stmt_sqlstate - Returns SQLSTATE error from previous
statement operation
* maxdb_stmt_store_result - Transfers a result set from a prepared
statement
* maxdb_store_result - Transfers a result set from the last query
* maxdb_thread_id - Returns the thread ID for the current
connection
* maxdb_thread_safe - Returns whether thread safety is given or not
* maxdb_use_result - Initiate a result set retrieval
* maxdb_warning_count - Returns the number of warnings from the
last query for the given link
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB Native Driver
----------------------------------------------------------------------
Manual
Table of Contents
* Installation
* Tutorial
* SQL to Mongo Mapping Chart
* Connecting
* Writes
* Querying
* Updates
* php.ini Options
* Security
* Running the Driver's Tests
* Troubleshooting
----------------------------------------------------------------------
Installation
The MongoDB PHP driver should work on nearly any system: Windows, Mac OS
X, Unix, and Linux; little- and big-endian machines; 32- and 64-bit
machines; PHP 5.1, 5.2, and 5.3.
This >> PECL extension is not bundled with PHP. This page gives more
specific information on installing on different systems and
troubleshooting issues users have run into.
* >> Installing on *NIX
* >> Manual Installation
* >> OS X
* >> Gentoo
* >> Fedora
* >> Installing on Windows
* >> Third-Party Installation Instructions
Installing on *NIX
Run:
$ sudo pecl install mongo
If you are using CentOS or Redhat, Csoke Arpad created >> RPMs for these
distributions.
Add the following line to your php.ini file:
extension=mongo.so
If pecl runs out of memory while installing, make sure memory_limit in
php.ini is set to at least 32MB.
Manual Installation
For driver developers and people interested in the latest bugfixes, you
can compile the driver from the latest source code on >> Github. Go to
Github and click the "download" button. Then run:
$ tar zxvf mongodb-mongodb-php-driver-.tar.gz
$ cd mongodb-mongodb-php-driver-
$ phpize
$ ./configure
$ sudo make install
Make the following changes to php.ini:
* Make sure the extension_dir variable is pointing to the location of
mongo.so. The build will display where it is installing the PHP driver
with output that looks something like:
Installing '/usr/lib/php/extensions/no-debug-zts-20060613/mongo.so'
Make sure that it is the same as the PHP extension directory by
runnning:
$ php -i | grep extension_dir
extension_dir => /usr/lib/php/extensions/no-debug-zts-20060613 =>
/usr/lib/php/extensions/no-debug-zts-20060613
If it's not, change the extension_dir in php.ini or move mongo.so.
* To load the extension on PHP startup, add a line:
extension=mongo.so
OS X
If your system is unable to find autoconf, you'll need to install Xcode
(available on your installation DVD or as a free download from the Apple
website).
If you are using XAMPP, you may be able to compile the driver with the
following command:
sudo /Applications/XAMPP/xamppfiles/bin/pecl install mongo
If you are using MAMP (or XAMPP and the above command does not work),
precompiled binaries are available from >> Github (download the latest one
with "osx" in the name that matches your version of PHP). Extract mongo.so
from the archive and add it to MAMP or XAMPP's extension directory. Add
extension=mongo.so
to the php.ini file being used and restart the server.
Gentoo
Gentoo has a package for the PHP driver called dev-php5/mongo, which can
be installed with:
$ sudo emerge -va dev-php5/mongo
If you use PECL, you may get an error that libtool is the wrong version.
Compiling from source you'll need to run aclocal and autoconf.
$ phpize && aclocal && autoconf && ./configure && make && make install
Red Hat
This includes Fedora and CentOS.
The default Apache settings on these systems do not let requests make
network connections, meaning that the driver will get "Permission denied"
errors when it tries to connect to the database. If you run into this, try
running:
$ /usr/sbin/setsebool -P httpd_can_network_connect 1
Then restart Apache. (This issue has also occurred with SELinux.)
Installing on Windows
Precompiled binaries for each release are available from >> Github for a
variety of combinations of versions, thread safety, and VC libraries.
Unzip the archive and put php_mongo.dll in your PHP extension directory
("ext" by default).
The latest (non-release) code is compiled into Windows binaries on every
commit. The zip consists of a .zip with php_mongo.dll and a version.txt.
Please keep the version.txt around so that if you have a question or
problem, you can give the developers the exact version you're using. (The
number is long and nonsensical, but it will make sense to the developers!)
To get the latest bug fixes (and possibly bugs), download the binary
corresponding to the PHP you have installed:
* >> PHP 5.2 VC6 Non-Thread-Safe Mongo extension
* >> PHP 5.2 VC6 Thread-Safe Mongo extension
* >> PHP 5.3 VC6 Non-Thread-Safe Mongo extension
* >> PHP 5.3 VC6 Thread-Safe Mongo extension
* >> PHP 5.3 VC8 Non-Thread-Safe Mongo extension
* >> PHP 5.3 VC8 Thread-Safe Mongo extension
* >> PHP 5.3 VC9 Non-Thread-Safe Mongo extension
* >> PHP 5.3 VC9 Thread-Safe Mongo extension
Add the following line to your php.ini file:
extension=php_mongo.dll
Third-Party Installation Instructions
A number of people have created excellent tutorials on installing the PHP
driver.
* >> PHP 5.3.1 with Xdebug, MongoDB and Lithium on Ubuntu 9.10 / Apache
2.2
An excellent video that takes you step-by-step through installing
Apache, PHP, Xdebug, MongoDB, and Lithium by Jon Adams.
* >> Installing MongoDB and the PHP driver on Ubuntu 9.04
Spanish article by Javier Aranda (>> English translation).
* >> OS X: Installing MongoDB and the PHP Mongo Driver
By Matt Butcher.
----------------------------------------------------------------------
----------------------------------------------------------------------
Tutorial
Introduction
This is the 10gen-supported PHP driver for MongoDB.
Here's a quick code sample that connects, inserts documents, queries for
documents, iterates through query results, and disconnects from MongoDB.
There are more details on each step in the tutorial below.
comedy;
// select a collection (analogous to a relational database's table)
$collection = $db->cartoons;
// add a record
$obj = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );
$collection->insert($obj);
// add another record, with a different "shape"
$obj = array( "title" => "XKCD", "online" => true );
$collection->insert($obj);
// find everything in the collection
$cursor = $collection->find();
// iterate through the results
foreach ($cursor as $obj) {
echo $obj["title"] . "\n";
}
?>
This would output:
Calvin and Hobbes
XKCD
Making a Connection
To connect to the database server, use one of the following:
You do not have to explicitly disconnect from the database. When
$connection goes out of scope, the connection will be closed automatically
and any database resources it was using will be freed.
See Also
The manual chapter on connecting covers different types of connections.
The API documentation on the Mongo class and Mongo::__construct() give a
comprehensive look at all possible options with a number of examples.
Getting a Database
To select a database, use:
dbname;
?>
The database does not need to be created in advance, you can create new
databases by selecting them. Be careful of typos! You can inadvertently
create a new database, which can cause confusing errors:
mybiglongdbname;
// do some stuff
$db = $connection->mybiglongdbnme;
// now connected to a different database!
?>
See Also
The API documentation on the MongoDB class contains more information about
database objects.
Getting A Collection
Getting a collection has the same syntax as getting a database:
baz;
$collection = $db->foobar;
// or, more succinctly
$collection = $connection->baz->foobar;
?>
See Also
The API documentation on the MongoCollection class contains more
information about collection objects.
Inserting a Document
Associative arrays are the basic object that can be saved to a collection
in the database. A somewhat random "document" might be:
"MongoDB",
"type" => "database",
"count" => 1,
"info" => (object)array( "x" => 203, "y" => 102),
"versions" => array("0.9.7", "0.9.8", "0.9.9")
);
?>
Note that you can have nested arrays and objects.
To insert this document, use MongoCollection::insert():
insert( $doc );
?>
See Also
The API documentation on MongoCollection::insert() contains more
information about inserting data.
Finding Documents using MongoCollection::findOne()
To show that the document we inserted in the previous step is there, we
can do a simple MongoCollection::findOne() operation to get a single
document from the collection. This method is useful when there only is one
document matching the query or you are only interested in one result.
findOne();
var_dump( $obj );
?>
This should print:
array(5) {
["_id"]=>
object(MongoId)#6 (0) {
}
["name"]
string(7) "MongoDB"
["type"]=>
string(8) "database"
["count"]=>
int(1)
["info"]=>
array (2) {
["x"]=>
int(203)
["y"]=>
int(102)
}
["versions"]
array(3) {
[0]=>
string(5) "0.9.7"
[1]=>
string(5) "0.9.8"
[2]=>
string(5) "0.9.9"
}
}
Note the _id field has been added automatically to your document. _id is
the "primary key" field that is automatically populate for almost all
documents in MongoDB.
See Also
The API documentation on MongoCollection::findOne() contains more
information about finding data.
Adding Multiple Documents
In order to do more interesting things with queries, let's add multiple
simple documents to the collection. These documents will just be
value );
?>
and we can do this fairly efficiently in a loop
insert( array( "i" => $i ) );
}
?>
Notice that we can insert arrays with different key sets into the same
collection. This aspect is what we mean when we say that MongoDB is
"schema-free".
Counting Documents in A Collection
Now that we've inserted 101 documents (the 100 we did in the loop, plus
the first one), we can check to see if we have them all using the
MongoCollection::count() method.
count();
?>
and it should print 101.
Using a Cursor to Get All of the Documents
In order to get all the documents in the collection, we will use
MongoCollection::find(). The find() method returns a MongoCursor object
which allows us to iterate over the set of documents that matched our
query. So to query all of the documents and print them out:
find();
foreach ($cursor as $id => $value) {
echo "$id: ";
var_dump( $value );
}
?>
and that should print all 101 documents in the collection. $id is the _id
field of a document, and $value is the document itself.
See Also
The API documentation on MongoCollection::find() contains more information
about finding data.
Setting Criteria for a Query
We can create a query to pass to the MongoCollection::find() method to get
a subset of the documents in our collection. For example, if we wanted to
find the document for which the value of the "i" field is 71, we would do
the following:
71 );
$cursor = $collection->find( $query );
while( $cursor->hasNext() ) {
var_dump( $cursor->getNext() );
}
?>
and it should just print just one document
array(2) {
["_id"]=>
object(MongoId)#6 (0) {
}
["i"]=>
int(71)
["_ns"]=>
"testCollection"
}
Getting A Set of Documents With a Query
We can use the query to get a set of documents from our collection. For
example, if we wanted to get all documents where "i" > 50, we could write:
array( '$gt' => 50 ) ); //note the single quotes around '$gt'
$cursor = $coll->find( $query );
while( $cursor->hasNext() ) {
var_dump( $cursor->getNext() );
}
?>
which should print the documents where i > 50. We could also get a range,
say 20 < i <= 30:
array( "\$gt" => 20, "\$lte" => 30 ) );
$cursor = $coll->find( $query );
while( $cursor->hasNext() ) {
var_dump( $cursor->getNext() );
}
?>
As it is easy to forget to escape the "$", you can also choose your own
special character to use instead of '$'. Choose a character that will not
occur in your key names, e.g. ":", and add the following line to php.ini:
mongo.cmd = ":"
Then the example above would look like:
array( ":gt" => 20, ":lte" => 30 ) );
?>
You can also change it in your code using ini_set("mongo.cmd", ":"). Of
course, you can also just use single quotes around the $.
Creating An Index
MongoDB supports indexes, and they are very easy to add on a collection.
To create an index, you specify the field name and direction: ascending
(1) or descending (-1). The following creates an ascending index on the
"i" field:
ensureIndex( array( "i" => 1 ) ); // create index on "i"
$coll->ensureIndex( array( "i" => -1, "j" => 1 ) ); // index on "i" descending, "j" ascending
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
SQL to Mongo Mapping Chart
This is a PHP-specific version of the >> SQL to Mongo mapping chart in the
main docs.
SQL Statement Mongo Query Language Statement
CREATE TABLE USERS (a Implicit or use MongoDB::createCollection().
Number, b Number)
INSERT INTO USERS $db->users->insert(array("a" => 1, "b" => 1));
VALUES(1,1)
SELECT a,b FROM users $db->users->find(array(), array("a" => 1, "b" =>
1));
SELECT * FROM users $db->users->find(array("age" => 33));
WHERE age=33
SELECT a,b FROM users $db->users->find(array("age" => 33), array("a" => 1,
WHERE age=33 "b" => 1));
SELECT a,b FROM users $db->users->find(array("age" => 33), array("a" => 1,
WHERE age=33 "b" => 1));
SELECT a,b FROM users $db->users->find(array("age" => 33), array("a" => 1,
WHERE age=33 ORDER BY "b" => 1))->sort(array("name" => 1));
name
SELECT * FROM users $db->users->find(array("age" => array('$gt' =>
WHERE age>33 33)));
SELECT * FROM users $db->users->find(array("age" => array('$lt' =>
WHERE age<33 33)));
SELECT * FROM users $db->users->find(array("name" => new
WHERE name LIKE MongoRegex("/Joe/")));
"%Joe%"
SELECT * FROM users $db->users->find(array("name" => new
WHERE name LIKE MongoRegex("/^Joe/")));
"Joe%"
SELECT * FROM users $db->users->find(array("age" => array('$gt' => 33,
WHERE age>33 AND '$lte' => 40)));
age<=40
SELECT * FROM users $db->users->find()->sort(array("name" => -1));
ORDER BY name DESC
CREATE INDEX
myindexname ON $db->users->ensureIndex(array("name" => 1));
users(name)
CREATE INDEX $db->users->ensureIndex(array("name" => 1, "ts" =>
myindexname ON -1));
users(name,ts DESC)
SELECT * FROM users $db->users->find(array("a" => 1, "b" => "q"));
WHERE a=1 and b='q'
SELECT * FROM users $db->users->find()->limit(10)->skip(20);
LIMIT 10 SKIP 20
SELECT * FROM users $db->users->find(array('$or' => array(array("a" =>
WHERE a=1 or b=2 1), array("b" => 2))));
SELECT * FROM users $db->users->find()->limit(1);
LIMIT 1
EXPLAIN SELECT * FROM $db->users->find(array("z" => 3))->explain()
users WHERE z=3
SELECT DISTINCT $db->command(array("distinct" => "users", "key" =>
last_name FROM users "last_name"));
SELECT COUNT(*y) FROM $db->users->count();
users
SELECT COUNT(*y) FROM $db->users->find(array("age" => array('$gt' =>
users where AGE > 30 30)))->count();
SELECT COUNT(AGE) $db->users->find(array("age" => array('$exists' =>
from users true)))->count();
UPDATE users SET a=1 $db->users->update(array("b" => "q"), array('$set'
WHERE b='q' => array("a" => 1)));
UPDATE users SET $db->users->update(array("b" => "q"), array('$inc =>
a=a+2 WHERE b='q' array("a" => 2)));
DELETE FROM users $db->users->remove(array("z" => "abc"));
WHERE z="abc"
----------------------------------------------------------------------
----------------------------------------------------------------------
Connecting
Connecting to MongoDB can be as easy as new Mongo, but there are many
additional options and configurations. The Mongo::__construct() page
covers all of the API options, but this page gives some more details and
advice for practical use cases.
Logging In on Connection
If MongoDB is started with the --auth or --keyFile options, you must log
in before you can do any operations with the driver. You can log in on
connection by supplying the username and password in the connection URI:
If your connection is dropped, the driver will automatically attempt to
reconnect and reauthenticate you.
You can also authenticate on a per-database level with
MongoDB::authenticate():
admin;
$db->authenticate($username, $password);
?>
There is a major disadvantage to this method: if the database connection
is dropped and then reconnected, the connection will no longer be
authenticated.
If you use the URI format, the driver will authenticate the user against
the admin database. To authenticate with a different database, specify the
database name after the hosts. This example will log the user into the
"blog" database:
Replica Sets
To connect to a replica set, specify one or more members of the set and
use the replicaSet option.
"myReplSetName"));
?>
Version 1.0.9+ of the driver is required to connect to a replica set
(earlier versions of the driver will not autodetect the master or
reconnect correctly).
The PHP driver will query the database server(s) listed to figure out who
is master. So long as it can connect to at least one host listed and find
a master, the connection will succeed. If it cannot make a connection to
any servers listed or cannot find a master, a MongoConnectionException
will be thrown.
If the master becomes unavailable, the slaves will not promote a new
master for a few seconds. During that time, this connection will not be
able to perform any database operations (connections to slaves will still
be able to perform reads). Thus, if you attempt to do any sort of read or
write on this connection, it will throw an exception.
Once a master is elected, attempting to perform a read or write will allow
the driver to detect the new master. The driver will make this its primary
database connection and continue operating normally.
For more information on replica sets, see the >> core documentation.
Domain Socket Support
If you are running MongoDB locally and have version 1.0.9 or better of the
driver, you can connect to the database via file. MongoDB automatically
opens a socket file on startup: /tmp/mongodb-.sock.
To connect to the socket file, specify the path in your MongoDB connection
string:
If you would like to use authentication on connection (as described above)
with a socket file, you must specify a port of 0 so that the connection
string parser knows where the end of the connection string is.
Connection Pooling
In version 1.2.0+, the driver will automatically manage connection pools
for the user.
When a user creates a new instance of Mongo, all necessary connections
will be taken from their pools (replica set connections may require
multple connections). When the Mongo instance goes out of scope, the
connections will be returned to the pool.
Persistent Connections
Note:
This section is not relevant for 1.2.0+. In 1.2.0+, connections are
always persistent and managed automatically by the driver.
Creating new connection to the database is very slow. To minimize the
number of connections that you need to make, you can use persistent
connections. A persistent connection is saved by PHP, so you can use the
same connection for multiple requests.
For example, this simple program connects to the database 1000 times:
It takes approximately 18 seconds to execute. If we change it to use a
persistent connection:
"x"));
}
?>
...it takes less than .02 seconds to execute, as it only makes one
database connection.
Persistent connections need an identifier string (which is "x" in the
above example) to uniquely identify them. For a persistent connection to
be used, the hostname, port, persist string, and username and password (if
given) must match an existing persistent connection. Otherwise, a new
connection will be created with this identifying information.
Persistent connections are highly recommended and should always be used in
production unless there is a compelling reason not to. Most of the reasons
that they are not recommended for relational databases are irrelevant to
MongoDB.
Persistent connections will become the default connection type in 1.0.12.
To create a non-persistent connection, you will need to pass "persist" =>
false to Mongo::__construct().
----------------------------------------------------------------------
----------------------------------------------------------------------
Writes
Safe Operations
By default, the driver does not wait for a database response to writes
(inserts, updates, and deletes). This means that writes can be performed
extremely quickly, but you don't know whether or not they actually
succeeded. Writes can fail for a number of reasons: if there are network
problems, if a database server goes down, or if the write was simply
invalid (e.g., writing to a system collection).
To get a response from the database, use the safe option, available for
all types of writes. This option will make sure that the database has the
write before returning success. If the write failed, it will throw a
MongoCursorException() with an explanation of the failure.
While developing, you should always use safe writes (to protect against
inadvertent mistakes, such as duplicate key errors and similar). In
production, unsafe writes can be used for "unimportant" data. Unimportant
data varies on application, but it's generally automatically (instead of
user generated) data, such as click tracking or GPS locations, where you
can get thousands of records per second.
To safely perform writes without incurring too large a performance
penalty, it is recommended that you do a safe write at the end of a series
of writes. For example:
$collection->insert($someDoc);
$collection->update($criteria, $newObj);
$collection->insert($somethingElse);
$collection->remove($something, array("safe" => true));
Then, if the last write throws an exception, you know that there's a
problem with your database.
There are a few other options available to ensure the safety of writes.
You can specify "fsync" => true to force the database to fsync all writes
up to this point to disk (by default, MongoDB fsyncs writes once per
minute).
The safest way of doing a write is to use replication and specify the
number of servers that must have this write before returning success. (You
should always use replication in production, see the Connecting section
for more information on replica sets.)
$collection->insert($someDoc, array("safe" => 3));
If you specify "safe" => N, the MongoDB server will make sure that at
least N servers have a copy of the write before returning success. So, if
N is 3, the master and two slaves must have the write.
Updating Nested Objects
Suppose we wish to change the name of a comment's author in this document:
{
"_id" : ObjectId("4b06c282edb87a281e09dad9"),
"content" : "this is a blog post.",
"comments" :
[
{
"author" : "Mike",
"comment" : "I think that blah blah blah...",
},
{
"author" : "John",
"comment" : "I disagree."
}
]
}
In order to change an inner field, we use $set (so that all of the other
fields are not removed!) with the index of comment to change:
update($criteria, array('$set' => array("comments.1" => array("author" => "Jim"))));
?>
The Positional Operator
The positional operator $ is useful for updating objects that are in
arrays. In the example above, for instance, suppose that we did not know
the index of the comment that we needed to change, merely that we needed
to change "John" to "Jim". We can use $ to do so.
update(
array("comments.author" => "John"),
array('$set' => array('comments.$.author' => "Jim")));
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
Querying
Distributing queries to slaves
Note: 1.1.0+
If you are using a >> replica set and version 1.1.0 or above of the
driver, the driver can automatically route reads to slaves. This
behavior does not exist in earlier versions of the driver and cannot be
used with "normal" master-slave.
By default, the driver will send all queries to the master. If you set the
"slaveOkay" option, the driver will send all queries to a non-primary
server, if possible. The "slaveOkay" option can be set at every "level":
connection, database, collection, and cursor. Each class inherits the
"slaveOkay" setting from the class above it, so if you do:
setSlaveOkay(true);
$c = $db->myCollection;
$cursor = $c->find();
?>
then the query will be executed against a slave (the collection inherited
"slaveOkay" from the database and the cursor inherited it from the
collection).
How slaves are chosen
Each instance of Mongo chooses its own slave using the available slave
with the lowest ping time. So, if we had a PHP client in Europe and one in
Australia and we had one secondary in each of these data centers, we could
do:
true));
$m1->foo->bar->find()->slaveOkay()->getNext();
echo "m1's slave is ".$m1->getSlave()."\n";
// on the European client
$m2 = new Mongo("mongodb://P", array("replicaSet" => true));
$m2->foo->bar->find()->slaveOkay()->getNext();
echo "m2's slave is ".$m2->getSlave()."\n";
?>
we'd probably end up with something like:
m1's slave is: australianHost
m2's slave is: europeanHost
Note that we have to do a query before a slave is chosen: slaves are
chosen lazily by the driver. Mongo::getSlave() will return NULL until a
slave is used.
You can see what the driver thinks is the current status of the set
members by running Mongo::getHosts().
If no non-primary server is readable, the driver will send reads to the
primary (even if "slaveOkay" is set). A server is considered readable if
its state is 2 (SECONDARY) and its health is 1. You can check this with
Mongo::getHosts().
If you enjoy twiddling knobs that you probably shouldn't mess with, you
can request the driver to use a different slave by calling
Mongo::switchSlave(). This may choose a new slave (if one is available)
and shouldn't be used unless you know what you're doing.
Random notes
Writes are always sent to the primary. Database commands, even read-only
commands, are also always sent to the primary.
The health and state of a slave is checked every 5 seconds or when the
next operation occurs after 5 seconds. It will also recheck the
configuration when the driver has a problem reaching a server.
Note that a non-primary server may be behind the primary in operations, so
your application must be okay with getting out-of-date data (or you must
use w for all writes).
Querying by _id
Every object inserted is automatically assigned a unique _id field, which
is often a useful field to use in queries.
Suppose that we wish to find the document we just inserted. Inserting adds
and _id field to the document, so we can query by that:
"joe");
$people->insert($person);
// now $joe has an _id field
$joe = $people->findOne(array("_id" => $person['_id']));
?>
Unless the user has specified otherwise, the _id field is a MongoId. The
most common mistake is attepting to use a string to match a MongoId. Keep
in mind that these are two different datatypes, and will not match each
other in the same way that the string "array()" is not the same as an
empty array. For example:
"joe");
$people->insert($person);
// convert the _id to a string
$pid = $person['_id'] . "";
// FAILS - $pid is a string, not a MongoId
$joe = $people->findOne(array("_id" => $pid));
?>
Arrays
Arrays are special in a couple ways. First, there are two types that
MongoDB uses: "normal" arrays and associative arrays. Associative arrays
can have any mix of key types and values. "Normal" arrays are defined as
arrays with ascending numeric indexes starting at 0 and increasing by one
for each element. These are, typically, just your usual PHP array.
For instance, if you want to save a list of awards in a document, you
could say:
save(array("awards" => array("gold", "silver", "bronze")));
?>
Queries can reach into arrays to search for elements. Suppose that we wish
to find all documents with an array element of a given value. For example,
documents with a "gold" award, such as:
{ "_id" : ObjectId("4b06c282edb87a281e09dad9"), "awards" : ["gold", "silver", "bronze"]}
This can be done with a simple query, ignoring the fact that "awards" is
an array:
find(array("awards" => "gold"));
?>
Suppose we are querying for a more complex object, if each element of the
array were an object itself, such as:
{
"_id" : ObjectId("4b06c282edb87a281e09dad9"),
"awards" :
[
{
"first place" : "gold"
},
{
"second place" : "silver"
},
{
"third place" : "bronze"
}
]
}
Still ignoring that this is an array, we can use dot notation to query the
subobject:
find(array("awards.first place" => "gold"));
?>
Notice that it doesn't matter that there is a space in the field name
(although it may be best not to use spaces, just to make things more
readable).
You can also use an array to query for a number of possible values. For
instance, if we were looking for documents "gold" or "copper", we could
do:
find(array("awards" => array('$in' => array("gold", "copper"))));
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
Updates
Updates can be one of the most complicated operation available with
MongoDB. They combine a query with an action, modifying documents that
match the criteria. They are also extremely powerful, allowing you to
change documents quickly and replace them altogether. They are done
in-place (when possible) with little overhead.
Modifying vs. replacing documents
There are two types of updates you can use: modifying updates and
replacing updates. Modifying updates contain $-operators and change fields
in a document: they might increment counters, push new elements onto an
array, or change the type of a field.
For example, a modifying update could add a new field to a document.
/** suppose documents look like:
* {"username" : "...", "password" : "...", "email" : "..."}
*/
$coll->update(array("username" => "joe"), array('$set' => array("twitter" => "@joe4153")));
/** now the document will look like:
* {"username" : "joe", "password" : "...", "email" : "...", "twitter" : "@joe4153"}
*/
Replacing updates replace the entire matching document with a new
document. They are generally not as efficient as using $-modifiers, but
can be very usefully for complex operations or updates that can't be
expressed in terms of $-operators.
For example, a replacing update can completely change the structure of a
document.
/** suppose documents look like:
* {"username" : "...", "password" : "...", "email" : "..."}
*/
$coll->update(array("username" => "joe"), array("userId" => 12345, "info" => array(
"name" => "joe", "twitter" => "@joe4153", "email" => "..."), "likes" => array()));
/** now the document will look like:
* {
* "userId" : 12345,
* "info" : {
* "name" : "joe",
* "twitter" : "@joe4153",
* "email" : "..."
* },
* "likes" : []
* }
*/
Updating Nested Objects
Suppose we wish to change the name of a comment's author in this document:
{
"_id" : ObjectId("4b06c282edb87a281e09dad9"),
"content" : "this is a blog post.",
"comments" :
[
{
"author" : "Mike",
"comment" : "I think that blah blah blah...",
},
{
"author" : "John",
"comment" : "I disagree."
}
]
}
In order to change an inner field, we use $set (so that all of the other
fields are not removed!) with the index of comment to change:
update($criteria, array('$set' => array("comments.1" => array("author" => "Jim"))));
?>
The Positional Operator
The positional operator $ is useful for updating objects that are in
arrays. In the example above, for instance, suppose that we did not know
the index of the comment that we needed to change, merely that we needed
to change "John" to "Jim". We can use $ to do so.
update(
array("comments.author" => "John"),
array('$set' => array('comments.$.author' => "Jim")));
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
php.ini Options
The behaviour of these functions is affected by settings in php.ini.
Mongo Configure Options
Name Default Changeable
mongo.native_long false* PHP_INI_ALL
mongo.long_as_object false PHP_INI_ALL
mongo.default_host "localhost" PHP_INI_ALL
mongo.default_port 27017 PHP_INI_ALL
mongo.auto_reconnect true PHP_INI_SYSTEM
mongo.allow_persistent true PHP_INI_SYSTEM
mongo.chunk_size 262144 PHP_INI_SYSTEM
mongo.cmd "$" PHP_INI_ALL
mongo.utf8 "1" PHP_INI_ALL
mongo.allow_empty_keys false PHP_INI_ALL
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
mongo.native-long int
The default behavior for this will be changed to TRUE in 2.0.0, so
make sure to set this variable to the value you want (probably
TRUE) so that the driver's behavior doesn't suddenly change when
you upgrade.
On 64-bit platforms, the mongo.native_long setting allows for
64-bit integers to be stored in MongoDB. If it is not set, only
32-bits of the integer will be saved. The MongoDB data type that
is used in this case is the BSON LONG, instead of the BSON INT
that is used if this setting is turned off.
The setting also changes the way how BSON LONGs behave when they
are read back from MongoDB. Without mongo.native_long enabled, the
driver would convert every BSON LONG to a PHP double which can
result in a loss of precision.
On 32-bit platforms, the mongo.native_log setting changes nothing
for storing integers in MongoDB: the integer is stored as a BSON
INT as before. However, when the setting is enabled and a BSON
LONG is read from MongoDB a MongoCursorException is thrown
alerting you that the data could not be read back without losing
precision.
On 32-bit systems especially, it is recommended that you combine
this with enabling mongo.long_as_object.
mongo.long_as_object string
Return a BSON_LONG as an instance of MongoInt64 (instead of a
primitive type).
mongo.default_host string
Default hostname when nothing is passed to the constructor.
mongo.default_port string
The default TCP port number to use when connecting to the database
server if no other port is specified. The database's default is
27017.
mongo.auto_reconnect bool
Whether to reconnect to the database if the connection is lost.
mongo.allow_persistent bool
If persistent connections are allowed.
mongo.chunk_size int
The number of bytes-per-chunk. Used in divvying up GridFS files.
This number must be at least 100 less than 4 megabytes (max:
4194204) and it is recommended that it be less than that.
mongo.cmd string
A character to be used in place of $ in modifiers and comparisons.
mongo.utf8 int
If an exception should be thrown for non-UTF8 strings. Until
version 1.0.4, the PHP driver would ignore non-UTF8 strings, even
though you're not supposed to insert them. As of 1.0.4, the driver
throws a MongoException. To ease the transition for applications
that insert non-UTF8 strings, you can turn this option off to
emulate the old, non-exception-throwning behavior. This option
will be eliminated and exceptions always thrown for non-UTF8
strings starting with version 1.1.0.
mongo.allow_empty_keys int
Added in version 1.0.11.
If empty strings ("") should be allowed as key names. By default,
the driver will throw an exception if you attempt to pass the
empty string as a key to the database. It is extremely easy to do
this inavertently by using double quotes with $-operators, so it
is recommended that you leave this setting as default. However, if
you need to save keys that are empty strings, you can set this
option to true and the driver will allow you to pass empty strings
to the database.
----------------------------------------------------------------------
----------------------------------------------------------------------
Security
Request Injection Attacks
If you are passing $_GET parameters to your queries, make sure that they
are cast to strings first. Users can insert associative arrays in GET
requests, which could then become unwanted $-queries.
A fairly innocuous example: suppose you are looking up a user's
information with the request http://www.example.com?username=bob. Your
application does the query $collection->find(array("username" =>
$_GET['username'])).
Someone could subvert this by getting
http://www.example.com?username[$ne]=foo, which PHP will magically turn
into an associative array, turning your query into
$collection->find(array("username" => array('$ne' => "foo"))), which will
return all users not named "foo" (all of your users, probably).
This is a fairly easy attack to defend against: make sure $_GET's
parameters are the type you expect before you send them to the database
(cast them to strings, in this case).
Note that this type of attack can be used with any databases interation
that locates a document, including updates, upserts, find-and-modifies,
and removes.
Thanks to >> Phil for pointing this out.
See >> the main documentation for more information about
SQL-injection-like issues with MongoDB.
Script Injection Attacks
If you are using JavaScript, make sure that any variables that cross the
PHP- to-JavaScript boundry are passed in the scope field of MongoCode, not
interpolated into the JavaScript string. This can come up when using
MongoDB::execute(), $where clauses, MapReduces, group-bys, and any other
time you may pass JavaScript into the database.
Note:
MapReduce ignore the scope field of MongoCode, but there is a scope
option on the command that can be used instead.
For example, suppose we have some JavaScript to greet a user in the
database logs. We could do:
execute("print('Hello, $username!');");
?>
However, what if a malicious user passes in some JavaScript?
execute("print('Hello, $username!');");
?>
Now MongoDB executes the JavaScript string "print('Hello, ');
db.users.drop(); print('!');". This attack is easy to avoid: use scope to
pass variables from PHP to JavaScript:
$username);
$db->execute(new MongoCode("print('Hello, '+user+'!');", $scope));
?>
This adds a variable user to the JavaScript scope. Now if someone tries to
send malicious code, MongoDB will harmlessly print Hello, ');
db.dropDatabase(); print('!.
Using scope helps prevent malicious input from being executed by the
database. However, you must make sure that your code does not turn around
and execute the input anyway! For example, never use the JavaScript eval
function on user input:
$jsShellInput);
$db->execute(new MongoCode("eval(input);", $scope));
?>
Always use scope and never allow the database to execute user input as
code.
----------------------------------------------------------------------
----------------------------------------------------------------------
Running the Driver's Tests
The PECL package does not come with the tests, but they are available at
>> Github. There are two types of tests: the PHPUnit tests and the C
tests.
PHPUnit Tests
To run the tests, you must download the driver from Github (the tests are
in the tests/ directory). You'll also need >> PHPUnit to run the tests.
PHPUnit can be installed via PEAR (although you should look at the
installation instructions, it requires a couple of prerequisites).
Some tests expect warnings or errors, so you must set error_reporting in
php.ini to E_STRICT | E_ALL for these tests to pass. If you do not, you
will get some failures that say the test was expecting a warning or error.
To run the tests, make sure that there is a MongoDB server running locally
on port 27017. Before reporting errors, please try running the tests
against the latest development version of MongoDB: often there are tests
for features that aren't yet in the stable release.
The test suite uses the "phpunit" database. If you are using a database
called "phpunit" in your application, make sure point MongoDB at a
different data directory before running the tests.
Make sure you're in the main directory of the driver source you downloaded
from Github. Run:
$ phpunit tests/MongoSuite.php
C Tests
The C tests mostly check internal functions that are not exposed through
PHP. If you'd like to run these tests, you'll need to compile PHP with the
--enable-embed flag. Then switch to the tests directory and run make. This
will create a binary called unit. Run unit to execute the tests. These
tests do no require a database to be running.
If a test passes, it will print a ".". If a test fails, it will assert and
stop the tests. Please report any asserts.
If make cannot find your PHP embedded library (libphp5.so) or header
files, you may have to specify the PHP_PATH variable.
Run make clean to remove all testing objects.
If you run these tests with valgrind, you should get no invalid memory
access errors and the "no leaks are possible" message at the end.
Reporting Errors
Please report any failures or errors in the >> bugtracker. There may be
skipped tests, these are normal and can be ignored.
New tests are always welcome! Please feel free to contribute new tests of
any type testing any functionality.
----------------------------------------------------------------------
----------------------------------------------------------------------
Troubleshooting
If you're having trouble, there are lots of resources you can turn to.
* IRC
The official MongoDB IRC room is irc.freenode.net/#mongodb. This is
the fastest way to get help... if there are people around.
* Mailing List
>> MongoDB's mailing list is a good (and usually very fast) way to get
answers to questions.
* Bug Tracker
Found a bug? Want a feature? Have a question? File it in the >> PHP
driver's bug tracker.
You can turn on (very) verbose debugging output by compiling the driver
with the debugging flag.
$ ./configure CFLAGS=-DDEBUG
DEBUG turns on all debugging. You can also turn on specific debug flags.
In the latest code, these flags are:
* DEBUG_CONN
Debugging connections.
----------------------------------------------------------------------
See Also
>> Developing Scalable PHP Applications Using MongoDB is an excellent
article on getting started with MongoDB. For francophones, >> NoSQL -
MongoDB et PHP: Premiere Approche gives a nice overview.
----------------------------------------------------------------------
----------------------------------------------------------------------
Core Classes
Table of Contents
* Mongo
* MongoDB
* MongoCollection
* MongoCursor
The core classes are the most important part of the driver.
----------------------------------------------------------------------
The Mongo class
Introduction
A connection between PHP and MongoDB.
This class is used to create and manage connections. A typical use is:
foo; // get the database named "foo"
?>
See Mongo::__construct() and the section on connecting for more
information about creating connections.
Class synopsis
Mongo {
/* Constants */
const string VERSION ;
const string DEFAULT_HOST = "localhost" ;
const int DEFAULT_PORT = 27017 ;
/* Fields */
public boolean $Mongo->connected = FALSE ;
public string $status = NULL ;
protected string $server = NULL ;
protected boolean $persistent = NULL ;
/* Methods */
public bool Mongo::close ( void )
public bool Mongo::connect ( void )
protected bool Mongo::connectUtil ( void )
Mongo::__construct ([ string $server = "mongodb://localhost:27017" [,
array $options = array("connect" => TRUE) ]] )
public array Mongo::dropDB ( mixed $db )
public MongoDB Mongo::__get ( string $dbname )
public array Mongo::getHosts ( void )
public static int Mongo::getPoolSize ( void )
public string Mongo::getSlave ( void )
public bool Mongo::getSlaveOkay ( void )
public array Mongo::listDBs ( void )
public array Mongo::poolDebug ( void )
public MongoCollection Mongo::selectCollection ( string $db , string
$collection )
public MongoDB Mongo::selectDB ( string $name )
public bool Mongo::setPoolSize ( int $size )
public bool Mongo::setSlaveOkay ([ bool $ok = true ] )
public string Mongo::switchSlave ( void )
public string Mongo::__toString ( void )
}
Predefined Constants
Mongo Constants
Mongo::VERSION
PHP driver version. May be suffixed with "+" or "-" if it is
in-between versions.
Mongo::DEFAULT_HOST
"localhost"
Host to connect to if no host is given.
Mongo::DEFAULT_PORT
27017
Port to connect to if no port is given.
Fields
status
If this is a persistent connection, if the connection was created
for this object or is being reused. If this is not a persistent
connection, this field should be NULL.
See Also
MongoDB core docs on >> connecting.
----------------------------------------------------------------------
Mongo::close
(PECL mongo >=0.9.0)
Mongo::close - Closes this connection
Description
public bool Mongo::close ( void )
This method does not need to be called, except in unusual circumstances.
The driver will cleanly close the database connection when this Mongo
instance goes out of scope.
If objects do not go out of scope between requests, you may wish to call
this method at the end of your program to keep old connections from
hanging around. However, it is probably more efficient use a persistent
connection, which will automatically create a connection if needed and use
it for as many requests as possible.
If you are connected to a replica set, close() will only close the
connection to the primary.
Parameters
This function has no parameters.
Return Values
Returns if the connection was successfully closed.
----------------------------------------------------------------------
----------------------------------------------------------------------
Mongo::connect
(PECL mongo >=0.9.0)
Mongo::connect - Connects to a database server
Description
public bool Mongo::connect ( void )
Parameters
This function has no parameters.
Return Values
If the connection was successful.
Errors/Exceptions
Throws MongoConnectionException if it fails to connect to the database.
----------------------------------------------------------------------
----------------------------------------------------------------------
Mongo::connectUtil
(PECL mongo >=0.9.0)
Mongo::connectUtil - Connects with a database server
Description
protected bool Mongo::connectUtil ( void )
Parameters
This function has no parameters.
Return Values
If the connection was successful.
Errors/Exceptions
Throws MongoConnectionException if it fails to connect to the databases.
----------------------------------------------------------------------
----------------------------------------------------------------------
Mongo::__construct
(PECL mongo >=0.9.0)
Mongo::__construct - Creates a new database connection object
Description
Mongo::__construct ([ string $server = "mongodb://localhost:27017" [,
array $options = array("connect" => TRUE) ]] )
If no parameters are passed, this connects to "localhost:27017" (or
whatever was specified in php.ini for mongo.default_host and
mongo.default_port).
server should have the form:
mongodb://[username:password@]host1[:port1][,host2[:port2:],...]/db
The connection string always starts with mongodb://, to indicate it is a
connection string in this form.
If username and password are specified, the constructor will attempt to
authenticate the connection with the database before returning. Username
and password are optional and must be followed by an @, if specified.
At least one host must be given (port optional, always defaulting to
27017) and as many hosts as desired may be connected to. Host names are
comma-separated and the constructor will return successfully if it
connected to at least one host. If it could not connect to any of the
hosts, it will throw a MongoConnectionException.
Finally, if you specified a username and password, you may specify a
database to authenticate with. If db is not specified, "admin" will be
used.
Parameters
server
The server name.
options
An array of options for the connection. Currently available
options include:
* "connect"
If the constructor should connect before returning. Default
is TRUE.
* "timeout"
For how long the driver should try to connect to the database
(in milliseconds).
* "replicaSet"
The name of the replica set to connect to. If this is given,
the master will be determined by using the ismaster database
command on the seeds, so the driver may end up connecting to
a server that was not even listed. See the replica set
example below for details.
* "username"
The username can be specified here, instead of including it
in the host list. This is especially useful if a username has
a ":" in it.
* "password"
The password can be specified here, instead of including it
in the host list. This is especially useful if a password has
a "@" in it.
Return Values
Returns a new database connection object.
Errors/Exceptions
Throws MongoConnectionException if it tries and fails to connect to the
database for all hostnames given. It will also throw a
MongoConnnectionException if an invalid username or password is given. See
MongoConnectionException documentation for common exceptions and their
causes.
Changelog
Version Description
Changed constructor to
take an array of
options. Pre-1.0.2, the
Removed the persist option, as all constructor took the
connections are now persistent. It following parameters:
can still be used, but it doesn't
affect anything. server
"persist" The server name.
If the connection should be connect
persistent. If set, the
connection will be persistent. Optional boolean
The string representation of the parameter specifying
1.2.0 value is used as an id for the 1.0.2 if the constructor
connection, so two instances of should connect to
Mongo that are initialized with the database before
array("persist" => "foobar") will returning. Defaults
share the same database to TRUE.
connection, whereas an instance
initialized with array("persist" persistent
=> "barbaz") will use a different
database connection. If the connection
should be
The "replicaSet" parameter now takes persistent.
a string, not a boolean (although
boolean is still accepted). paired
If the connection
should be paired.
1.0.9 Added the replicaSet option.
1.2.0 Added the username and password
options.
Examples
Example #1 Mongo::__construct() replica set example
This example shows how to connect the driver to a replica set. It assumes
that there is a set of three servers: sf1.example.com, sf2.example.com,
and ny1.example.com. The master could be any one of these servers.
"myReplSet"));
// you only need to pass a single seed, the driver will derive the full list and
// find the master from this seed
$m2 = new Mongo("mongodb://ny1.example.com", array("replicaSet" => "myReplSet"));
?>
If the current master fails, the driver will figure out which secondary
server became the new master and automatically start using that
connection. Automatic failover will not work correctly if replicaSet is
not specified.
At least one seed in the seed list must be up for the driver to connect to
the replica set.
If you include seeds from two separate replica sets, behavior is
undefined.
See the >> core documentation on replica sets for more information.
Example #2 Connecting to a domain socket
In version 1.0.9+, you can use a UNIX domain socket to connect to an
instance of MongoDB running locally. This should be slightly faster than
using a network connection.
In version 1.5.0, the MongoDB server automatically opens a socket at
/tmp/mongodb-.sock. You can connect to this by specifying the path
in your connection string:
You can combine this with any other connections you'd like:
Example #3 Mongo::__construct() authentication example
A user must exist in the admin database before attempting to use
authentication. You can create one with the Mongo shell by running:
> use admin
switched to db admin
> db.addUser("testUser", "testPass");
{
"_id" : ObjectId("4b21272fd9ab21611d19095c"),
"user" : "testUser",
"pwd" : "03b9b27e0abf1865e2f6fcbd9845dd59"
}
>
After creating a user with, in this case, username "testUser" and password
"testPass", you can create an authenticated connection:
----------------------------------------------------------------------
----------------------------------------------------------------------
Mongo::dropDB
(PECL mongo >=0.9.0)
Mongo::dropDB - Drops a database [deprecated]
Description
public array Mongo::dropDB ( mixed $db )
Warning
Deprecated
Use MongoDB::drop() instead.
Parameters
db
The database to drop. Can be a MongoDB object or the name of the
database.
Return Values
Returns the database response.
----------------------------------------------------------------------
----------------------------------------------------------------------
Mongo::__get
(PECL mongo >=1.0.2)
Mongo::__get - Gets a database
Description
public MongoDB Mongo::__get ( string $dbname )
This is the cleanest way of getting a database. If the database name has
any special characters, Mongo::selectDB() will need to be used. However,
in most cases, this should be sufficient.
selectDB("foo");
$db = $mongo->foo;
?>
Parameters
dbname
The database name.
Return Values
Returns a new db object.
Errors/Exceptions
Throws a generic exception if the database name is invalid.
----------------------------------------------------------------------
----------------------------------------------------------------------
Mongo::getHosts
(PECL mongo >=1.1.0)
Mongo::getHosts - Updates status for all hosts associated with this
Description
public array Mongo::getHosts ( void )
This method can only be used with a connection to a replica set. It
returns the status of all of the hosts in the set.
See the query section of this manual for information on distributing reads
to slaves.
Parameters
This function has no parameters.
Return Values
Returns an array of information about the hosts in the set. Includes each
host's hostname, its health (1 is healthy), its state (1 is primary, 2 is
secondary, 0 is anything else), the amount of time it took to ping the
server, and when the last ping occurred. For example, on a three-member
replica set, it might look something like:
array(2) {
["A:27017"]=>
array(4) {
["health"]=>
int(1)
["state"]=>
int(2)
["ping"]=>
int(369)
["lastPing"]=>
int(1309470644)
}
["B:27017"]=>
array(4) {
["health"]=>
int(1)
["state"]=>
int(1)
["ping"]=>
int(139)
["lastPing"]=>
int(1309470644)
}
["C:27017"]=>
array(4) {
["health"]=>
int(1)
["state"]=>
int(2)
["ping"]=>
int(1012)
["lastPing"]=>
int(1309470644)
}
}
In the example above, B and C are secondaries (state 2). B is likely to be
selected for queries if slaveOkay is set, as it has a lower ping time (and
thus is likely closer or handling less load) than C.
----------------------------------------------------------------------
----------------------------------------------------------------------
Mongo::getPoolSize
(No version information available, might only be in SVN)
Mongo::getPoolSize - Get pool size for connection pools
Description
public static int Mongo::getPoolSize ( void )
Parameters
This function has no parameters.
Return Values
Returns the current pool size.
Examples
Example #1 Changing pool size
This returns the default pool size, sets a new pool size, then prints the
new pool size and the pool debugging information. Note that changing the
pool size only affects new connection pools, it does not change old ones.
See Also
* Mongo::setPoolSize() - Set the size for future connection pools.
* Mongo::poolDebug() - Returns information about all connection pools.
* The connection documentation.
----------------------------------------------------------------------
----------------------------------------------------------------------
Mongo::getSlave
(PECL mongo >=1.1.0)
Mongo::getSlave - Returns the address being used by this for slaveOkay
reads
Description
public string Mongo::getSlave ( void )
This finds the address of the slave currently being used for reads. It is
a read-only method: it does not change anything about the internal state
of the object.
When you create a connection to the database, the driver will not
immediately decide on a slave to use. Thus, after you connect, this
function will return NULL even if there are slaves available. When you
first do a query with slaveOkay set, at that point the driver will choose
a slave for this connection. At that point, this function will return the
chosen slave.
See the query section of this manual for information on distributing reads
to slaves.
Parameters
This function has no parameters.
Return Values
The address of the slave this connection is using for reads.
This returns NULL if this is not connected to a replica set or not yet
initialized.
----------------------------------------------------------------------
----------------------------------------------------------------------
Mongo::getSlaveOkay
(PECL mongo >=1.1.0)
Mongo::getSlaveOkay - Get slaveOkay setting for this connection
Description
public bool Mongo::getSlaveOkay ( void )
See the query section of this manual for information on distributing reads
to slaves.
Parameters
This function has no parameters.
Return Values
Returns the value of slaveOkay for this instance.
----------------------------------------------------------------------
----------------------------------------------------------------------
Mongo::listDBs()
(No version information available, might only be in SVN)
- Lists all of the databases available.
Description
public array Mongo::listDBs ( void )
Parameters
This function has no parameters.
Return Values
Returns an associative array containing three fields. The first field is
databases, which in turn contains an array. Each element of the array is
an associative array corresponding to a database, giving the database's
name, size, and if it's empty. The other two fields are totalSize (in
bytes) and ok, which is 1 if this method ran successfully.
Examples
Example #1 Mongo::listDBs() example
Example demonstrating how to use listDBs and the returned data structure.
listDBs();
print_r($dbs);
?>
The above example will output something similar to:
Array
(
[databases] => Array
(
[0] => Array
(
[name] => doctrine
[sizeOnDisk] => 218103808
[empty] =>
)
)
[totalSize] => 218103808
[ok] => 1
)
----------------------------------------------------------------------
----------------------------------------------------------------------
Mongo::poolDebug
(No version information available, might only be in SVN)
Mongo::poolDebug - Returns information about all connection pools.
Description
public array Mongo::poolDebug ( void )
Returns an array of information about all connection pools.
Parameters
This function has no parameters.
Return Values
Each connection pool has an identifier, which starts with the host. For
each pool, this function shows the following fields:
in use
The number of connections currently being used by Mongo instances.
in pool
The number of connections currently in the pool (not being used).
remaining
The number of connections that could be created by this pool. For
example, suppose a pool had 5 connections remaining and 3
connections in the pool. We could create 8 new instances of Mongo
before we exhausted this pool (assuming no instances of Mongo went
out of scope, returning their connections to the pool).
A negative number means that this pool will spawn unlimited
connections.
Before a pool is created, you can change the max number of
connections by calling Mongo::setPoolSize(). Once a pool is
showing up in the output of this function, its size cannot be
changed.
timeout
The socket timeout for connections in this pool. This is how long
connections in this pool will attempt to connect to a server
before giving up.
----------------------------------------------------------------------
----------------------------------------------------------------------
Mongo::selectCollection()
(No version information available, might only be in SVN)
- Gets a database collection
Description
public MongoCollection Mongo::selectCollection ( string $db , string
$collection )
Parameters
db
The database name.
collection
The collection name.
Return Values
Returns a new collection object.
Errors/Exceptions
Throws InvalidArgumentException if the database or collection name is
invalid.
Examples
Example #1 Mongo::selectCollection() example
selectCollection("foo", "bar.baz");
// which is equivalent to
$c2 = $m->selectDB("foo")->selectCollection("bar.baz");
// $c1 and $c2 now represent the same collection
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
Mongo::selectDB
(PECL mongo >=0.9.0)
Mongo::selectDB - Gets a database
Description
public MongoDB Mongo::selectDB ( string $name )
Parameters
name
The database name.
Return Values
Returns a new db object.
Errors/Exceptions
Throws InvalidArgumentException if the database name is invalid.
----------------------------------------------------------------------
----------------------------------------------------------------------
Mongo::setPoolSize
(No version information available, might only be in SVN)
Mongo::setPoolSize - Set the size for future connection pools.
Description
public bool Mongo::setPoolSize ( int $size )
Sets the max number of connections new pools will be able to create.
Parameters
size
The max number of connections future pools will be able to create.
Negative numbers mean that the pool will spawn an infinite number
of connections.
Return Values
Returns the former value of pool size.
----------------------------------------------------------------------
----------------------------------------------------------------------
Mongo::setSlaveOkay
(PECL mongo >=1.1.0)
Mongo::setSlaveOkay - Change slaveOkay setting for this connection
Description
public bool Mongo::setSlaveOkay ([ bool $ok = true ] )
See the query section of this manual for information on distributing reads
to slaves.
Parameters
ok
If reads should be sent to secondary members of a replica set for
all possible queries using this Mongo instance.
Return Values
Returns the former value of slaveOkay for this instance.
----------------------------------------------------------------------
----------------------------------------------------------------------
Mongo::switchSlave
(PECL mongo >=1.1.0)
Mongo::switchSlave - Choose a new slave for slaveOkay reads
Description
public string Mongo::switchSlave ( void )
This choses a random slave for a connection to read from. It is called
automatically by the driver and should not need to be used. It calls
Mongo::getHosts() (to refresh the status of hosts) and Mongo::getSlave()
(to get the return value).
See the query section of this manual for information on distributing reads
to slaves.
Parameters
This function has no parameters.
Return Values
The address of the slave this connection is using for reads. This may be
the same as the previous address as addresses are randomly chosen. It may
return only one address if only one secondary (or only the primary) is
available.
For example, if we had a three member replica set with a primary,
secondary, and arbiter this method would always return the address of the
secondary. If the secondary became unavailable, this method would always
return the address of the primary. If the primary also became unavailable,
this method would throw an exception, as an arbiter cannot handle reads.
Errors/Exceptions
Throws a MongoException (error code 15) if it is called on a
non-replica-set connection. It will also throw MongoExceptions if it
cannot find anyone (primary or secondary) to read from (error code 16).
----------------------------------------------------------------------
----------------------------------------------------------------------
Mongo::__toString
(PECL mongo >=0.9.0)
Mongo::__toString - String representation of this connection
Description
public string Mongo::__toString ( void )
Parameters
This function has no parameters.
Return Values
Returns hostname and port for this connection.
----------------------------------------------------------------------
Table of Contents
* Mongo::close - Closes this connection
* Mongo::connect - Connects to a database server
* Mongo::connectUtil - Connects with a database server
* Mongo::__construct - Creates a new database connection object
* Mongo::dropDB - Drops a database [deprecated]
* Mongo::__get - Gets a database
* Mongo::getHosts - Updates status for all hosts associated with this
* Mongo::getPoolSize - Get pool size for connection pools
* Mongo::getSlave - Returns the address being used by this for slaveOkay
reads
* Mongo::getSlaveOkay - Get slaveOkay setting for this connection
* Mongo::listDBs - Lists all of the databases available.
* Mongo::poolDebug - Returns information about all connection pools.
* Mongo::selectCollection - Gets a database collection
* Mongo::selectDB - Gets a database
* Mongo::setPoolSize - Set the size for future connection pools.
* Mongo::setSlaveOkay - Change slaveOkay setting for this connection
* Mongo::switchSlave - Choose a new slave for slaveOkay reads
* Mongo::__toString - String representation of this connection
----------------------------------------------------------------------
----------------------------------------------------------------------
The MongoDB class
Introduction
Instances of this class are used to interact with a database. To get a
database:
selectDB("example");
?>
Database names can use almost any character in the ASCII range. However,
they cannot contain " ", "." or be the empty string. The name "system" is
also reserved.
A few unusual, but valid, database names: "null", "[x,y]", "3", "\"", "/".
Unlike collection names, database names may contain "$".
Class synopsis
MongoDB {
/* Constants */
const int PROFILING_OFF = 0 ;
const int PROFILING_SLOW = 1 ;
const int PROFILING_ON = 2 ;
/* Fields */
public integer $MongoDB->w = 1 ;
public integer $wtimeout = 10000 ;
/* Methods */
public array MongoDB::authenticate ( string $username , string $password )
public array MongoDB::command ( array $command )
MongoDB::__construct ( Mongo $conn , string $name )
public MongoCollection MongoDB::createCollection ( string $name [, bool
$capped = FALSE [, int $size = 0 [, int $max = 0 ]]] )
public array MongoDB::createDBRef ( string $collection , mixed $a )
public array MongoDB::drop ( void )
public array MongoDB::dropCollection ( mixed $coll )
public array MongoDB::execute ( mixed $code [, array $args = array() ] )
public bool MongoDB::forceError ( void )
public MongoCollection MongoDB::__get ( string $name )
public array MongoDB::getDBRef ( array $ref )
public MongoGridFS MongoDB::getGridFS ([ string $prefix = "fs" ] )
public int MongoDB::getProfilingLevel ( void )
public bool MongoDB::getSlaveOkay ( void )
public array MongoDB::lastError ( void )
public array MongoDB::listCollections ( void )
public array MongoDB::prevError ( void )
public array MongoDB::repair ([ bool $preserve_cloned_files = FALSE [,
bool $backup_original_files = FALSE ]] )
public array MongoDB::resetError ( void )
public MongoCollection MongoDB::selectCollection ( string $name )
public int MongoDB::setProfilingLevel ( int $level )
public bool MongoDB::setSlaveOkay ([ bool $ok = true ] )
public string MongoDB::__toString ( void )
}
Predefined Constants
MongoDB Log Levels
MongoDB::PROFILING_OFF
0
Profiling is off.
MongoDB::PROFILING_SLOW
1
Profiling is on for slow operations (>100 ms).
MongoDB::PROFILING_ON
2
Profiling is on for all operations.
Fields
w
1
The number of servers to replicate a change to before returning
success. Inherited by instances of MongoCollection derived from
this. w functionality is only available in version 1.5.1+ of the
MongoDB server and 1.0.8+ of the driver.
w is used whenever you perform a "safe" operation
(MongoCollection::insert(), MongoCollection::update(),
MongoCollection::remove(), MongoCollection::save(), and
MongoCollection::ensureIndex() all support safe options). With the
default value (1), a safe operation will return once the database
server has the operation. If the server goes down before the
operation has been replicated to a slave, it is possible to lose
the operation forever. Thus, you can specify w to be higher than
one and guarantee that at least one slave has the operation before
it is considered successful.
For example, if w is 2, the main server and one slave must have a
record of the operation or the driver will throw a
MongoCursorException. It is tempting to set w to the total number
of slaves + master, but then if one slave is down the op will fail
and an exception will be thrown, so usually w=2 is safest
(master+1 slave).
wtimeout
10000
The number of milliseconds to wait for MongoDB::$w replications to
take place. Inherited by instances of MongoCollection derived from
this. w functionality is only available in version 1.5.1+ of the
MongoDB server and 1.0.8+ of the driver.
Unless wtimeout is set, the server waits forever for replicating
to w servers to finish. The driver defaults to waiting for 10
seconds, you can change this value to alter its behavior.
See Also
MongoDB core docs on >> databases.
----------------------------------------------------------------------
MongoDB::authenticate
(PECL mongo >=1.0.1)
MongoDB::authenticate - Log in to this database
Description
public array MongoDB::authenticate ( string $username , string $password )
This method causes its connection to be authenticated. If authentication
is enabled for the database server (it's not, by default), you need to log
in before the database will allow you to do anything.
In general, you should use the authenticate built into
Mongo::__construct() in preference to this method. If you authenticate on
connection and the connection drops and reconnects during your session,
you'll be reauthenticated. If you manually authenticated using this method
and the connection drops, you'll have to call this method again once
you're reconnected.
This method is identical to running:
command(array("getnonce" => 1));
$saltedHash = md5($nonce["nonce"]."${username}${hash}");
$result = $db->command(array("authenticate" => 1,
"user" => $username,
"nonce" => $nonce["nonce"],
"key" => $saltedHash
));
?>
Once a connection has been authenticated, it can only be un-authenticated
by using the "logout" database command:
command(array("logout" => 1));
?>
Parameters
username
The username.
password
The password (in plaintext).
Return Values
Returns database response. If the login was successful, it will return
1);
?>
If something went wrong, it will return
0, "errmsg" => "auth fails");
?>
("auth fails" could be another message, depending on database version and
what when wrong).
See Also
MongoDB core docs on >> authenticate.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB::command
(PECL mongo >=0.9.2)
MongoDB::command - Execute a database command
Description
public array MongoDB::command ( array $command )
Almost everything that is not a CRUD operation can be done with a database
command. Need to know the database version? There's a command for that.
Need to do aggregation? There's a command for that. Need to turn up
logging? You get the idea.
This method is identical to:
selectCollection('$cmd')->findOne($data);
}
?>
Parameters
command
The query to send.
Changelog
Version Description
1.2.0 Added options parameter with a single option: timeout.
Return Values
Returns database response.
Examples
Example #1 MongoDB::command() "distinct" example
Finding all of the distinct values for a key.
people;
$people->insert(array("name" => "Joe", "age" => 4));
$people->insert(array("name" => "Sally", "age" => 22));
$people->insert(array("name" => "Dave", "age" => 22));
$people->insert(array("name" => "Molly", "age" => 87));
$ages = $db->command(array("distinct" => "people", "key" => "age"));
foreach ($ages['values'] as $age) {
echo "$age\n";
}
?>
The above example will output something similar to:
4
22
87
Example #2 MongoDB::command() MapReduce example
Get all users with at least on "sale" event, and how many times each of
these users has had a sale.
insert(array("user_id" => $id,
"type" => $type,
"time" => new MongoDate(),
"desc" => $description));
// construct map and reduce functions
$map = new MongoCode("function() { emit(this.user_id,1); }");
$reduce = new MongoCode("function(k, vals) { ".
"var sum = 0;".
"for (var i in vals) {".
"sum += vals[i];".
"}".
"return sum; }");
$sales = $db->command(array(
"mapreduce" => "events",
"map" => $map,
"reduce" => $reduce,
"query" => array("type" => "sale"),
"out" => array("merge" => "eventCounts")));
$users = $db->selectCollection($sales['result'])->find();
foreach ($users as $user) {
echo "{$user['_id']} had {$user['value']} sale(s).\n";
}
?>
The above example will output something similar to:
User 47cc67093475061e3d9536d2 had 3 sale(s).
User 49902cde5162504500b45c2c had 14 sale(s).
User 4af467e4fd543cce7b0ea8e2 had 1 sale(s).
Note: Using MongoCode
This example uses MongoCode, which can also take a scope argument.
However, at the moment, MongoDB does not support using scopes in
MapReduce. If you would like to use client-side variables in the
MapReduce functions, you can add them to the global scope by using the
optional scope field with the database command. See the >> MapReduce
documentation for more information.
Note: The out argument
Before 1.8.0, the out argument was optional. If you did not use it,
MapReduce results would be written to a temporary collection, which
would be deleted when your connection was closed. In 1.8.0+, the out
argument is required. See the >> MapReduce documentation for more
information.
If you are going to be using MapReduce, Prajwal Tuladhar created an API
for Mongo PHP users which provides a nicer interface than the bare
command. You can download it from >> Github and there is a >> blog post on
how to use it.
See Also
MongoDB core docs on >> database commands and on individual commands:
>> findAndModify, >> getLastError, and >> repair (dozens more exist, there
are merely a few examples).
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB::__construct
(PECL mongo >=0.9.0)
MongoDB::__construct - Creates a new database
Description
MongoDB::__construct ( Mongo $conn , string $name )
This method is not meant to be called directly. The preferred way to
create an instance of MongoDB is through Mongo::__get() or
Mongo::selectDB().
If you're ignoring the previous paragraph and want to call it directly you
can do so:
But don't. Isn't this much nicer:
mydbname;
// or, if the name contains weird characters:
$db = $m->selectDB('my,db:name');
?>
Parameters
Mongo conn
Database connection.
name
Database name.
Return Values
Returns the database.
Errors/Exceptions
Throws default exception if the database name is invalid.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB::createCollection
(PECL mongo >=0.9.0)
MongoDB::createCollection - Creates a collection
Description
public MongoCollection MongoDB::createCollection ( string $name [, bool
$capped = FALSE [, int $size = 0 [, int $max = 0 ]]] )
This method is used to create capped collections and other collections
requiring special options. It is identical to running:
command(array("create" => $name, "size" => $size, "capped" => $capped, "max" => $max));
?>
See MongoDB::command() for more information about database commands.
Parameters
name
The name of the collection.
capped
If the collection should be a fixed size.
size
If the collection is fixed size, its size in bytes.
max
If the collection is fixed size, the maximum number of elements to
store in the collection.
Return Values
Returns a collection object representing the new collection.
Examples
Example #1 MongoDB::createCollection() capped collection example
A capped collection is a special type of collection that has either a
fixed or a fixed number of elements. Once the collection is "full," the
oldest elements will be removed when new elements are added. Capped
collections can be very useful for applications like logging, where you
may want to reserve a certain amount of space for logs and not worry about
them getting too big.
This example creates a very tiny log collection that will keep a maximum
of 10 documents.
createCollection("logger", true, 10*1024, 10);
for ($i = 0; $i < 100; $i++) {
$log->insert(array("level" => WARN, "msg" => "sample log message #$i", "ts" => new MongoDate()));
}
$msgs = $log->find();
foreach ($msgs as $msg) {
echo $msg['msg']."\n";
}
?>
The above example will output something similar to:
sample log message #90
sample log message #91
sample log message #92
sample log message #93
sample log message #94
sample log message #95
sample log message #96
sample log message #97
sample log message #98
sample log message #99
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB::createDBRef
(PECL mongo >=0.9.0)
MongoDB::createDBRef - Creates a database reference
Description
public array MongoDB::createDBRef ( string $collection , mixed $a )
This method is a flexible interface for creating database refrences (see
MongoDBRef).
Parameters
collection
The collection to which the database reference will point.
a
Object or _id to which to create a reference. If an object or
associative array is given, this will create a reference using the
_id field.
Return Values
Returns a database reference array.
Examples
Example #1 MongoDB::createDBRef() example
Example demonstrating how to programatically create a DB reference array
from a document.
articles;
$article = array(
'title' => 'Test article',
'description' => 'Test article description'
);
$articles->insert($article);
$ref = $db->createDBRef('articles', $article);
print_r($article);
print_r($ref);
?>
The above example will output something similar to:
Array
(
[title] => Test article
[description] => Test article description
[_id] => MongoId Object
(
)
)
Array
(
[$ref] => articles
[$id] => MongoId Object
(
)
)
Now the $ref can be stored on another document and retrieved later with
MongoDB::getDBRef() or MongoCollection::getDBRef().
Example #2 MongoDB::createDBRef() example
Example demonstrating how to programatically create a DB reference from
just an id.
createDBRef('articles', $id);
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB::drop
(PECL mongo >=0.9.0)
MongoDB::drop - Drops this database
Description
public array MongoDB::drop ( void )
This drops the database currently being used.
This is identical to running:
command(array("dropDatabase" => 1));
}
?>
Parameters
This function has no parameters.
Return Values
Returns the database response.
Examples
Example #1 MongoDB::drop() example
This example demonstrates how to drop a mongo database and the response to
expect.
foo;
$response = $db->drop();
print_r($response);
?>
The above example will output something similar to:
Array
(
[dropped] => foo.$cmd
[ok] => 1
)
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB::dropCollection
(PECL mongo >=0.9.0)
MongoDB::dropCollection - Drops a collection [deprecated]
Description
public array MongoDB::dropCollection ( mixed $coll )
Warning
Deprecated
Use MongoCollection::drop() instead.
This function leaks memory in version 1.0.7 and earlier!
Parameters
coll
MongoCollection or name of collection to drop.
Return Values
Returns the database response.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB::execute
(PECL mongo >=0.9.3)
MongoDB::execute - Runs JavaScript code on the database server.
Description
public array MongoDB::execute ( mixed $code [, array $args = array() ] )
The Mongo database server runs a JavaScript engine. This method allows you
to run arbitary JavaScript on the database. This can be useful if you want
touch a number of collections lightly, or process some results on the
database side to reduce the amount that has to be sent to the client.
Running JavaScript in the database takes a write lock, meaning it blocks
other operations. Make sure you consider this before running a long
script.
This is a wrapper for a database command. This method is basically:
command(array('$eval' => $code, args => $args));
}
?>
MongoDB implies a return statement if you have a single statement on a
single line. This can cause some unintuitive behavior. For example, this
returns "foo":
execute('"foo";');
?>
However, these return NULL:
execute('"bar"; "foo";'); // more than one statement
$db->execute('db.foo.count(
);'); // more than one line
?>
To avoid surprising behavior, it is best not to depend on MongoDB to
decide what to return, but to explicitly state a return value. In the
examples above, we can change them to:
execute('"bar"; return "foo";');
$db->execute('return db.foo.count(
);');
?>
Now the first statement will return "foo" and the second statement will
return a count of the "foo" collection.
Parameters
code
MongoCode or string to execute.
args
Arguments to be passed to code.
Return Values
Returns the result of the evaluation.
Examples
Example #1 Simple MongoDB::execute() example
execute("function() { return 'Hello, world!'; }");
echo $response['retval'];
?>
The above example will output something similar to:
Hello, world!
Example #2 Parameter MongoDB::execute() example
The optional array of parameters will be passed to the JavaScript
function.
execute("function(greeting, name) { return greeting+', '+name+'!'; }", array("Good bye", "Joe"));
echo $response['retval'];
?>
The above example will output something similar to:
Good bye, Joe!
Example #3 Scope example
If a MongoCode object is used instead of a string for the first parameter,
a scope can be passed in which the JavaScript will be executed.
"Fred");
$code = new MongoCode($func, $scope);
$response = $db->execute($code, array("Goodbye", "Joe"));
echo $response['retval'];
?>
The above example will output something similar to:
Goodbye, Joe, says Fred
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB::forceError()
(No version information available, might only be in SVN)
- Creates a database error
Description
public bool MongoDB::forceError ( void )
This method is not very useful for normal MongoDB use. It forces a
database error to occur. This means that MongoDB::lastError() will return
a generic database error after running this command.
This command is identical to running:
command(array('forceerror' => 1));
}
?>
Parameters
This function has no parameters.
Return Values
Returns the database response.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB::__get
(PECL mongo >=1.0.2)
MongoDB::__get - Gets a collection
Description
public MongoCollection MongoDB::__get ( string $name )
This is the easiest way of getting a collection from a database object. If
a collection name contains strange characters, you may have to use
MongoDB::selectCollection() instead.
selectDB("foo")->selectCollection("bar");
$collection = $mongo->foo->bar;
?>
Parameters
name
The name of the collection.
Return Values
Returns the collection.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB::getDBRef
(PECL mongo >=0.9.0)
MongoDB::getDBRef - Fetches the document pointed to by a database
reference
Description
public array MongoDB::getDBRef ( array $ref )
Parameters
ref
A database reference.
Return Values
Returns the document pointed to by the reference.
Examples
Example #1 MongoDB::getDBRef() example
Example demonstrating how to get a database reference and what the
expected input is.
'profiles',
'$id' => '47cc67093475061e3d9536d2'
);
$profile = $db->getDBRef($ref);
?>
See MongoDB::createDBRef() for more information about how to
programatically create DB references.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB::getGridFS
(PECL mongo >=0.9.0)
MongoDB::getGridFS - Fetches toolkit for dealing with files stored in this
database
Description
public MongoGridFS MongoDB::getGridFS ([ string $prefix = "fs" ] )
Parameters
prefix
The prefix for the files and chunks collections.
Return Values
Returns a new gridfs object for this database.
Examples
Example #1 MongoDB::getGridFS() example
This example demonstrates how get a MongoGridFS instance.
my_db;
$prefix = 'files';
$collection = $db->getGridFS($prefix);
?>
Read more about the MongoGridFS to learn how to store files with MongoDB.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB::getProfilingLevel
(PECL mongo >=0.9.0)
MongoDB::getProfilingLevel - Gets this database's profiling level
Description
public int MongoDB::getProfilingLevel ( void )
This returns the current database profiling level.
The database profiler tracks query execution times. If you turn it on
(say, using MongoDB::setProfilingLevel() or the shell), you can see how
many queries took longer than a given number of milliseconds or the timing
for all queries.
Note that profiling slows down queries, so it is better to use in
development or testing than in a time-sensitive application.
This function is equivalent to running:
command(array('profile' => -1));
}
?>
Parameters
This function has no parameters.
Return Values
Returns the profiling level.
See Also
MongoDB core docs on >> profiling and MongoDB::setProfilingLevel() - Sets
this database's profiling level.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB::getSlaveOkay
(PECL mongo >=1.1.0)
MongoDB::getSlaveOkay - Get slaveOkay setting for this database
Description
public bool MongoDB::getSlaveOkay ( void )
See the query section of this manual for information on distributing reads
to slaves.
Parameters
This function has no parameters.
Return Values
Returns the value of slaveOkay for this instance.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB::lastError
(PECL mongo >=0.9.5)
MongoDB::lastError - Check if there was an error on the most recent db
operation performed
Description
public array MongoDB::lastError ( void )
This method is equivalent to:
command(array('getlasterror' => 1));
}
?>
Parameters
This function has no parameters.
Return Values
Returns the error, if there was one.
Examples
Example #1 MongoDB::lastError() NULL error example
resetError();
var_dump($db->lastError());
?>
The above example will output something similar to:
array(3) {
["err"]=>
NULL
["n"]=>
int(0)
["ok"]=>
float(1)
}
Example #2 MongoDB::lastError() duplicate key example
selectCollection("foo");
// insert two documents with the same _id
$c->insert(array("_id" => 1));
$c->insert(array("_id" => 1));
var_dump($db->lastError());
?>
The above example will output something similar to:
array(3) {
["err"]=>
string(64) "E11000 duplicate key errorindex: foo.foo.$_id_ dup key: { : 1 }"
["n"]=>
int(0)
["ok"]=>
float(1)
}
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB::listCollections
(PECL mongo >=0.9.0)
MongoDB::listCollections - Get a list of collections in this database
Description
public array MongoDB::listCollections ( void )
Parameters
This function has no parameters.
Return Values
Returns a list of MongoCollections.
Examples
Example #1 MongoDB::listCollections() example
The following example demonstrates dropping each collection in a database.
selectDB("sample");
$list = $db->listCollections();
foreach ($list as $collection) {
echo "removing $collection... ";
$collection->drop();
echo "gone\n";
}
?>
The above example will output something similar to:
removing sample.blog.posts... gone
removing sample.critical.docs... gone
removing sample.taxes... gone
...
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB::prevError
(PECL mongo >=0.9.5)
MongoDB::prevError - Checks for the last error thrown during a database
operation
Description
public array MongoDB::prevError ( void )
MongoDB::lastError() is usually preferred to this. This method returns the
last database error that occurred and how many operations ago it occurred.
It is mostly deprecated.
Parameters
This function has no parameters.
Return Values
Returns the error and the number of operations ago it occurred.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB::repair
(PECL mongo >=0.9.0)
MongoDB::repair - Repairs and compacts this database
Description
public array MongoDB::repair ([ bool $preserve_cloned_files = FALSE [,
bool $backup_original_files = FALSE ]] )
This creates a fresh copy of all database data. It will remove any corrupt
data and compact and large stretches of free space it finds. This is a
very slow operation on a large database.
This is usually run from the shell or the command line, not the driver.
It is equivalent to the function:
command(array('repairDatabase' => 1));
}
?>
Parameters
preserve_cloned_files
If cloned files should be kept if the repair fails.
backup_original_files
If original files should be backed up.
Return Values
Returns db response.
See Also
MongoDB core docs on >> repair.
Examples
Example #1 MongoDB::repair() example
This example demonstrates how to repare and compact a database.
foo;
$response = $db->repair();
print_r($response);
?>
The above example will output something similar to:
Array
(
[ok] => 1
)
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB::resetError
(PECL mongo >=0.9.5)
MongoDB::resetError - Clears any flagged errors on the database
Description
public array MongoDB::resetError ( void )
This method is not used in normal operations. It resets the database error
tracker (which can be incremented with MongoDB::forceError(), also not
normally used).
It is equivalent to running:
command(array('reseterror' => 1));
}
?>
Parameters
This function has no parameters.
Return Values
Returns the database response.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB::selectCollection
(PECL mongo >=0.9.0)
MongoDB::selectCollection - Gets a collection
Description
public MongoCollection MongoDB::selectCollection ( string $name )
Parameters
name
The name of the collection.
Return Values
Returns the collection.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB::setProfilingLevel
(PECL mongo >=0.9.0)
MongoDB::setProfilingLevel - Sets this database's profiling level
Description
public int MongoDB::setProfilingLevel ( int $level )
This changes the current database profiling level.
This function is equivalent to running:
command(array('profile' => $level));
}
?>
The options for level are 0 (off), 1 (queries > 100ms), and 2 (all
queries). If you would like to profile queries that take longer than
another time period, use the database command and pass it a second option,
the number of milliseconds. For example, to profile all queries that take
longer than one second, run:
command(array('profile' => 1, 'slowms' => 1000));
?>
Profiled queries will appear in the system.profile collection of this
database.
Parameters
level
Profiling level.
Return Values
Returns the previous profiling level.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB::setSlaveOkay
(PECL mongo >=1.1.0)
MongoDB::setSlaveOkay - Change slaveOkay setting for this database
Description
public bool MongoDB::setSlaveOkay ([ bool $ok = true ] )
See the query section of this manual for information on distributing reads
to slaves.
Parameters
ok
If reads should be sent to secondary members of a replica set for
all possible queries using this MongoDB instance.
Return Values
Returns the former value of slaveOkay for this instance.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDB::__toString
(PECL mongo >=0.9.0)
MongoDB::__toString - The name of this database
Description
public string MongoDB::__toString ( void )
Parameters
This function has no parameters.
Return Values
Returns this database's name.
----------------------------------------------------------------------
Table of Contents
* MongoDB::authenticate - Log in to this database
* MongoDB::command - Execute a database command
* MongoDB::__construct - Creates a new database
* MongoDB::createCollection - Creates a collection
* MongoDB::createDBRef - Creates a database reference
* MongoDB::drop - Drops this database
* MongoDB::dropCollection - Drops a collection [deprecated]
* MongoDB::execute - Runs JavaScript code on the database server.
* MongoDB::forceError - Creates a database error
* MongoDB::__get - Gets a collection
* MongoDB::getDBRef - Fetches the document pointed to by a database
reference
* MongoDB::getGridFS - Fetches toolkit for dealing with files stored in
this database
* MongoDB::getProfilingLevel - Gets this database's profiling level
* MongoDB::getSlaveOkay - Get slaveOkay setting for this database
* MongoDB::lastError - Check if there was an error on the most recent db
operation performed
* MongoDB::listCollections - Get a list of collections in this database
* MongoDB::prevError - Checks for the last error thrown during a
database operation
* MongoDB::repair - Repairs and compacts this database
* MongoDB::resetError - Clears any flagged errors on the database
* MongoDB::selectCollection - Gets a collection
* MongoDB::setProfilingLevel - Sets this database's profiling level
* MongoDB::setSlaveOkay - Change slaveOkay setting for this database
* MongoDB::__toString - The name of this database
----------------------------------------------------------------------
----------------------------------------------------------------------
The MongoCollection class
Introduction
Representations a database collection.
Collection names can use any character in the ASCII set. Some valid
collection names are "", "...", "my collection", and "*@".
User-defined collection names cannot contain the $ symbol. There are
certain system collections which use a $ in their names (e.g.,
local.oplog.$main), but it is a reserved character. If you attempt to
create and use a collection with a $ in the name, MongoDB will assert.
Class synopsis
MongoCollection {
/* Constants */
const int ASCENDING = 1 ;
const int DESCENDING = -1 ;
/* Fields */
public MongoDB $MongoCollection->db = NULL ;
public integer $w ;
public integer $wtimeout ;
/* Methods */
public mixed MongoCollection::batchInsert ( array $a [, array $options =
array() ] )
public MongoCollection::__construct ( MongoDB $db , string $name )
public int MongoCollection::count ([ array $query = array() [, int $limit
= 0 [, int $skip = 0 ]]] )
public array MongoCollection::createDBRef ( array $a )
public array MongoCollection::deleteIndex ( string|array $keys )
public array MongoCollection::deleteIndexes ( void )
public array MongoCollection::drop ( void )
public bool MongoCollection::ensureIndex ( array $keys [, array $options =
array() ] )
public MongoCursor MongoCollection::find ([ array $query = array() [,
array $fields = array() ]] )
public array MongoCollection::findOne ([ array $query = array() [, array
$fields = array() ]] )
public MongoCollection MongoCollection::__get ( string $name )
public array MongoCollection::getDBRef ( array $ref )
public array MongoCollection::getIndexInfo ( void )
public string MongoCollection::getName ( void )
public bool MongoCollection::getSlaveOkay ( void )
public array MongoCollection::group ( mixed $keys , array $initial ,
MongoCode $reduce [, array $options = array() ] )
public mixed MongoCollection::insert ( array $a [, array $options =
array() ] )
public mixed MongoCollection::remove ([ array $criteria = array() [, array
$options = array() ]] )
public mixed MongoCollection::save ( array $a [, array $options = array()
] )
public bool MongoCollection::setSlaveOkay ([ bool $ok = true ] )
public string MongoCollection::__toString ( void )
public bool MongoCollection::update ( array $criteria , array $newobj [,
array $options = array() ] )
public array MongoCollection::validate ([ bool $scan_data = FALSE ] )
}
Predefined Constants
MongoCollection::ASCENDING
1
Ascending direction for sorts and index creation.
MongoCollection::DESCENDING
-1
Descending direction for sorts and index creation.
Fields
db
The "parent" database for this collection.
w
The number of servers to replicate a change to before returning
success. Value is inherited from the parent database. The MongoDB
class has a more detailed description of how w works.
wtimeout
The number of milliseconds to wait for $this->w replications to
take place. Value is inherited from the parent database. The
MongoDB class has a more detailed description of how wtimeout
works.
See Also
MongoDB core docs on >> collections.
----------------------------------------------------------------------
MongoCollection::batchInsert
(PECL mongo >=0.9.0)
MongoCollection::batchInsert - Inserts multiple documents into this
collection
Description
public mixed MongoCollection::batchInsert ( array $a [, array $options =
array() ] )
Parameters
a
An array of arrays.
options
Options for the inserts.
* "safe"
Can be a boolean or integer, defaults to FALSE. If FALSE, the
program continues executing without waiting for a database
response. If TRUE, the program will wait for the database
response and throw a MongoCursorException if the insert did
not succeed.
If safe is an integer, will replicate the insert to that many
machines before returning success (or throw an exception if
the replication times out, see wtimeout). This overrides the
w variable set on the collection.
* "fsync"
Boolean, defaults to FALSE. Forces the insert to be synced to
disk before returning success. If TRUE, a safe insert is
implied and will override setting safe to FALSE.
Return Values
If "safe" is set, returns an associative array with the status of the
inserts ("ok") and any error that may have occured ("err"). Otherwise,
returns TRUE if the batch insert was successfully sent, FALSE otherwise.
Errors/Exceptions
Throws MongoCursorException if the "safe" option is set and the insert
fails.
Throws MongoCursorTimeoutException if the "safe" option is set to a value
greater than one and the database cannot replicate the operation in
MongoCollection::$wtimeout milliseconds.
Changelog
Version Description
1.0.5 Added "options" parameter.
1.0.9 Added ability to pass integers to "safe" options (only accepted
booleans before) and added "fsync" option.
Examples
Example #1 MongoCollection::batchInsert() example
Batch insertion is a quick way to add many elements to the database at
once
'user'.$i, 'i' => $i);
}
$mongo = new Mongo();
$collection = $mongo->my_db->users;
$collection->drop();
$collection->batchInsert($users);
foreach ($users as $user) {
echo $user['_id']."\n"; // populated with instanceof MongoId
}
$users = $collection->find()->sort(array('i' => 1));
foreach ($users as $user) {
var_dump($user['username']);
}
?>
The above example will output something similar to:
4bf43ac68ead0e1971000000
4bf43ac68ead0e1971010000
4bf43ac68ead0e1971020000
...
string(5) "user1"
string(5) "user2"
string(5) "user3"
...
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCollection::__construct
(PECL mongo >=0.9.0)
MongoCollection::__construct - Creates a new collection
Description
public MongoCollection::__construct ( MongoDB $db , string $name )
Parameters
MongoDB db
Parent database.
name
Name for this collection.
Return Values
Returns a new collection object.
Errors/Exceptions
Throws default exception if the collection name is invalid.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCollection::count
(PECL mongo >=0.9.0)
MongoCollection::count - Counts the number of documents in this collection
Description
public int MongoCollection::count ([ array $query = array() [, int $limit
= 0 [, int $skip = 0 ]]] )
Parameters
query
Associative array or object with fields to match.
limit
Specifies an upper limit to the number returned.
skip
Specifies a number of results to skip before starting the count.
Return Values
Returns the number of documents matching the query.
Changelog
Version Description
1.0.7 Added limit and skip parameters.
Examples
Example #1 MongoCollection::count() example
insert(array('x'=>1));
$collection->insert(array('x'=>2));
$collection->insert(array('x'=>3));
var_dump($collection->count());
var_dump($collection->count(array('x'=>1)));
?>
The above example will output something similar to:
int(3)
int(1)
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCollection::createDBRef
(PECL mongo >=0.9.0)
MongoCollection::createDBRef - Creates a database reference
Description
public array MongoCollection::createDBRef ( array $a )
Parameters
a
Object to which to create a reference.
Return Values
Returns a database reference array.
Examples
Example #1 MongoCollection::createDBRef() example
songs;
$playlists = $db->playlists;
// create a reference to a song
$manamana = $songs->findOne(array('title' => 'Ma na ma na'));
$refToSong = $songs->createDBRef($manamana);
// add the reference to my playlist
$playlists->update(array('username' => 'me'), array('$push' => array('songlist' => $refToSong)));
?>
See Also
* MongoCollection::getDBRef() - Fetches the document pointed to by a
database reference
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCollection::deleteIndex
(PECL mongo >=0.9.0)
MongoCollection::deleteIndex - Deletes an index from this collection
Description
public array MongoCollection::deleteIndex ( string|array $keys )
This method is identical to:
toIndexString($keys);
return $this->db->command(array("deleteIndexes" => $this->getName(),
"index" => $index);
}
?>
Each index, when created, is given a unique name. This is generally
user-set (with MongoCollection::ensureIndex()'s "name" option) or
generated by the driver from a combination of key names and directions.
This name is then used by MongoCollection::deleteIndex() to remove the
function.
Unfortunately, the MongoCollection::ensureIndex() generates slightly
different names than the shell and, due to backwards compatibility issues,
MongoCollection::deleteIndex() cannot delete custom-named indexes as well.
Thus, the best way to delete indexes created in the shell or with custom
names is to directly call the deleteIndexes database command.
Thus, if you named an index "superfast query", you could delete it with:
command(array("deleteIndexes" => $collection->getName(), "index" => "superfast query");
?>
To find what an index is named, you can query the system.indexes
collection of a database and look for the name field.
Parameters
keys
Field or fields from which to delete the index.
Return Values
Returns the database response.
Examples
Example #1 MongoCollection::deleteIndex() example
This example passes the function string and array parameters.
example->indices;
// create an index
$c->ensureIndex(array("i"=>1));
// remove a simple index
$c->deleteIndex("i");
// create a multi-key index
$c->ensureIndex(array("j" => 1, "k" => 1));
// remove a multi-key index
$c->deleteIndex(array("j" => 1, "k" => 1));
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCollection::deleteIndexes
(PECL mongo >=0.9.0)
MongoCollection::deleteIndexes - Delete all indices for this collection
Description
public array MongoCollection::deleteIndexes ( void )
Parameters
This function has no parameters.
Return Values
Returns the database response.
Examples
Example #1 MongoCollection::deleteIndexes() example
This example demonstrates how to delete all indexes from a collection and
the response to expect.
my_db->articles;
$response = $collection->deleteIndexes();
print_r($response);
?>
The above example will output something similar to:
Array
(
[nIndexesWas] => 1
[msg] => all indexes deleted for collection
[ok] => 1
)
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCollection::drop
(PECL mongo >=0.9.0)
MongoCollection::drop - Drops this collection
Description
public array MongoCollection::drop ( void )
Drops this collection and deletes its indices.
Parameters
This function has no parameters.
Return Values
Returns the database response.
Examples
Example #1 MongoCollection::drop() example
This example demonstrates how to drop a collection and the response to
expect.
my_db->articles;
$response = $collection->drop();
print_r($response);
?>
The above example will output something similar to:
Array
(
[nIndexesWas] => 1
[msg] => all indexes deleted for collection
[ns] => my_db.articles
[ok] => 1
)
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCollection::ensureIndex
(PECL mongo >=0.9.0)
MongoCollection::ensureIndex - Creates an index on the given field(s), or
does nothing if the index already exists
Description
public bool MongoCollection::ensureIndex ( array $keys [, array $options =
array() ] )
A unique index cannot be created on a field if multiple existing documents
do not contain the field. The field is effectively NULL for these
documents and thus already non-unique.
Parameters
keys
Field or fields to use as index.
options
This parameter is an associative array of the form
array("optionname" => , ...). Currently supported options
are:
* "unique"
Create a unique index.
* "dropDups"
If a unique index is being created and duplicate values
exist, drop all but one duplicate value.
* "background"
If you are using MongoDB version 1.3.2+, you can create
indexes in the background while other operations are taking
place. By default, index creation happens synchronously. If
you specify TRUE with this option, index creation will be
asynchronous.
* "safe"
Starting with driver version 1.0.4, you can specify a boolean
value for checking if the index creation succeeded. The
driver will throw a MongoCursorException if index creation
failed.
If you are using replication and the master has changed,
using "safe" will make the driver disconnect from the master,
throw and exception, and attempt to find a new master on the
next operation (your application must decide whether or not
to retry the operation on the new master).
If you do not use "safe" with a replica set and the master
changes, there will be no way for the driver to know about
the change so it will continuously and silently fail to
write.
* "name"
After driver version 1.0.4 (NOT including 1.0.4) you can
specify an index name. This can be useful if you are indexing
many keys and Mongo complains about the index name being too
long.
* "timeout"
Integer, defaults to MongoCursor::$timeout. If "safe" is set,
this sets how long (in milliseconds) for the client to wait
for a database response. If the database does not respond
within the timeout period, a MongoCursorTimeoutException will
be thrown.
Return Values
Returns TRUE.
Changelog
Version Description
1.2.0 Added timeout option.
1.0.11 "safe" will trigger master failover, if necessary.
1.0.11 MongoException will be thrown if index name (either generated or
set) is longer than 128 bytes.
Changed "options" parameter from boolean to array. Pre-1.0.2, the
1.0.2 second parameter was an optional boolean value specifying a unique
index.
Errors/Exceptions
Throws MongoException if the index name is longer than 128 bytes. (Version
1.0.11+)
Throws MongoCursorException if the "safe" option is set and the index
creation fails.
Throws MongoCursorTimeoutException if the "safe" option is set and the
operation takes longer than MongoCursor::$timeout milliseconds to
complete. This does not kill the operation on the server, it is a
client-side timeout.
Examples
Example #1 MongoCollection::ensureIndex() example
ensureIndex(array('x' => 1));
// create an index on 'z' ascending and 'zz' descending
$c->ensureIndex(array('z' => 1, 'zz' => -1));
// create a unique index on 'x'
$c->ensureIndex(array('x' => 1), array("unique" => true));
?>
Example #2 Drop duplicates example
insert(array("username" => "joeschmoe"));
$collection->insert(array("username" => "joeschmoe"));
/*
* index creation fails, you can't create a unique index on a key with
* non-unique values
*/
$collection->ensureIndex(array("username" => 1), array("unique" => 1));
/*
* index creation succeeds: one of the documents is removed from the collection
*/
$collection->ensureIndex(array("username" => 1), array("unique" => 1, "dropDups" => 1));
/*
* now we have a unique index, more inserts with the same username (such as the
* one below) will fail
*/
$collection->insert(array("username" => "joeschmoe"));
?>
Example #3 Geospatial Indexing
Mongo supports geospatial indexes, which allow you to search for documents
near a given location or within a shape. For example, to create a
geospatial index on the "loc" field:
ensureIndex(array("loc" => "2d"));
?>
See Also
MongoDB core docs on >> vanilla indexes and >> geospatial indexes.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCollection::find
(PECL mongo >=0.9.0)
MongoCollection::find - Querys this collection
Description
public MongoCursor MongoCollection::find ([ array $query = array() [,
array $fields = array() ]] )
Parameters
query
The fields for which to search.
fields
Fields of the results to return.
Return Values
Returns a cursor for the search results.
Examples
Example #1 MongoCollection::find() example
This example demonstrates how to search for a range.
array( '$gt' => 5, '$lt' => 20 ));
$cursor = $collection->find($rangeQuery);
?>
See MongoCursor for more information how to work with cursors.
Example #2 MongoCollection::find() example using $where
This example demonstrates how to search a collection using javascript code
to reduce the resultset.
my_db->articles;
$js = "function() {
return this.type == 'homepage' || this.featured == true;
}";
$articles = $collection->find(array('$where' => $js));
?>
Example #3 MongoCollection::find() example using $in
This example demonstrates how to search a collection using the $in
operator.
my_db->articles;
$articles = $collection->find(array(
'type' => array('$in' => array('homepage', 'editorial'))
));
?>
Example #4 Getting results as an array
This returns a MongoCursor. Often, when people are starting out, they are
more comfortable using an array. To turn a cursor into an array, use the
iterator_to_array() function.
find();
$array = iterator_to_array($cursor);
?>
Using iterator_to_array() forces the driver to load all of the results
into memory, so do not do this for result sets that are larger than
memory!
Also, certain system collections do not have an _id field. If you are
dealing with a collection that might have documents without _ids, pass
FALSE as the second argument to iterator_to_array() (so that it will not
try to use the non-existent _id values as keys).
See Also
MongoDB core docs on >> find.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCollection::findOne
(PECL mongo >=0.9.0)
MongoCollection::findOne - Querys this collection, returning a single
element
Description
public array MongoCollection::findOne ([ array $query = array() [, array
$fields = array() ]] )
Parameters
query
The fields for which to search.
fields
Fields of the results to return.
Return Values
Returns record matching the search or NULL.
Errors/Exceptions
Throws MongoConnectionException if it cannot reach the database.
Examples
Example #1 MongoCollection::findOne() document by its id.
This example demonstrates how to find a single document in a collection by
its id.
my_db->articles;
$article = $articles->findOne(array('_id' => new MongoId('47cc67093475061e3d9536d2')));
?>
Example #2 MongoCollection::findOne() document by some condition.
This example demonstrates how to find a single document in a collection by
some condition and limiting the returned fields.
my_db->users;
$user = $users->findOne(array('username' => 'jwage'), array('password'));
print_r($user);
?>
The above example will output something similar to:
Array
(
[_id] => MongoId Object
(
)
[password] => test
)
Notice how even though the document does have a username field, we limited
the results to only contain the password field.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCollection::__get
(PECL mongo >=1.0.2)
MongoCollection::__get - Gets a collection
Description
public MongoCollection MongoCollection::__get ( string $name )
A concise syntax for getting a collection with a dot-separated name. If a
collection name contains strange characters, you may have to use
MongoDB::selectCollection() instead.
selectDB("foo")->selectCollection("bar.baz");
$collection = $mongo->foo->bar->baz;
?>
Parameters
name
The next string in the collection name.
Return Values
Returns the collection.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCollection::getDBRef
(PECL mongo >=0.9.0)
MongoCollection::getDBRef - Fetches the document pointed to by a database
reference
Description
public array MongoCollection::getDBRef ( array $ref )
Parameters
ref
A database reference.
Return Values
Returns the database document pointed to by the reference.
Examples
Example #1 MongoCollection::getDBRef() example
playlists;
$myList = $playlists->findOne(array('username' => 'me'));
// fetch each song in the playlist
foreach ($myList['songlist'] as $songRef) {
$song = $playlists->getDBRef($songRef);
echo $song['title'] . "\n";
}
?>
The above example will output something similar to:
Dazed and Confused
Ma na ma na
Bohemian Rhapsody
In the above example each $songRef looks something like the following:
Array
(
[$ref] => songs
[$id] => 49902cde5162504500b45c2c
)
See Also
* MongoCollection::createDBRef() - Creates a database reference
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCollection::getIndexInfo
(PECL mongo >=0.9.0)
MongoCollection::getIndexInfo - Returns an array of index names for this
collection
Description
public array MongoCollection::getIndexInfo ( void )
Parameters
This function has no parameters.
Return Values
Returns a list of index names.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCollection::getName
(PECL mongo >=0.9.0)
MongoCollection::getName - Returns this collection's name
Description
public string MongoCollection::getName ( void )
Parameters
This function has no parameters.
Return Values
Returns the name of this collection.
Examples
Example #1 MongoCollection::getName() example
foo->bar->baz;
echo "Working with collection " . $c->getName() . ".\n";
// the full namespace is given by the MongoCollection::__toString() method
echo "Working in namespace $c.\n";
?>
The above example will output something similar to:
Working with collection bar.baz.
Working in namespace foo.bar.baz.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCollection::getSlaveOkay
(PECL mongo >=1.1.0)
MongoCollection::getSlaveOkay - Get slaveOkay setting for this collection
Description
public bool MongoCollection::getSlaveOkay ( void )
See the query section of this manual for information on distributing reads
to slaves.
Parameters
This function has no parameters.
Return Values
Returns the value of slaveOkay for this instance.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCollection::group
(PECL mongo >=0.9.2)
MongoCollection::group - Performs an operation similar to SQL's GROUP BY
command
Description
public array MongoCollection::group ( mixed $keys , array $initial ,
MongoCode $reduce [, array $options = array() ] )
Parameters
keys
Fields to group by. If an array or non-code object is passed, it
will be the key used to group results.
1.0.4+: If keys is an instance of MongoCode, keys will be treated
as a function that returns the key to group by (see the "Passing a
keys function" example below).
initial
Initial value of the aggregation counter object.
reduce
A function that takes two arguments (the current document and the
aggregation to this point) and does the aggregation.
options
Optional parameters to the group command. Valid options include:
* "condition"
Criteria for including a document in the aggregation.
* "finalize"
Function called once per unique key that takes the final
output of the reduce function.
Return Values
Returns an array containing the result.
Examples
Example #1 MongoCollection::group() example
This groups documents by category and creates a list of names within that
category.
insert(array("category" => "fruit", "name" => "apple"));
$collection->insert(array("category" => "fruit", "name" => "peach"));
$collection->insert(array("category" => "fruit", "name" => "banana"));
$collection->insert(array("category" => "veggie", "name" => "corn"));
$collection->insert(array("category" => "veggie", "name" => "broccoli"));
$keys = array("category" => 1);
$initial = array("items" => array());
$reduce = "function (obj, prev) { prev.items.push(obj.name); }";
$g = $collection->group($keys, $initial, $reduce);
echo json_encode($g['retval']);
?>
The above example will output something similar to:
[{"category":"fruit","items":["apple","peach","banana"]},{"category":"veggie","items":["corn","broccoli"]}]
Example #2 MongoCollection::group() example
This example doesn't use any key, so every document will be its own group.
It also uses a condition: only documents that match this condition will be
processed by the grouping function.
save(array("a" => 2));
$collection->save(array("b" => 5));
$collection->save(array("a" => 1));
// use all fields
$keys = array();
// set intial values
$initial = array("count" => 0);
// JavaScript function to perform
$reduce = "function (obj, prev) { prev.count++; }";
// only use documents where the "a" field is greater than 1
$condition = array("a" => array( '$gt' => 1));
$g = $collection->group($keys, $initial, $reduce, $condition);
var_dump($g);
?>
The above example will output something similar to:
array(4) {
["retval"]=>
array(1) {
[0]=>
array(1) {
["count"]=>
float(1)
}
}
["count"]=>
float(1)
["keys"]=>
int(1)
["ok"]=>
float(1)
}
Example #3 Passing a keys function
If you want to group by something other than a field name, you can pass a
function as the first parameter of MongoCollection::group() and it will be
run against each document. The return value of the function will be used
as its grouping value.
This example demonstrates grouping by the num field modulo 4.
group(new MongoCode('function(doc) { return {mod : doc.num % 4}; }'),
array("count" => 0),
new MongoCode('function(current, total) { total.count++; }'));
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCollection::insert
(PECL mongo >=0.9.0)
MongoCollection::insert - Inserts an array into the collection
Description
public mixed MongoCollection::insert ( array $a [, array $options =
array() ] )
All strings sent to the database must be UTF-8. If a string is not UTF-8,
a MongoException will be thrown. To insert (or query for) a non-UTF-8
string, use MongoBinData.
Parameters
a
An array.
options
Options for the insert.
* "safe"
Can be a boolean or integer, defaults to FALSE. If FALSE, the
program continues executing without waiting for a database
response. If TRUE, the program will wait for the database
response and throw a MongoCursorException if the insert did
not succeed.
If you are using replication and the master has changed,
using "safe" will make the driver disconnect from the master,
throw an exception, and attempt to find a new master on the
next operation (your application must decide whether or not
to retry the operation on the new master).
If you do not use "safe" with a replica set and the master
changes, there will be no way for the driver to know about
the change so it will continuously and silently fail to
write.
If safe is an integer, will replicate the insert to that many
machines before returning success (or throw an exception if
the replication times out, see wtimeout). This overrides the
w variable set on the collection.
* "fsync"
Boolean, defaults to FALSE. Forces the insert to be synced to
disk before returning success. If TRUE, a safe insert is
implied and will override setting safe to FALSE.
* "timeout"
Integer, defaults to MongoCursor::$timeout. If "safe" is set,
this sets how long (in milliseconds) for the client to wait
for a database response. If the database does not respond
within the timeout period, a MongoCursorTimeoutException will
be thrown.
Return Values
If safe was set, returns an array containing the status of the insert.
Otherwise, returns a boolean representing if the array was not empty (an
empty array will not be inserted).
Errors/Exceptions
Throws MongoCursorException if the "safe" option is set and the insert
fails. (Version 1.0.1+)
Throws MongoCursorTimeoutException if the "safe" option is set and the
operation takes longer than MongoCursor::$timeout milliseconds to
complete. This does not kill the operation on the server, it is a
client-side timeout.
Changelog
Version Description
1.0.5 Changed second parameter to an array of options. Pre-1.0.5, the
second parameter was a boolean indicating the "safe" option.
1.0.9 Added ability to pass integers to "safe" options (only accepted
booleans before) and added "fsync" option.
1.0.11 Disconnects on "not master" errors if "safe" is set.
1.2.0 Added timeout option.
Examples
Example #1 MongoCollection::insert() _id example
Inserting an object will add an _id field to it, unless it is passed by
reference.
1);
$collection->insert($a);
var_dump($a);
$b = array('x' => 1);
$ref = &$b;
$collection->insert($ref);
var_dump($ref);
?>
The above example will output something similar to:
array(2) {
["x"]=>
int(1)
["_id"]=>
object(MongoId)#4 (0) {
}
}
array(1) {
["x"]=>
int(1)
}
Example #2 MongoCollection::insert() safe example
This example shows inserting two elements with the same _id, which causes
a MongoCursorException to be thrown, as safe was set.
"Joe", "age" => 20);
$collection->insert($person, true);
// now $person has an _id field, so if we save it
// again, we will get an exception
try {
$collection->insert($person, true);
}
catch(MongoCursorException $e) {
echo "Can't save the same person twice!\n";
}
?>
See Also
MongoDB core docs on >> insert.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCollection::remove
(PECL mongo >=0.9.0)
MongoCollection::remove - Remove records from this collection
Description
public mixed MongoCollection::remove ([ array $criteria = array() [, array
$options = array() ]] )
Parameters
criteria
Description of records to remove.
options
Options for remove.
* "justOne"
Remove at most one record matching this criteria.
* "safe"
Can be a boolean or integer, defaults to FALSE. If FALSE, the
program continues executing without waiting for a database
response. If TRUE, the program will wait for the database
response and throw a MongoCursorException if the update did
not succeed.
If you are using replication and the master has changed,
using "safe" will make the driver disconnect from the master,
throw and exception, and attempt to find a new master on the
next operation (your application must decide whether or not
to retry the operation on the new master).
If you do not use "safe" with a replica set and the master
changes, there will be no way for the driver to know about
the change so it will continuously and silently fail to
write.
If safe is an integer, will replicate the update to that many
machines before returning success (or throw an exception if
the replication times out, see wtimeout). This overrides the
w variable set on the collection.
* "fsync"
Boolean, defaults to FALSE. Forces the update to be synced to
disk before returning success. If TRUE, a safe update is
implied and will override setting safe to FALSE.
* "timeout"
Integer, defaults to MongoCursor::$timeout. If "safe" is set,
this sets how long (in milliseconds) for the client to wait
for a database response. If the database does not respond
within the timeout period, a MongoCursorTimeoutException will
be thrown.
Return Values
If "safe" is set, returns an associative array with the status of the
remove ("ok"), the number of items removed ("n"), and any error that may
have occured ("err"). Otherwise, returns TRUE if the remove was
successfully sent, FALSE otherwise.
Errors/Exceptions
Throws MongoCursorException if the "safe" option is set and the remove
fails.
Throws MongoCursorTimeoutException if the "safe" option is set and the
operation takes longer than MongoCursor::$timeout milliseconds to
complete. This does not kill the operation on the server, it is a
client-side timeout.
Changelog
Version Description
1.0.9 Added ability to pass integers to "safe" options (only accepted
booleans before) and added "fsync" option.
Changed second parameter to an array of options. Pre-1.0.5, the
1.0.5 second parameter was a boolean indicating the "justOne" option and
there was no safe option.
1.0.11 Disconnects on "not master" errors if "safe" is set.
1.2.0 Added timeout option.
Examples
Example #1 MongoCollection::remove() with justOne example
radioactive;
// count how much more plutonium there is
$remaining = $radioactive->count(array('type' => 94));
$halflife = $remaining/2;
// remove half of it
while ($halflife > 0) {
$radioactive->remove(array('type' => 94), array("justOne" => true));
$halflife--;
}
?>
See Also
MongoDB core docs on >> remove.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCollection::save
(PECL mongo >=0.9.0)
MongoCollection::save - Saves an object to this collection
Description
public mixed MongoCollection::save ( array $a [, array $options = array()
] )
If the object is from the database, update the existing database object,
otherwise insert this object.
Parameters
a
Array to save.
options
Options for the save.
* "safe"
Can be a boolean or integer, defaults to FALSE. If FALSE, the
program continues executing without waiting for a database
response. If TRUE, the program will wait for the database
response and throw a MongoCursorException if the insert did
not succeed.
If you are using replication and the master has changed,
using "safe" will make the driver disconnect from the master,
throw and exception, and attempt to find a new master on the
next operation (your application must decide whether or not
to retry the operation on the new master).
If you do not use "safe" with a replica set and the master
changes, there will be no way for the driver to know about
the change so it will continuously and silently fail to
write.
If safe is an integer, will replicate the insert to that many
machines before returning success (or throw an exception if
the replication times out, see wtimeout). This overrides the
w variable set on the collection.
* "fsync"
Boolean, defaults to FALSE. Forces the insert to be synced to
disk before returning success. If TRUE, a safe insert is
implied and will override setting safe to FALSE.
* "timeout"
Integer, defaults to MongoCursor::$timeout. If "safe" is set,
this sets how long (in milliseconds) for the client to wait
for a database response. If the database does not respond
within the timeout period, a MongoCursorTimeoutException will
be thrown.
Return Values
If safe was set, returns an array containing the status of the save.
Otherwise, returns a boolean representing if the array was not empty (an
empty array will not be inserted).
Errors/Exceptions
Throws MongoCursorException if the "safe" option is set and the save
fails.
Throws MongoCursorTimeoutException if the "safe" option is set and the
operation takes longer than MongoCursor::$timeout milliseconds to
complete. This does not kill the operation on the server, it is a
client-side timeout.
Changelog
Version Description
1.0.5 Added "options" parameter.
1.0.9 Added ability to pass integers to "safe" options (only accepted
booleans before) and added "fsync" option.
1.0.11 Disconnects on "not master" errors if "safe" is set.
1.2.0 Added timeout option.
Examples
Example #1 MongoCollection::save() example
1);
// insert $obj into the db
$collection->save($obj);
// add another field
$obj['foo'] = 'bar';
// $obj cannot be inserted again, causes duplicate _id error
$collection->insert($obj);
// save updates $obj with the new field
$collection->save($obj);
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCollection::setSlaveOkay
(PECL mongo >=1.1.0)
MongoCollection::setSlaveOkay - Change slaveOkay setting for this
collection
Description
public bool MongoCollection::setSlaveOkay ([ bool $ok = true ] )
See the query section of this manual for information on distributing reads
to slaves.
Parameters
ok
If reads should be sent to secondary members of a replica set for
all possible queries using this MongoCollection instance.
Return Values
Returns the former value of slaveOkay for this instance.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCollection::__toString
(PECL mongo >=0.9.0)
MongoCollection::__toString - String representation of this collection
Description
public string MongoCollection::__toString ( void )
Parameters
This function has no parameters.
Return Values
Returns the full name of this collection.
Examples
Example #1 MongoCollection::__toString() example
foo->bar->baz;
echo "Working with collection $c1.";
$c2 = $m->selectCollection('[]', '&');
echo "Working with collection $c2.";
?>
The above example will output something similar to:
Working with collection foo.bar.baz.
Working with collection [].&.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCollection::update
(PECL mongo >=0.9.0)
MongoCollection::update - Update records based on a given criteria
Description
public bool MongoCollection::update ( array $criteria , array $newobj [,
array $options = array() ] )
Parameters
criteria
Description of the objects to update.
newobj
The object with which to update the matching records.
options
This parameter is an associative array of the form
array("optionname" => , ...). Currently supported options
are:
* "upsert"
If no document matches $criteria, a new document will be
created from $criteria and $newobj (see upsert example
below).
* "multiple"
All documents matching $criteria will be updated.
MongoCollection::update() has exactly the opposite behavior
of MongoCollection::remove(): it updates one document by
default, not all matching documents. It is recommended that
you always specify whether you want to update multiple
documents or a single document, as the database may change
its default behavior at some point in the future.
* "safe"
Can be a boolean or integer, defaults to FALSE. If FALSE, the
program continues executing without waiting for a database
response. If TRUE, the program will wait for the database
response and throw a MongoCursorException if the update did
not succeed.
If you are using replication and the master has changed,
using "safe" will make the driver disconnect from the master,
throw and exception, and attempt to find a new master on the
next operation (your application must decide whether or not
to retry the operation on the new master).
If you do not use "safe" with a replica set and the master
changes, there will be no way for the driver to know about
the change so it will continuously and silently fail to
write.
If safe is an integer, will replicate the update to that many
machines before returning success (or throw an exception if
the replication times out, see wtimeout). This overrides the
w variable set on the collection.
* "fsync"
Boolean, defaults to FALSE. Forces the update to be synced to
disk before returning success. If TRUE, a safe update is
implied and will override setting safe to FALSE.
* "timeout"
Integer, defaults to MongoCursor::$timeout. If "safe" is set,
this sets how long (in milliseconds) for the client to wait
for a database response. If the database does not respond
within the timeout period, a MongoCursorTimeoutException will
be thrown.
Return Values
Returns if the update was successfully sent to the database.
Errors/Exceptions
Throws MongoCursorException if the "safe" option is set and the update
fails.
Throws MongoCursorTimeoutException if the "safe" option is set and the
operation takes longer than MongoCursor::$timeout milliseconds to
complete. This does not kill the operation on the server, it is a
client-side timeout.
Changelog
Version Description
Changed "options" parameter from boolean to array. Pre-1.0.1, the
1.0.1 second parameter was an optional boolean value specifying an
upsert.
1.0.5 Added "safe" option.
1.0.9 Added ability to pass integers to "safe" options (only accepted
booleans before) and added "fsync" option.
1.0.11 Disconnects on "not master" errors if "safe" is set.
1.2.0 Added timeout option.
Examples
Example #1 MongoCollection::update()
Adding an address field to a document.
insert(array("firstname" => "Bob", "lastname" => "Jones" ));
$newdata = array('$set' => array("address" => "1 Smith Lane"));
$c->update(array("firstname" => "Bob"), $newdata);
var_dump($c->findOne(array("firstname" => "Bob")));
?>
The above example will output something similar to:
array(4) {
["_id"]=>
object(MongoId)#6 (0) {
}
["firstname"]=>
string(3) "Bob"
["lastname"]=>
string(5) "Jones"
["address"]=>
string(12) "1 Smith Lane"
}
Example #2 MongoCollection::update() upsert example
Upserts can simplify code, as a single line can create the object if it
does not exist yet and update it if it does.
drop();
$c->update(array("uri" => "/summer_pics"), array('$inc' => array("page hits" => 1)), array("upsert" => true));
var_dump($c->findOne());
?>
The above example will output something similar to:
array(3) {
["_id"]=>
object(MongoId)#9 (0) {
}
["uri"]=>
string(12) "/summer_pics"
["page hits"]=>
int(1)
}
If newobj does not contain $-operators, an upsert will create a new
document from it alone. This matches the behavior of a normal update,
where not using $-operators causes the whole document to be overwritten.
update(array("name" => "joe"), array("username" => "joe312", "createdAt" => new MongoDate()),
array("upsert" => true));
?>
The above example will output something similar to:
array(3) {
["_id"]=>
object(MongoId)#10 (0) {
}
["username"]=>
string(6) "joe312"
["createdAt"]=>
object(MongoDate)#4 (0) {
}
}
Example #3 MongoCollection::update() multiple example
By default, MongoCollection::update() will only update the first document
matching $criteria that it finds. Using the "multiple" option can override
this behavior, if needed.
This example adds a "gift" field to every person whose birthday is in the
next day.
new MongoDate(), '$lt' => new MongoDate(strtotime("+1 day")));
$people->update(array("birthday" => $today), array('$set' => array('gift' => $surprise)), array("multiple" => true));
?>
See Also
The PHP documentation on updates and the >> MongoDB core docs.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCollection::validate
(PECL mongo >=0.9.0)
MongoCollection::validate - Validates this collection
Description
public array MongoCollection::validate ([ bool $scan_data = FALSE ] )
Parameters
scan_data
Only validate indices, not the base collection.
Return Values
Returns the database's evaluation of this object.
----------------------------------------------------------------------
Table of Contents
* MongoCollection::batchInsert - Inserts multiple documents into this
collection
* MongoCollection::__construct - Creates a new collection
* MongoCollection::count - Counts the number of documents in this
collection
* MongoCollection::createDBRef - Creates a database reference
* MongoCollection::deleteIndex - Deletes an index from this collection
* MongoCollection::deleteIndexes - Delete all indices for this
collection
* MongoCollection::drop - Drops this collection
* MongoCollection::ensureIndex - Creates an index on the given field(s),
or does nothing if the index already exists
* MongoCollection::find - Querys this collection
* MongoCollection::findOne - Querys this collection, returning a single
element
* MongoCollection::__get - Gets a collection
* MongoCollection::getDBRef - Fetches the document pointed to by a
database reference
* MongoCollection::getIndexInfo - Returns an array of index names for
this collection
* MongoCollection::getName - Returns this collection's name
* MongoCollection::getSlaveOkay - Get slaveOkay setting for this
collection
* MongoCollection::group - Performs an operation similar to SQL's GROUP
BY command
* MongoCollection::insert - Inserts an array into the collection
* MongoCollection::remove - Remove records from this collection
* MongoCollection::save - Saves an object to this collection
* MongoCollection::setSlaveOkay - Change slaveOkay setting for this
collection
* MongoCollection::__toString - String representation of this collection
* MongoCollection::update - Update records based on a given criteria
* MongoCollection::validate - Validates this collection
----------------------------------------------------------------------
----------------------------------------------------------------------
The MongoCursor class
Introduction
A cursor is used to iterate through the results of a database query. For
example, to query the database and see all results, you could do:
find();
var_dump(iterator_to_array($cursor));
?>
You don't generally create cursors using the MongoCursor constructor, you
get a new cursor by calling MongoCollection::find() (as shown above).
Suppose that, in the example above, $collection was a 50GB collection. We
certainly wouldn't want to load that into memory all at once, which is
what a cursor is for: allowing the client to access the collection in
dribs and drabs.
If we have a large result set, we can iterate through it, loading a few
megabytes of results into memory at a time. For example, we could do:
find();
foreach ($cursor as $doc) {
// do something to each document
}
?>
This will go through each document in the collection, loading and garbage
collecting documents as needed.
Note that this means that a cursor does not "contain" the database
results, it just manages them. Thus, if you print a cursor (with, say,
var_dump() or print_r()), you'll just get the cursor object, not your
documents. To get the documents themselves, you can use one of the methods
shown above.
Cursor Stages
A MongoCursor has two "life stages": pre- and post- query. When a cursor
is created, it has not yet contacted the database, so it is in its
pre-query state. In this state, the client can further specify what they
want the query to do, including adding limits, skips, sorts, and more
advanced options.
When the client attempts to get a result (by calling MongoCursor::next(),
directly or indirectly), the cursor moves into the post-query stage. At
this point, the query has been executed by the database and cannot be
modified anymore.
find()->limit(10);
// database has not yet been queried, so more search options can be added
$cursor = $cursor->sort(array("a" => 1));
var_dump($cursor->getNext());
// now database has been queried and more options cannot be added
// so this will throw an exception:
$cursor->skip(4);
?>
Class synopsis
implements Iterator {
/* Static Fields */
static boolean $MongoCursor->slaveOkay = FALSE ;
static integer $timeout = 20000 ;
/* Methods */
public MongoCursor MongoCursor::addOption ( string $key , mixed $value )
public MongoCursor MongoCursor::batchSize ( int $num )
MongoCursor::__construct ( Mongo $connection , string $ns [, array $query
= array() [, array $fields = array() ]] )
public int MongoCursor::count ([ bool $foundOnly = FALSE ] )
public array MongoCursor::current ( void )
public bool MongoCursor::dead ( void )
protected void MongoCursor::doQuery ( void )
public array MongoCursor::explain ( void )
public MongoCursor MongoCursor::fields ( array $f )
public array MongoCursor::getNext ( void )
public bool MongoCursor::hasNext ( void )
public MongoCursor MongoCursor::hint ( array $key_pattern )
public MongoCursor MongoCursor::immortal ([ bool $liveForever = true ] )
public array MongoCursor::info ( void )
public string MongoCursor::key ( void )
public MongoCursor MongoCursor::limit ( int $num )
public void MongoCursor::next ( void )
public MongoCursor MongoCursor::partial ([ bool $okay = true ] )
public void MongoCursor::reset ( void )
public void MongoCursor::rewind ( void )
public MongoCursor MongoCursor::skip ( int $num )
public MongoCursor MongoCursor::slaveOkay ([ bool $okay = true ] )
public MongoCursor MongoCursor::snapshot ( void )
public MongoCursor MongoCursor::sort ( array $fields )
public MongoCursor MongoCursor::tailable ([ bool $tail = true ] )
public MongoCursor MongoCursor::timeout ( int $ms )
public bool MongoCursor::valid ( void )
}
Static Variables
MongoCursor::slaveOkay
If the query should have the "slaveOkay" flag set, which allows
reads on the slave (slaves are, by default, just for backup and
unreadable). Can be overridden with MongoCursor::slaveOkay().
MongoCursor::timeout
Set timeout in milliseconds for all database responses. To wait
forever, use -1. Can be overridden with MongoCursor::timeout().
This does not cause the MongoDB server to cancel the operation, it
just causes the driver to stop waiting for a response and throw a
MongoCursorTimeoutException.
See Also
MongoDB core docs on >> cursors.
----------------------------------------------------------------------
MongoCursor::addOption
(PECL mongo >=1.0.4)
MongoCursor::addOption - Adds a top-level key/value pair to a query
Description
public MongoCursor MongoCursor::addOption ( string $key , mixed $value )
This is an advanced function and should not be used unless you know what
you're doing.
A query can optionally be nested in a "query" field if other options, such
as a sort or hint, are given. For instance, adding a sort causes the query
to become a subfield of a bigger query object, like:
$query, "orderby" => $sort);
?>
This method is for adding a top-level field to a query. It makes the query
a subobject (if it isn't already) and adds the key/value pair of your
chosing to the top level.
Warning
It cannot be used to add extra criteria to a query on the fly. For
instance, this will not work:
find()->addOption("name", "joe")->addOption("age", 20);
?>
This does not query for a user named "joe" with an age of 20.
Parameters
key
Fieldname to add.
value
Value to add.
Return Values
Returns this cursor.
Errors/Exceptions
Throws MongoCursorException if this cursor has started iterating.
Examples
Example #1 MongoCursor::addOption() example
Using MongoCursor::skip() to skip over millions of results can become
slow. One way around this is to use $min or $max options for the query.
These can be handy, but they require an index on exactly the fields being
searched for. This is an example of how to use $min as an alternative to
MongoCursor::skip().
ensureIndex(array("ts" => 1));
// you may have to modify this to run in a reasonable amount of time on slow
// machines (should take about 30 seconds on a good machine)
for ($i = 0; $i < 30000000; $i++) {
$c->insert(array("ts" => new MongoDate(), "i" => $i));
}
$now = strtotime("now");
// find documents inserted in the last 2 seconds
$cursor = $c->find()->addOption('$min', array("ts" => $now-2));
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::batchSize
(PECL mongo >=1.0.11)
MongoCursor::batchSize - Sets the number of results returned per result
set
Description
public MongoCursor MongoCursor::batchSize ( int $num )
This cannot override MongoDB's limit on the amount of data it will return
to the client (i.e., if you set batch size to 1,000,000,000, MongoDB will
still only return 4-16MB of results).
To ensure consistent behavior, the rules of batchSize and limit behavior a
little complex but work "as expected". The rules are: hard limits override
soft limits with preference given to MongoCursor::limit() over
MongoCursor::batchSize(). After that, whichever is set and lower than the
other will take precedence. Some examples:
limit(-20)->batchSize(10);
// one batch, at most 10 items
$cursor->limit(20)->batchSize(-10);
// first batch: at most 10 items
$cursor->limit(10);
// first batch: at most 10 items
$cursor->limit(10)->batchSize(20);
// first batch: at most 10 items
$cursor->limit(20)->batchSize(10);
$cursor->limit(30)->batchSize(7)
// if we iterate through 28 items, the next call to getNext() will contact the
// database and request a batch of 2 documents
?>
Parameters
num
The number of results to return in the next batch.
Return Values
Returns this cursor.
Errors/Exceptions
Throws MongoCursorException if this cursor has started iterating. This
will change in 1.0.12, as this should be able to be called at any time.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::__construct
(PECL mongo >=0.9.0)
MongoCursor::__construct - Create a new cursor
Description
MongoCursor::__construct ( Mongo $connection , string $ns [, array $query
= array() [, array $fields = array() ]] )
Parameters
connection
Database connection.
ns
Full name of database and collection.
query
Database query.
fields
Fields to return.
Return Values
Returns the new cursor.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::count
(PECL mongo >=0.9.2)
MongoCursor::count - Counts the number of results for this query
Description
public int MongoCursor::count ([ bool $foundOnly = FALSE ] )
This method does not affect the state of the cursor: if you haven't
queried yet, you can still apply limits, skips, etc. If you have started
iterating through results, it will not move the current position of the
cursor. If you have exhasted the cursor, it will not reset it.
Parameters
foundOnly
Send cursor limit and skip information to the count function, if
applicable.
Return Values
The number of documents returned by this cursor's query.
Examples
Example #1 MongoCursor::count() example
insert(array('x'=>1));
$collection->insert(array('x'=>2));
$collection->insert(array('x'=>3));
$cursor = $collection->find();
var_dump($cursor->count());
var_dump($cursor->count(true));
$cursor->limit(2);
var_dump($cursor->count());
var_dump($cursor->count(true));
?>
The above example will output something similar to:
int(3)
int(3)
int(3)
int(2)
Errors/Exceptions
Throws MongoConnectionException if it cannot reach the database.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::current
(PECL mongo >=0.9.0)
MongoCursor::current - Returns the current element
Description
public array MongoCursor::current ( void )
This returns NULL until MongoCursor::next() is called.
Parameters
This function has no parameters.
Return Values
The current result as an associative array.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::dead
(PECL mongo >=0.9.6)
MongoCursor::dead - Checks if there are documents that have not been sent
yet from the database for this cursor
Description
public bool MongoCursor::dead ( void )
The database sends responses in batches of documents, up to 4Mb of
documents per response. This method checks if the database has more
batches or if the result set has been exhausted.
A cursor being "dead" does not mean that MongoCursor::hasNext() will
return FALSE, it only means that the database is done sending results to
the client. The client should continue iterating through results until
MongoCursor::hasNext() is FALSE.
Parameters
This function has no parameters.
Return Values
Returns if there are more results that have not been sent to the client,
yet.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::doQuery
(No version information available, might only be in SVN)
MongoCursor::doQuery - Execute the query.
Description
protected void MongoCursor::doQuery ( void )
Parameters
This function has no parameters.
Return Values
NULL.
Errors/Exceptions
Throws MongoConnectionException if it cannot reach the database.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::explain
(PECL mongo >=0.9.2)
MongoCursor::explain - Return an explanation of the query, often useful
for optimization and debugging
Description
public array MongoCursor::explain ( void )
Parameters
This function has no parameters.
Return Values
Returns an explanation of the query.
Examples
Example #1 MongoCursor::explain() example
find(array("x"=>1), array("y"));
$cursor->sort(array("z" => 1))->limit(4)->skip(5);
var_dump($cursor->explain());
?>
The above example will output something similar to:
array(8) {
["cursor"]=>
string(15) "BtreeCursor x_1"
["startKey"]=>
array(1) {
["x"]=>
int(1)
}
["endKey"]=>
array(1) {
["x"]=>
int(1)
}
["nscanned"]=>
float(4)
["n"]=>
int(4)
["scanAndOrder"]=>
int(1)
["millis"]=>
int(3)
["allPlans"]=>
array(2) {
[0]=>
array(3) {
["cursor"]=>
string(15) "BtreeCursor x_1"
["startKey"]=>
array(1) {
["x"]=>
int(1)
}
["endKey"]=>
array(1) {
["x"]=>
int(1)
}
}
[1]=>
array(3) {
["cursor"]=>
string(11) "BasicCursor"
["startKey"]=>
array(0) {
}
["endKey"]=>
array(0) {
}
}
}
}
Errors/Exceptions
Throws MongoConnectionException if it cannot reach the database.
See Also
MongoDB core docs on >> explain.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::fields
(PECL mongo >=1.0.6)
MongoCursor::fields - Sets the fields for a query
Description
public MongoCursor MongoCursor::fields ( array $f )
Fields are specified by "fieldname" : bool. TRUE indicates that a field
should be returned, FALSE indicates that it should not be returned. You
can also use 1 and 0 instead of TRUE and FALSE.
Thus, to return only the "summary" field, one could say:
fields(array("summary" => true));
?>
To return all fields except the "hidden" field:
fields(array("hidden" => false));
?>
Parameters
f
Fields to return (or not return).
Return Values
Returns this cursor.
Errors/Exceptions
Throws MongoCursorException if this cursor has started iterating or a
scalar argument is given.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::getNext
(PECL mongo >=0.9.0)
MongoCursor::getNext - Return the next object to which this cursor points,
and advance the cursor
Description
public array MongoCursor::getNext ( void )
This is identical to the function:
next();
return $this->current();
}
?>
Parameters
This function has no parameters.
Return Values
Returns the next object.
Errors/Exceptions
Throws MongoConnectionException if it cannot reach the database and
MongoCursorTimeoutException if the timeout is exceeded.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::hasNext
(PECL mongo >=0.9.0)
MongoCursor::hasNext - Checks if there are any more elements in this
cursor
Description
public bool MongoCursor::hasNext ( void )
Parameters
This function has no parameters.
Return Values
Returns if there is another element.
Errors/Exceptions
Throws MongoConnectionException if it cannot reach the database and
MongoCursorTimeoutException if the timeout is exceeded.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::hint
(PECL mongo >=0.9.0)
MongoCursor::hint - Gives the database a hint about the query
Description
public MongoCursor MongoCursor::hint ( array $key_pattern )
Parameters
key_pattern
Indexes to use for the query.
Return Values
Returns this cursor.
Errors/Exceptions
Throws MongoCursorException if this cursor has started iterating.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::immortal
(PECL mongo >=1.0.1)
MongoCursor::immortal - Sets whether this cursor will timeout
Description
public MongoCursor MongoCursor::immortal ([ bool $liveForever = true ] )
After remaining idle for some amount of time, cursor, by default, "die."
This is generally the behavior one wants. The database cleans up a cursor
once all of its results have been sent to the client, but if the client
doesn't request all of the results, the cursor will languish there, taking
up resources. Thus, after a few minutes, the cursor "times out" and the
database assumes the client has gotten everything it needs and cleans up
its the cursor's resources.
If, for some reason, you need a cursor to hang around for a long time, you
can prevent the database from cleaning it up by using this method.
However, if you make a cursor immortal, you need to iterate through all of
its results (or at least until Cursor::dead() returns TRUE) or the cursor
will hang around the database forever, taking up resources.
Parameters
liveForever
If the cursor should be immortal.
Return Values
Returns this cursor.
Errors/Exceptions
Throws MongoCursorException if this cursor has started iterating.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::info
(PECL mongo >=1.0.5)
MongoCursor::info - Gets the query, fields, limit, and skip for this
cursor
Description
public array MongoCursor::info ( void )
This can be called before or after the query.
Parameters
This function has no parameters.
Return Values
Returns the namespace, limit, skip, query, and fields for this cursor.
Changelog
Version Description
1.0.10 Added started_iterating field, a boolean indicating if cursor is
pre- or post-query.
Added a number of other fields, including id (the cursor id), at
(the driver's counter of which document is current), numReturned
1.1.0 (the number returned by the server in the current batch), and
server (which server the query was sent to-useful in conjunction
with MongoCursor::slaveOkay()).
Examples
Example #1 MongoCursor::info() example
foo->bar->find(array("x" => 4), array("y" => false));
var_dump($cursor->info());
?>
The above example will output something similar to:
array(5) {
["ns"]=>
string(7) "foo.bar"
["limit"]=>
int(0)
["skip"]=>
int(0)
["query"]=>
array(1) {
["x"]=>
int(4)
}
["fields"]=>
array(1) {
["y"]=>
int(0)
}
}
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::key
(PECL mongo >=0.9.0)
MongoCursor::key - Returns the current result's _id
Description
public string MongoCursor::key ( void )
Parameters
This function has no parameters.
Return Values
The current result's _id as a string.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::limit
(PECL mongo >=0.9.0)
MongoCursor::limit - Limits the number of results returned
Description
public MongoCursor MongoCursor::limit ( int $num )
Parameters
num
The number of results to return.
Return Values
Returns this cursor.
Errors/Exceptions
Throws MongoCursorException if this cursor has started iterating.
See Also
MongoDB core docs on >> limit.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::next
(PECL mongo >=0.9.0)
MongoCursor::next - Advances the cursor to the next result
Description
public void MongoCursor::next ( void )
Parameters
This function has no parameters.
Return Values
NULL.
Errors/Exceptions
Throws MongoConnectionException if it cannot reach the database and
MongoCursorTimeoutException if the timeout is exceeded.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::partial
(PECL mongo >=1.2.0)
MongoCursor::partial - If this query should fetch partial results from
mongos if a shard is down
Description
public MongoCursor MongoCursor::partial ([ bool $okay = true ] )
This option allows mongos to send partial query results if a shard is
unreachable. This is only applicable when running a sharded MongoDB
cluster and connecting to a mongos.
If a shard goes down and a query needs to be sent to that shard, mongos
will return the results (if any) from shards it already contacted, then an
error message that it could not reach the shard (a MongoCursorException in
PHP). If you would like to get whatever results mongos can provide and no
exception, you can use this method. Note that this means that you won't
have an indication that a shard is down in your query response.
This has no effect on the query if all shards are reachable. This flag was
implemented in MongoDB version 1.7.5, so will only work with that version
and higher.
Parameters
okay
If receiving partial results is okay.
Return Values
Returns this cursor.
Errors/Exceptions
Throws MongoCursorException if this cursor has started iterating.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::reset
(PECL mongo >=0.9.0)
MongoCursor::reset - Clears the cursor
Description
public void MongoCursor::reset ( void )
Parameters
This function has no parameters.
Return Values
NULL.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::rewind
(PECL mongo >=0.9.0)
MongoCursor::rewind - Returns the cursor to the beginning of the result
set
Description
public void MongoCursor::rewind ( void )
This is identical to the function:
reset();
$this->next();
}
?>
Parameters
This function has no parameters.
Return Values
NULL.
Errors/Exceptions
Throws MongoConnectionException if it cannot reach the database and
MongoCursorTimeoutException if the timeout is exceeded.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::skip
(PECL mongo >=0.9.0)
MongoCursor::skip - Skips a number of results
Description
public MongoCursor MongoCursor::skip ( int $num )
Parameters
num
The number of results to skip.
Return Values
Returns this cursor.
Errors/Exceptions
Throws MongoCursorException if this cursor has started iterating.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::slaveOkay
(PECL mongo >=0.9.4)
MongoCursor::slaveOkay - Sets whether this query can be done on a slave
Description
public MongoCursor MongoCursor::slaveOkay ([ bool $okay = true ] )
Calling this will make the driver route reads to slaves if:
* You are using a replica set and
* You created a Mongo instance using the option "replicaSet" => true and
* There is a healthy slave that can be reached by the driver.
You can check which server was used for this query by calling
MongoCursor::info() after running the query. It's server field will show
which server the query was sent to.
Note that you should use this function even if you do not use the
automatic routing to slaves. If you connect directly to a secondary in a
replica set, you still need to call this function, which basically tells
the database that you are aware that you might be getting older data and
you're okay with that. If you do not call this, you'll get "not master"
errors when you try to query.
This method will override the static class variable
MongoCursor::slaveOkay. It will also override Mongo::setSlaveOkay(),
MongoDB::setSlaveOkay() and MongoCollection::setSlaveOkay().
Parameters
okay
If it is okay to query the slave.
Return Values
Returns this cursor.
Errors/Exceptions
Throws MongoCursorException if this cursor has started iterating.
Examples
Example #1 MongoCursor::slaveOkay() example
find();
// can query slave
$cursor = $collection->find()->slaveOkay();
MongoCursor::$slaveOkay = true;
// can query slave
$cursor = $collection->find();
// cannot query slave
$cursor = $collection->find()->slaveOkay(false);
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::snapshot
(PECL mongo >=0.9.4)
MongoCursor::snapshot - Use snapshot mode for the query
Description
public MongoCursor MongoCursor::snapshot ( void )
Use snapshot mode for the query. Snapshot mode assures no duplicates are
returned, or objects missed, which were present at both the start and end
of the query's execution (if an object is new during the query, or deleted
during the query, it may or may not be returned, even with snapshot mode).
Note that short query responses (less than 1MB) are always effectively
snapshotted.
Currently, snapshot mode may not be used with sorting or explicit hints.
Parameters
This function has no parameters.
Return Values
Returns this cursor.
Errors/Exceptions
Throws MongoCursorException if this cursor has started iterating.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::sort
(PECL mongo >=0.9.0)
MongoCursor::sort - Sorts the results by given fields
Description
public MongoCursor MongoCursor::sort ( array $fields )
Parameters
fields
The fields by which to sort.
Return Values
Returns this cursor.
Errors/Exceptions
Throws MongoCursorException if this cursor has started iterating.
Examples
Example #1 MongoCursor::sort() example
sort(array('x' => 1));
// the associative array is ordered, for instance, these two
// examples might yield different results:
// sort date ascending and age descending
$cursor->sort(array('date' => 1, 'age' => -1));
// sort age descending and date ascending
$cursor->sort(array('age' => -1, 'date' => 1));
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::tailable
(PECL mongo >=0.9.4)
MongoCursor::tailable - Sets whether this cursor will be left open after
fetching the last results
Description
public MongoCursor MongoCursor::tailable ([ bool $tail = true ] )
Mongo has a feature known as tailable cursors which are similar to the
Unix "tail -f" command.
Tailable means cursor is not closed when the last data is retrieved.
Rather, the cursor marks the final object's position. you can resume using
the cursor later, from where it was located, if more data were received.
Like any "latent cursor", the cursor may become invalid at some point --
for example if that final object it references were deleted. Thus, you
should be prepared to requery if the cursor is MongoCursor::dead().
Parameters
tail
If the cursor should be tailable.
Return Values
Returns this cursor.
Errors/Exceptions
Throws MongoCursorException if this cursor has started iterating.
Examples
Example #1 MongoCursor::tailable() example
find()->tailable();
$results = array();
while (1) {
if (!$cursor->hasNext()) {
// we've read all the results, exit
if ($cursor->dead()) {
break;
}
// read all results so far, wait for more
sleep(10);
}
else {
$results[] = $cursor->getNext();
}
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::timeout
(PECL mongo >=1.0.3)
MongoCursor::timeout - Sets a client-side timeout for this query
Description
public MongoCursor MongoCursor::timeout ( int $ms )
A timeout can be set at any time and will affect subsequent queries on the
cursor, including fetching more results from the database. For example, to
wait forever for an initial response but timeout after 100 ms for
subsequent results, one could say:
find();
// $cursor->hasNext() executes the query. No timeout has been set, so the
// program will wait as long as necessary for a response.
while ($cursor->hasNext()) {
$cursor->timeout(100);
// now the timeout has been set, so if the cursor needs to get more results
// from the database, it will only wait 100 ms for the database's reply
try {
print_r($cursor->getNext());
}
catch(MongoCursorTimeoutException $e) {
echo "query took too long!";
}
}
?>
A timeout of 0 (or a negative number) will wait forever so it can be used
to reset the cursor if a timeout is no longer needed.
Parameters
ms
The number of milliseconds for the cursor to wait for a response.
By default, the cursor will wait forever.
Return Values
This cursor.
Examples
Example #1 MongoCursor::timeout() example
A query where the cursor waits for one second for a response.
find()->timeout(1000);
try {
foreach ($cursor as $value) {
print_r($value);
}
}
catch(MongoCursorTimeoutException $e) {
echo "query took too long!";
}
?>
Errors/Exceptions
Causes methods that fetch results to throw MongoCursorTimeoutExceptions if
the query takes longer than the number of milliseconds specified.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCursor::valid
(PECL mongo >=0.9.0)
MongoCursor::valid - Checks if the cursor is reading a valid result.
Description
public bool MongoCursor::valid ( void )
Parameters
This function has no parameters.
Return Values
If the current result is not null.
----------------------------------------------------------------------
Table of Contents
* MongoCursor::addOption - Adds a top-level key/value pair to a query
* MongoCursor::batchSize - Sets the number of results returned per
result set
* MongoCursor::__construct - Create a new cursor
* MongoCursor::count - Counts the number of results for this query
* MongoCursor::current - Returns the current element
* MongoCursor::dead - Checks if there are documents that have not been
sent yet from the database for this cursor
* MongoCursor::doQuery - Execute the query.
* MongoCursor::explain - Return an explanation of the query, often
useful for optimization and debugging
* MongoCursor::fields - Sets the fields for a query
* MongoCursor::getNext - Return the next object to which this cursor
points, and advance the cursor
* MongoCursor::hasNext - Checks if there are any more elements in this
cursor
* MongoCursor::hint - Gives the database a hint about the query
* MongoCursor::immortal - Sets whether this cursor will timeout
* MongoCursor::info - Gets the query, fields, limit, and skip for this
cursor
* MongoCursor::key - Returns the current result's _id
* MongoCursor::limit - Limits the number of results returned
* MongoCursor::next - Advances the cursor to the next result
* MongoCursor::partial - If this query should fetch partial results from
mongos if a shard is down
* MongoCursor::reset - Clears the cursor
* MongoCursor::rewind - Returns the cursor to the beginning of the
result set
* MongoCursor::skip - Skips a number of results
* MongoCursor::slaveOkay - Sets whether this query can be done on a
slave
* MongoCursor::snapshot - Use snapshot mode for the query
* MongoCursor::sort - Sorts the results by given fields
* MongoCursor::tailable - Sets whether this cursor will be left open
after fetching the last results
* MongoCursor::timeout - Sets a client-side timeout for this query
* MongoCursor::valid - Checks if the cursor is reading a valid result.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Types
Table of Contents
* MongoId
* MongoCode
* MongoDate
* MongoRegex
* MongoBinData
* MongoInt32
* MongoInt64
* MongoDBRef
* MongoMinKey
* MongoMaxKey
* MongoTimestamp
MongoDB allows programmers to save and query for data expressed in all of
the basic PHP types, compound types (arrays, associative arrays, and
objects), and a half-dozen classes provided by the MongoDB PHP driver (for
regular expressions, dates, and other specialized applications).
Booleans and NULL
TRUE, FALSE, and NULL can be used as-is.
Numbers
Numbers are distinct from strings in MongoDB: "123" does not match 123.
Thus, if you want to make sure numbers are sorted and matched correctly,
you must make sure that they are actually saved as numbers.
123, "b" => "123");
$collection->insert($doc);
$doc->find(array("a" => 123)); // matches
$doc->find(array("a" => "123")); // doesn't match
$doc->find(array("a" => 123.0)); // matches
$doc->find(array("b" => 123)); // doesn't match
$doc->find(array("b" => "123")); // matches
?>
As noted above, floating point numbers do compare with/match integer
numbers as one would expect.
Large Numbers
By default, on a 32-bit system, numbers are sent to the database as 32-bit
integers. On a 64-bit system, they are sent as 64-bit integers. For
backwards compatibility, all systems deserialize 64-bit integers as
floating point numbers. Floating point numbers are not exact. If you need
exact values, you must tweak your >> php.ini settings.
On a 32-bit system, if mongo.long_as_object is set, 64-bit integers will
be returns as MongoInt64 objects. The integer will be stored in the value
field with perfect precision (as a string). You can also use MongoInt64 to
save 64-bit integers on 32-bit machines.
On 64-bit systems, you can either set mongo.long_as_object or set
mongo.native_long. mongo.native_long will return 64-bit integers and
"normal" PHP integers. You can use MongoInt32 to save 32-bit integers on
64-bit machines.
You should set the mongo.long_as_object and mongo.native_long behavior
that you plan to use, even if it is the default behavior (to protect
against future changes to the defaults).
See also: >> php.ini Options, MongoInt32, MongoInt64.
Strings
Strings must be UTF-8. Non-UTF-8 strings must either be converted to UTF-8
before being sent to the database or saved as binary data.
Regular expressions can be used to match strings, and are expressed using
the MongoRegex class.
Binary Data
Non-UTF-8 strings, images, and any other binary data should be sent to the
database using the MongoBinData type.
Dates
Dates can be created using the MongoDate class. They are stored as
milliseconds since the epoch.
MongoTimestamp is not for saving dates or timestamps, it is used
internally by MongoDB. Unless you are creating a tool that interacts with
the internals of replication or sharding, you should use MongoDate, not
MongoTimestamp.
Unique Ids
The driver will automatically create an _id field before inserting a
document (unless one is specified by the user). This field is an instance
of MongoId (called "ObjectId" in most other languages).
These ids are 12 bytes long and composed of:
* 4 bytes of timestamp
No two records can have the same id if they were inserted at different
times.
* 3 bytes machine id
No two records can have the same id if they were inserted on different
machines
* 2 bytes thread id
No two records can have the same id if they were inserted by different
threads running on the same machine.
* 3 bytes incrementing value
Each time an id is created, a global counter is incremented and used
as the increment value of the next id.
Thus, no two records can have the same id unless a single process on a
single machine managed to insert 256^3 (over 16 million) documents in one
second, overflowing the increment field.
JavaScript
MongoDB comes with a JavaScript engine, so you can embed JavaScript in
queries (using a $where clause), send it directly to the database to be
executed, and use it to perform aggregations.
For security, use MongoCode's scope field to use PHP variables in
JavaScript. Code that does not require external values can either use
MongoCode or just be a string. See the >> section on security for more
information about sending JavaScript to the database.
Arrays and Objects
Arrays and objects can also be saved to the database. An array with
ascending numeric keys will be saved as a an array, anything else will be
saved as an object.
insert(array("scores" => $scores));
// $scores will be saved as an object
$scores = array("quiz1" => 98, "midterm" => 100, "quiz2" => 73, "final" => 85);
$collection->insert(array("scores" => $scores));
?>
If you query for these objects using the database shell, they will look
like:
> db.students.find()
{ "_id" : ObjectId("4b06beada9ad6390dab17c43"), "scores" : [ 98, 100, 73, 85 ] }
{ "_id" : ObjectId("4b06bebea9ad6390dab17c44"), "scores" : { "quiz1" : 98, "midterm" : 100, "quiz2" : 73, "final" : 85 } }
The database can also save arbitrary PHP objects (although they will be
returned as associative arrays). The fields are used for the key/value
pairs. For example, a blog post might look like:
author = $author;
$this->content = $content;
$this->date = new MongoDate();
}
public function setTitle($title) {
$this->title = $title;
}
}
// create a simple blog post and insert it into the database
$post1 = new Post("Adam", "This is a blog post");
$blog->insert($post1);
// there is nothing restricting the type of the "author" field, so we can make
// it a nested object
$author = array("name" => "Fred", "karma" => 42);
$post2 = new Post($author, "This is another blog post.");
// we create an extra field by setting the title
$post2->setTitle("Second Post");
$blog->insert($post2);
?>
From the database shell, this will look something like:
> db.blog.find()
{ "_id" : ObjectId("4b06c263edb87a281e09dad8"), "author" : "Adam", "content" : "This is a blog post", "comments" : [ ], "date" : "Fri Nov 20 2009 11:22:59 GMT-0500 (EST)" }
{ "_id" : ObjectId("4b06c282edb87a281e09dad9"), "author" : { "name" : "Fred", "karma" : 42 }, "content" : "This is a blog post", "comments" : [ ], "date" : "Fri Nov 20 2009 11:23:30 GMT-0500 (EST)", "title" : "Second Post" }
The driver will not detect reference loops in arrays and objects. For
example, this will give a fatal error:
insert($GLOBALS);
?>
Fatal error: Nesting level too deep - recursive dependency?
If you need to insert documents that may have recursive dependency, you
have to check for it yourself before passing it to the driver.
----------------------------------------------------------------------
The MongoId class
Introduction
A unique identifier created for database objects. If an object is inserted
into the database without an _id field, an _id field will be added to it
with a MongoId instance as its value. If the data has a naturally occuring
unique field (say, a username or timestamp) it is fine to use this as the
_id field instead, and it will not be replaced with a MongoId.
Instances of the MongoId class fulfill the role that autoincrementing does
in a relational database: to provide a unique key if the data does not
natually have one. Autoincrementing does not work well with a sharded
database, as it is impossible to find what the next number should be
quickly. This class fulfills the constraints of quickly generating a value
that is unique across shards.
Each MongoId is 12 bytes (making its string form 24 hexidecimal
characters). The first four bytes are a timestamp, the next three are a
hash of the client machine's hostname, the next two are the two least
significant bytes of the process id running the script, and the last three
bytes are an incrementing value.
MongoIds are serializable/unserializable. Their serialized form is similar
to their string form:
C:7:"MongoId":24:{4af9f23d8ead0e1d32000000}
Class synopsis
MongoId {
public string $MongoId->$id = NULL ;
/* Methods */
MongoId::__construct ([ string $id = NULL ] )
public static string MongoId::getHostname ( void )
public int MongoId::getInc ( void )
public int MongoId::getPID ( void )
public int MongoId::getTimestamp ( void )
public static MongoId MongoId::__set_state ( array $props )
public string MongoId::__toString ( void )
}
Fields
$id
This field contains the string representation of this object.
See Also
MongoDB core docs on >> ids.
----------------------------------------------------------------------
MongoId::__construct
(PECL mongo >= 0.8.0)
MongoId::__construct - Creates a new id
Description
MongoId::__construct ([ string $id = NULL ] )
Parameters
id
A string to use as the id. Must be 24 hexidecimal characters. If
an invalid string is passed to this constructor, the constructor
will ignore it and create a new id value.
Return Values
Returns a new id.
Examples
Example #1 MongoId::__construct() example
This example shows how to create a new id. This is seldom necessary, as
the driver adds an id to arrays automatically before storing them in the
database.
The above example will output something similar to:
49a7011a05c677b9a916612a
49a702d5450046d3d515d10d
Example #2 Parameter example
This example shows how to use a string parameter to initialize a MongoId
with a given value.
The above example will output something similar to:
bool(true)
See Also
* MongoId::__toString() - Returns a hexidecimal representation of this
id
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoId::getHostname
(PECL mongo >= 1.0.8)
MongoId::getHostname - Gets the hostname being used for this machine's ids
Description
public static string MongoId::getHostname ( void )
This returns the hostname MongoId is using to generate unique ids. This
should be the same value gethostname() returns.
It is identical to the function:
Parameters
This function has no parameters.
Return Values
Returns the hostname.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoId::getInc
(PECL mongo >= 1.0.11)
MongoId::getInc - Gets the incremented value to create this id
Description
public int MongoId::getInc ( void )
Parameters
This function has no parameters.
Return Values
Returns the incremented value used to create this MongoId.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoId::getPID
(PECL mongo >= 1.0.11)
MongoId::getPID - Gets the process id used to create this
Description
public int MongoId::getPID ( void )
Parameters
This function has no parameters.
Return Values
Returns the PID used to create this MongoId.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoId::getTimestamp
(PECL mongo >= 1.0.1)
MongoId::getTimestamp - Gets the number of seconds since the epoch that
this id was created
Description
public int MongoId::getTimestamp ( void )
This returns the same thing as running time() when the id is created.
Parameters
This function has no parameters.
Return Values
Returns the number of seconds since the epoch that this id was created.
There are only four bytes of timestamp stored, so MongoDate is a better
choice for storing exact or wide-ranging times.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoId::__set_state
(PECL mongo >= 1.0.8)
MongoId::__set_state - Create a dummy MongoId
Description
public static MongoId MongoId::__set_state ( array $props )
This function is only used by PHP internally, it shouldn't need to ever be
called by the user.
It is identical to the function:
Parameters
props
Theoretically, an array of properties used to create the new id.
However, as MongoId instances have no properties, this is not
used.
Return Values
A new id with the value "000000000000000000000000".
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoId::__toString
(PECL mongo >= 0.8.0)
MongoId::__toString - Returns a hexidecimal representation of this id
Description
public string MongoId::__toString ( void )
Parameters
This function has no parameters.
Return Values
This id.
Examples
Example #1 MongoId::__toString() example
selectDB("foo")->selectCollection("bar");
$collection->insert(array( "x" => "y" ));
$collection->insert(array( "x" => "y" ));
$cursor = $collection->find();
$r1 = $cursor->next();
$r2 = $cursor->next();
echo $r1["_id"] . "\n";
echo $r2["_id"] . "\n";
?>
The above example will output something similar to:
49a7011a05c677b9a916612a
49a702d5450046d3d515d10d
----------------------------------------------------------------------
Table of Contents
* MongoId::__construct - Creates a new id
* MongoId::getHostname - Gets the hostname being used for this machine's
ids
* MongoId::getInc - Gets the incremented value to create this id
* MongoId::getPID - Gets the process id used to create this
* MongoId::getTimestamp - Gets the number of seconds since the epoch
that this id was created
* MongoId::__set_state - Create a dummy MongoId
* MongoId::__toString - Returns a hexidecimal representation of this id
----------------------------------------------------------------------
----------------------------------------------------------------------
The MongoCode class
Introduction
Represents JavaScript code for the database.
MongoCode objects are composed of two parts: a string of code and an
optional scope. The string of code must be valid JavaScript. The scope is
a associative array of variable name/value pairs.
Class synopsis
MongoCode {
/* Methods */
__construct ( string $code [, array $scope = array() ] )
public string __toString ( void )
}
----------------------------------------------------------------------
MongoCode::__construct
(PECL mongo >= 0.8.3)
MongoCode::__construct - Creates a new code object
Description
MongoCode::__construct ( string $code [, array $scope = array() ] )
Parameters
code
A string of code.
scope
The scope to use for the code.
Return Values
Returns a new code object.
Examples
Example #1 MongoCode::__construct() example
4));
var_dump($code);
?>
The above example will output something similar to:
object(MongoCode)#1 (2) {
["scope"]=>
array(1) {
["x"]=>
int(4)
}
["code"]=>
string(80) "function() { for(i=0;i<10;i++) { db.foo.update({z : i}, {z : x}); } return x-1; }"
}
Example #2 Using MongoCode() with $where
This example queries a collection for elements where the 'x' fields is
less than $y. Notice that PHP objects can be passed into the JavaScript
scope and that the JavaScript function returns a boolean.
find(array('$where' => new MongoCode('function() { return this.x < y; }', array('y'=>$y))));
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoCode::__toString
(PECL mongo >= 0.8.3)
MongoCode::__toString - Returns this code as a string
Description
public string MongoCode::__toString ( void )
Parameters
This function has no parameters.
Return Values
This code, the scope is not returned.
Examples
Example #1 MongoCode::__toString() example
"hi"));
echo "$code\n";
$code = new MongoCode('function() { for(i=0;i<10;i++) { db.foo.update({x:i}, {x:i+1}); } }');
echo "$code\n";
?>
The above example will output something similar to:
return x;
function() { for(i=0;i<10;i++) { db.foo.update({x:i}, {x:i+1}); } }
----------------------------------------------------------------------
Table of Contents
* MongoCode::__construct - Creates a new code object
* MongoCode::__toString - Returns this code as a string
----------------------------------------------------------------------
----------------------------------------------------------------------
The MongoDate class
Introduction
Represent date objects for the database. This class should be used to save
dates to the database and to query for dates. For example:
save(array("ts" => new MongoDate()));
$start = new MongoDate(strtotime("2010-01-15 00:00:00"));
$end = new MongoDate(strtotime("2010-01-30 00:00:00"));
// find dates between 1/15/2010 and 1/30/2010
$collection->find(array("ts" => array('$gt' => $start, '$lte' => $end)));
?>
MongoDB stores dates as milliseconds past the epoch. This means that dates
do not contain timezone information. Timezones must be stored in a
separate field if needed. Second, this means that any precision beyond
milliseconds will be lost when the document is sent to/from the database.
Class synopsis
MongoDate {
/* Fields */
public int $MongoDate->sec ;
public int $usec ;
/* Methods */
MongoDate::__construct ([ int $sec = time() [, int $usec = 0 ]] )
public string MongoDate::__toString ( void )
}
----------------------------------------------------------------------
MongoDate::__construct
(PECL mongo >= 0.8.1)
MongoDate::__construct - Creates a new date.
Description
MongoDate::__construct ([ int $sec = time() [, int $usec = 0 ]] )
Creates a new date. If no parameters are given, the current time is used.
Parameters
sec
Number of seconds since January 1st, 1970.
usec
Microseconds.
Return Values
Returns this new date.
Examples
Example #1 MongoDate::__construct() example
This example demonstrates creating a new date with the current time and a
new date with a given time.
The above example will output something similar to:
0.23660600 1235685067
0.00000000 1234567890
0.00000000 1241150401
See Also
* MongoDate::__toString() - Returns a string representation of this date
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDate::__toString
(PECL mongo >= 0.8.1)
MongoDate::__toString - Returns a string representation of this date
Description
public string MongoDate::__toString ( void )
Returns a string representation of this date, similar to the
representation returned by microtime().
Parameters
This function has no parameters.
Return Values
This date.
----------------------------------------------------------------------
Table of Contents
* MongoDate::__construct - Creates a new date.
* MongoDate::__toString - Returns a string representation of this date
----------------------------------------------------------------------
----------------------------------------------------------------------
The MongoRegex class
Introduction
This class can be used to create regular expressions. Typically, these
expressions will be used to query the database and find matching strings.
More unusually, they can be saved to the database and retrieved.
Mongo recognizes six regular expression flags:
* i
Case insensitive
* m
Multiline
* x
Can contain comments
* l
locale
* s
dotall, "." matches everything, including newlines
* u
match unicode
Class synopsis
MongoRegex {
/* Fields */
public string $MongoRegex->regex ;
public string $flags ;
/* Methods */
MongoRegex::__construct ( string $regex )
public string MongoRegex::__toString ( void )
}
----------------------------------------------------------------------
MongoRegex::__construct
(PECL mongo >= 0.8.1)
MongoRegex::__construct - Creates a new regular expression
Description
MongoRegex::__construct ( string $regex )
Creates a new regular expression.
Parameters
regex
Regular expression string of the form /expr/flags.
Return Values
Returns a new regular expression.
Examples
Example #1 MongoRegex::__construct() example
This example uses a regular expression to query for all documents with a
username field matching a regular expression.
find(array("username" => $joe_search));
?>
See Also
* MongoRegex::__toString() - A string representation of this regular
expression
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoRegex::__toString
(PECL mongo >= 0.8.1)
MongoRegex::__toString - A string representation of this regular
expression
Description
public string MongoRegex::__toString ( void )
Returns a string representation of this regular expression.
Parameters
This function has no parameters.
Return Values
This regular expression in the form "/expr/flags".
Examples
Example #1 MongoRegex::__toString() example
regex . "\n";
echo $r->flags . "\n";
echo "$r\n";
?>
The above example will output something similar to:
[a-fA-F0-9]{16}
g
/[a-fA-F0-9]{16}/g
----------------------------------------------------------------------
Table of Contents
* MongoRegex::__construct - Creates a new regular expression
* MongoRegex::__toString - A string representation of this regular
expression
----------------------------------------------------------------------
----------------------------------------------------------------------
The MongoBinData class
Introduction
An object that can be used to store or retrieve binary data from the
database.
The maximum size of a single object that can be inserted into the database
is 4Mb. For data that is larger than this (movies, music, Henry
Kissinger's autobiography), use MongoGridFS. For data that is smaller than
4Mb, it's probably be easier to just embed it into the document using
MongoBinData.
For example, to embed an image in a document, one could write:
"foobity",
"pic" => new MongoBinData(file_get_contents("gravatar.jpg"))
);
$users->save($profile);
?>
This class contains a type field, which currently gives no additional
functionality in the driver or the database. There are five predefined
types (which are the class constants listed below), and the user can
create their own (at the risk of the BSON spec catching up with them). By
default, the PHP driver always uses type 2: a byte array.
Class synopsis
MongoBinData {
/* Constants */
const int FUNC = 1 ;
const int BYTE_ARRAY = 2 ;
const int UUID = 3 ;
const int MD5 = 5 ;
const int CUSTOM = 128 ;
/* Fields */
public string $MongoBinData->bin ;
public int $type = 2 ;
/* Methods */
public MongoBinData::__construct ( string $data [, int $type = 2 ] )
public string MongoBinData::__toString ( void )
}
Predefined Constants
Binary Data Types
MongoBinData::FUNC
0x01
Function.
MongoBinData::BYTE_ARRAY
0x02
Array of bytes.
MongoBinData::UUID
0x03
Universally unique identifier.
MongoBinData::MD5
0x05
MD5.
MongoBinData::CUSTOM
0xf0
User-defined type.
----------------------------------------------------------------------
MongoBinData::__construct
(PECL mongo >= 0.8.1)
MongoBinData::__construct - Creates a new binary data object.
Description
public MongoBinData::__construct ( string $data [, int $type = 2 ] )
Creates a new binary data object.
There are five types of binary data currently recognized by the BSON spec:
function (0x01), byte array (0x02), UUID (0x03), MD5 (0x05), and user
defined (0x80). The default type is byte array (0x02). There is no
particular difference in how the driver or server interpret different
types, so by and large they are irrelevant for now. Any number (between 0
and 255) could be used for type, if the user is willing to assume the risk
that the database might eventually do something with binary data based on
type.
Parameters
data
Binary data.
type
Data type.
Return Values
Returns a new binary data object.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoBinData::__toString
(PECL mongo >= 0.8.1)
MongoBinData::__toString - The string representation of this binary data
object.
Description
public string MongoBinData::__toString ( void )
Parameters
This function has no parameters.
Return Values
Returns the string "". To access the contents of a
MongoBinData, use the bin field.
----------------------------------------------------------------------
Table of Contents
* MongoBinData::__construct - Creates a new binary data object.
* MongoBinData::__toString - The string representation of this binary
data object.
----------------------------------------------------------------------
----------------------------------------------------------------------
The MongoInt32 class
Introduction
The class can be used to save 32-bit integers to the database on a 64-bit
system.
Class synopsis
MongoInt32 {
/* Fields */
public string $MongoInt32->value ;
/* Methods */
public MongoInt32::__construct ( string $value )
public string MongoInt32::__toString ( void )
}
Fields
value
This is the string value of the 64-bit number. For instance, 123's
value would be "123".
----------------------------------------------------------------------
MongoInt32::__construct
(PECL mongo >= 1.0.9)
MongoInt32::__construct - Creates a new 32-bit integer.
Description
public MongoInt32::__construct ( string $value )
Creates a new 32-bit number with the given value.
Parameters
value
A number.
Return Values
Returns a new integer.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoInt32::__toString
(PECL mongo >= 1.0.9)
MongoInt32::__toString - Returns the string representation of this 32-bit
integer.
Description
public string MongoInt32::__toString ( void )
Parameters
This function has no parameters.
Return Values
Returns the string representation of this integer.
----------------------------------------------------------------------
Table of Contents
* MongoInt32::__construct - Creates a new 32-bit integer.
* MongoInt32::__toString - Returns the string representation of this
32-bit integer.
----------------------------------------------------------------------
----------------------------------------------------------------------
The MongoInt64 class
Introduction
The class can be used to save 64-bit integers to the database on a 32-bit
system.
Class synopsis
MongoInt64 {
/* Fields */
public string $MongoInt64->value ;
/* Methods */
public MongoInt64::__construct ( string $value )
public string MongoInt64::__toString ( void )
}
Fields
value
This is the string value of the 64-bit number. For instance, 123's
value would be "123".
----------------------------------------------------------------------
MongoInt64::__construct
(PECL mongo >= 1.0.9)
MongoInt64::__construct - Creates a new 64-bit integer.
Description
public MongoInt64::__construct ( string $value )
Creates a new 64-bit number with the given value.
Parameters
value
A number.
Return Values
Returns a new integer.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoInt64::__toString
(PECL mongo >= 1.0.9)
MongoInt64::__toString - Returns the string representation of this 64-bit
integer.
Description
public string MongoInt64::__toString ( void )
Parameters
This function has no parameters.
Return Values
Returns the string representation of this integer.
----------------------------------------------------------------------
Table of Contents
* MongoInt64::__construct - Creates a new 64-bit integer.
* MongoInt64::__toString - Returns the string representation of this
64-bit integer.
----------------------------------------------------------------------
----------------------------------------------------------------------
The MongoDBRef class
Introduction
This class can be used to create lightweight links between objects in
different collections.
Motivation: Suppose we need to refer to a document in another collection.
The easiest way is to create a field in the current document. For example,
if we had a "people" collection and an "addresses" collection, we might
want to create a link between each person document and an address
document:
people;
$addresses = $db->addresses;
$myAddress = array("line 1" => "123 Main Street",
"line 2" => null,
"city" => "Springfield",
"state" => "Vermont",
"country" => "USA");
// save the address
$addresses->insert($myAddress);
// save a person with a reference to the address
$me = array("name" => "Fred", "address" => $myAddress['_id']);
$people->insert($me);
?>
Then, later on, we can find the person's address by querying the
"addresses" collection with the MongoId we saved in the "people"
collection.
Suppose now that we have a more general case, where we don't know which
collection (or even which database) contains the referenced document.
MongoDBRef is a good choice for this case, as it is a common format that
all of the drivers and the database understand.
If each person had a list of things they liked which could come from
multiple collections, such as "hobbies", "sports", "books", etc., we could
use MongoDBRefs to keep track of what "like" went with what collection:
selectCollection("people");
// model trains are in the "hobbies" collection
$trainRef = MongoDBRef::create("hobbies", $modelTrains['_id']);
// soccer is in the "sports" collection
$soccerRef = MongoDBRef::create("sports", $soccer['_id']);
// now we'll know what collections the items in the "likes" array came from when
// we retrieve this document
$people->insert(array("name" => "Fred", "likes" => array($trainRef, $soccerRef)));
?>
Database references can be thought of as hyperlinks: they give the unique
address of another document, but they do not load it or automatically
follow the link/reference.
A database reference is just a normal associative array, not an instance
of MongoDBRef, so this class is a little different than the other data
type classes. This class contains exclusively static methods for
manipulating database references.
Class synopsis
MongoDBRef {
/* Methods */
public static array create ( string $collection , mixed $id [, string
$database ] )
public static array get ( MongoDB $db , array $ref )
public static bool isRef ( mixed $ref )
}
See Also
MongoDB core docs on >> databases references.
----------------------------------------------------------------------
MongoDBRef::create
(PECL mongo >= 0.9.0)
MongoDBRef::create - Creates a new database reference
Description
public static array MongoDBRef::create ( string $collection , mixed $id [,
string $database ] )
If no database is given, the current database is used.
Parameters
collection
Collection name (without the database name).
id
The _id field of the object to which to link.
database
Database name.
Return Values
Returns the reference.
Examples
Example #1 MongoDBRef::create() example
This creates a database reference to a document in the addresses
collection. The MongoCollection::getName() function returns the name of
the collection (not including the database name).
addresses;
$people = $db->people;
// save $address so it has an _id
$addresses->insert($address);
// create a reference
$ref = MongoDBRef::create($addresses->getName(), $address['_id']);
// set the field in $person
$person['address'] = $ref;
$people->save($person);
?>
See Also
* MongoDB::createDBRef() - Creates a database reference
* MongoCollection::createDBRef() - Creates a database reference
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDBRef::get
(PECL mongo >= 0.9.0)
MongoDBRef::get - Fetches the object pointed to by a reference
Description
public static array MongoDBRef::get ( MongoDB $db , array $ref )
Parameters
db
Database to use.
ref
Reference to fetch.
Return Values
Returns the document to which the reference refers or NULL if the document
does not exist (the reference is broken).
Examples
Example #1 MongoCollection::createDBRef() example
findOne();
// dereference the address
$address = MongoDBRef::get($people->db, $person['address']);
?>
See Also
* MongoDB::getDBRef() - Fetches the document pointed to by a database
reference
* MongoCollection::getDBRef() - Fetches the document pointed to by a
database reference
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoDBRef::isRef
(PECL mongo >= 0.9.0)
MongoDBRef::isRef - Checks if an array is a database reference
Description
public static bool MongoDBRef::isRef ( mixed $ref )
This not actually follow the reference, so it does not determine if it is
broken or not. It merely checks that ref is in valid database reference
format (in that it is an object or array with $ref and $id fields).
Parameters
ref
Array or object to check.
Return Values
Returns if ref is a reference.
----------------------------------------------------------------------
Table of Contents
* MongoDBRef::create - Creates a new database reference
* MongoDBRef::get - Fetches the object pointed to by a reference
* MongoDBRef::isRef - Checks if an array is a database reference
----------------------------------------------------------------------
----------------------------------------------------------------------
The MongoMinKey class
Introduction
MongoMinKey is a special type used by the database that evaluates to less
than any other type. Thus, if a query is sorted by a given field in
ascending order, any document with a MongoMinKey as its value will be
returned first.
MongoMinKey has no associated fields, methods, or constants. It is merely
the "smallest" thing that can be inserted into the database.
Class synopsis
MongoMinKey {
}
Using MongoMinKey as a value
insert(array("task" => "lunch", "do by" => new MongoMinKey));
$collection->insert(array("task" => "staff meeting", "do by" => new MongoDate(strtotime("+4 days"))));
$cursor = $collection->find()->sort(array("do by" => 1));
?>
The cursor will contain the lunch document, then the staff meeting
document. The lunch document will always be returned first, regardless of
what else is added to the collection (unless other documents are added
with MongoMinKey in the "do by" field).
----------------------------------------------------------------------
----------------------------------------------------------------------
The MongoMaxKey class
Introduction
MongoMaxKey is a special type used by the database that evaluates to
greater than any other type. Thus, if a query is sorted by a given field
in ascending order, any document with a MongoMaxKey as its value will be
returned last.
MongoMaxKey has no associated fields, methods, or constants. It is merely
the "largest" thing that can be inserted into the database.
Class synopsis
MongoMaxKey {
}
Using MongoMaxKey as a value
insert(array("task" => "dishes", "do by" => new MongoMaxKey));
$collection->insert(array("task" => "staff meeting", "do by" => new MongoDate(strtotime("+4 days"))));
$cursor = $collection->find()->sort(array("do by" => 1));
?>
The cursor will contain the staff meeting document, then the dishes
document. The dishes document will always be returned last, regardless of
what else is added to the collection (unless other documents are added
with MongoMaxKey in the "do by" field).
----------------------------------------------------------------------
----------------------------------------------------------------------
The MongoTimestamp class
Introduction
MongoTimestamp is used by sharding. If you're not looking to write
sharding tools, what you probably want is MongoDate.
MongoTimestamp is 4 bytes of timestamp (seconds since the epoch) and 4
bytes of increment.
This class is not for measuring time, creating a timestamp on a document
or automatically adding or updating a timestamp on a document. Unless you
are writing something that interacts with the sharding internals, stop, go
directly to MongoDate, do not pass go, do not collect 200 dollars. This is
not the class you are looking for.
If you are writing sharding tools, read on.
Class synopsis
MongoTimestamp {
/* Fields */
public int $MongoTimestamp->sec = 0 ;
public int $inc = 0 ;
/* Methods */
MongoTimestamp::__construct ([ int $sec = time() [, int $inc ]] )
public string MongoTimestamp::__toString ( void )
}
----------------------------------------------------------------------
MongoTimestamp::__construct
(PECL mongo >= 1.0.1)
MongoTimestamp::__construct - Creates a new timestamp.
Description
MongoTimestamp::__construct ([ int $sec = time() [, int $inc ]] )
Creates a new timestamp. If no parameters are given, the current time is
used and the increment is automatically provided. The increment is set to
0 when the module is loaded and is incremented every time this constructor
is called (without the $inc parameter passed in).
Parameters
sec
Number of seconds since January 1st, 1970.
inc
Increment.
Return Values
Returns this new timestamp.
See Also
* MongoTimestamp::__toString() - Returns a string representation of this
timestamp
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoTimestamp::__toString
(PECL mongo >= 1.0.1)
MongoTimestamp::__toString - Returns a string representation of this
timestamp
Description
public string MongoTimestamp::__toString ( void )
Returns the "sec" field of this timestamp.
Parameters
This function has no parameters.
Return Values
The seconds since epoch represented by this timestamp.
----------------------------------------------------------------------
Table of Contents
* MongoTimestamp::__construct - Creates a new timestamp.
* MongoTimestamp::__toString - Returns a string representation of this
timestamp
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
GridFS Classes
Table of Contents
* MongoGridFS
* MongoGridFSFile
* MongoGridFSCursor
----------------------------------------------------------------------
The MongoGridFS class
Introduction
Utilities for storing and retrieving files from the database.
GridFS is a storage specification all supported drivers implement.
Basically, it defines two collections: files, for file metadata, and
chunks, for file content. If the file is large, it will automatically be
split into smaller chunks and each chunk will be saved as a document in
the chunks collection.
Each document in the files collection contains the filename, upload date,
and md5 hash. It also contains a unique _id field, which can be used to
query the chunks collection for the file's content. Each document in the
chunks collection contains a chunk of binary data, a files_id field that
matches its file's _id, and the position of this chunk in the overall
file.
For example, the files document is something like:
123456789, "filename" => "foo.txt", "chunkSize" => 3, "length" => 12);
?>
and the chunks documents look like:
123456789, "n" => 0, "data" => new MongoBinData("abc"));
array("files_id" => 123456789, "n" => 1, "data" => new MongoBinData("def"));
array("files_id" => 123456789, "n" => 2, "data" => new MongoBinData("ghi"));
array("files_id" => 123456789, "n" => 3, "data" => new MongoBinData("jkl"));
?>
Of course, the default chunk size is thousands of bytes, but that makes an
unweildy example.
Inter-Language Compatibility
You should be able to use any files created by MongoGridFS with any other
drivers, and visa vera. However, some drivers expect that all metadata
associated with a file be in a "metadata" field. If you're going to be
using other languages, it's a good idea to wrap info you might want them
to see in a "metadata" field. For example, instead of:
storeFile("somefile.txt", array("date" => new MongoDate()));
?>
use something like:
storeFile("somefile.txt", array("metadata" => array("date" => new MongoDate())));
?>
The MongoGridFS Family
MongoGridFS represents the files and chunks collections. MongoGridFS
extends MongoCollection, and an instance of MongoGridFS has access to all
of MongoCollection methods, which act on the files collection:
getGridFS();
$grid->update(array("filename" => "foo"), $newObj); // update on the files collection
?>
Another example of manipulating metadata:
storeFile("game.tgz");
$game = $grid->findOne();
// add a downloads counter
$game->file['downloads'] = 0;
$grid->save($game->file);
// increment the counter
$grid->update(array("_id" => $id), array('$inc' => array("downloads" => 1)));
?>
You can also access the chunks collection from an instance of MongoGridFS:
chunks; // $chunks is a normal MongoCollection
$chunks->insert(array("x" => 4));
?>
There are some methods for MongoGridFS with the same name as
MongoCollection methods, that behave slightly differently. For example,
MongoGridFS::remove() will remove any objects that match the criteria from
the files collection and their content from the chunks collection.
To store something new in GridFS, there are a couple options. If you have
a filename, you can say:
storeFile($filename, array("whatever" => "metadata", "you" => "want"));
?>
If you have a string of bytes that isn't a file, you can also store that
using MongoGridFS::storeBytes():
storeBytes($bytes, array("whatever" => "metadata", "you" => "want"));
?>
Querying a MongoGridFS collection returns a MongoGridFSCursor, which
behaves like a normal MongoCursor except that it returns MongoGridFSFiles
instead of associative arrays.
MongoGridFSFiles can be written back to disc using
MongoGridFSFile::write() or retrieved in memory using
MongoGridFSFile::getBytes(). There is currently no method that
automatically streams chunks, but it would be fairly easy to write by
querying the $grid->chunks collection.
MongoGridFSFile objects contain a field file which contains any file
metadata.
Class synopsis
extends MongoCollection {
/* Fields */
public MongoCollection $MongoGridFS->chunks = NULL ;
protected string $filesName = NULL ;
protected string $chunksName = NULL ;
/* Methods */
MongoGridFS::__construct ( MongoDB $db [, string $prefix = "fs" [, mixed
$chunks = "fs" ]] )
public bool MongoGridFS::delete ( mixed $id )
public array MongoGridFS::drop ( void )
public MongoGridFSCursor MongoGridFS::find ([ array $query = array() [,
array $fields = array() ]] )
public MongoGridFSFile MongoGridFS::findOne ([ mixed $query = array() [,
mixed $fields = array() ]] )
public MongoGridFSFile MongoGridFS::get ( mixed $id )
public mixed MongoGridFS::put ( string $filename [, array $extra = array()
] )
public bool MongoGridFS::remove ([ array $criteria = array() [, array
$options = array() ]] )
public mixed MongoGridFS::storeBytes ( string $bytes [, array $extra =
array() [, array $options = array() ]] )
public mixed MongoGridFS::storeFile ( string $filename [, array $extra =
array() [, array $options = array() ]] )
public mixed MongoGridFS::storeUpload ( string $name [, string $filename ]
)
}
See Also
MongoDB core docs on >> GridFS. There's also a nice intro to >> saving
user uploads and >> adding metadata at LightCubeSolutions.com.
----------------------------------------------------------------------
MongoGridFS::__construct
(PECL mongo >=0.9.0)
MongoGridFS::__construct - Creates new file collections
Description
MongoGridFS::__construct ( MongoDB $db [, string $prefix = "fs" [, mixed
$chunks = "fs" ]] )
Files as stored across two collections, the first containing file meta
information, the second containing chunks of the actual file. By default,
fs.files and fs.chunks are the collection names used.
Use one argument to specify a prefix other than "fs":
$fs = new MongoGridFS($db, "myfiles");
uses myfiles.files and myfiles.chunks collections.
Parameters
db
Database.
files
Optional collection name prefix.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoGridFS::delete
(PECL mongo >=1.0.8)
MongoGridFS::delete - Delete a file from the database
Description
public bool MongoGridFS::delete ( mixed $id )
Parameters
id
_id of the file to remove.
Return Values
Returns if the remove was successfully sent to the database.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoGridFS::drop
(PECL mongo >=0.9.0)
MongoGridFS::drop - Drops the files and chunks collections
Description
public array MongoGridFS::drop ( void )
Parameters
This function has no parameters.
Return Values
The database response.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoGridFS::find
(PECL mongo >=0.9.0)
MongoGridFS::find - Queries for files
Description
public MongoGridFSCursor MongoGridFS::find ([ array $query = array() [,
array $fields = array() ]] )
Parameters
query
The query.
fields
Fields to return.
Return Values
A MongoGridFSCursor.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoGridFS::findOne
(PECL mongo >=0.9.0)
MongoGridFS::findOne - Returns a single file matching the criteria
Description
public MongoGridFSFile MongoGridFS::findOne ([ mixed $query = array() [,
mixed $fields = array() ]] )
Parameters
query
The filename or criteria for which to search.
Return Values
Returns a MongoGridFSFile or NULL.
Examples
Example #1 MongoGridFS::findOne() example
Example demonstrating how to find a single file from the MongoGridFS.
my_db->getGridFS('downloads');
$downloads->storeFile('filename.tgz');
$download = $downloads->findOne('filename.tgz'); // instance of MongoGridFSFile
print_r($download);
?>
See MongoGridFSFile for more information about how to work with files.
The above example will output something similar to:
MongoGridFSFile Object
(
[file] => Array
(
[_id] => MongoId Object
(
)
[filename] => filename.tgz
[uploadDate] => MongoDate Object
(
[sec] => 1274288014
[usec] => 467000
)
[chunkSize] => 262144
[md5] => d41d8cd98f00b204e9800998ecf8427e
)
[gridfs:protected] => MongoGridFS Object
(
[chunks] => MongoCollection Object
(
)
[filesName:protected] => downloads.files
[chunksName:protected] => downloads.chunks
)
)
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoGridFS::get
(PECL mongo >=1.0.8)
MongoGridFS::get - Retrieve a file from the database
Description
public MongoGridFSFile MongoGridFS::get ( mixed $id )
Parameters
id
_id of the file to find.
Return Values
Returns the file, if found, or NULL.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoGridFS::put
(PECL mongo >=1.0.8)
MongoGridFS::put - Stores a file in the database
Description
public mixed MongoGridFS::put ( string $filename [, array $extra = array()
] )
Parameters
filename
The name of the file.
extra
Other metadata to add to the file saved.
Return Values
Returns the _id of the saved object.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoGridFS::remove
(PECL mongo >=0.9.0)
MongoGridFS::remove - Removes files from the collections
Description
public bool MongoGridFS::remove ([ array $criteria = array() [, array
$options = array() ]] )
Parameters
query
The filename or criteria for which to search.
options
Options for the remove. Valid options are:
* "safe"
Check that the remove succeeded.
Return Values
Returns if the removal was successfully sent to the database.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoGridFS::storeBytes
(PECL mongo >=0.9.2)
MongoGridFS::storeBytes - Chunkifies and stores bytes in the database
Description
public mixed MongoGridFS::storeBytes ( string $bytes [, array $extra =
array() [, array $options = array() ]] )
Parameters
bytes
A string of bytes to store.
extra
Other metadata to add to the file saved.
options
Options for the store.
* "safe"
Check that this store succeeded.
Return Values
The _id of the object saved.
Errors/Exceptions
Throws MongoCursorException if the "safe" option is set and the insert
fails.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoGridFS::storeFile
(PECL mongo >=0.9.0)
MongoGridFS::storeFile - Stores a file in the database
Description
public mixed MongoGridFS::storeFile ( string $filename [, array $extra =
array() [, array $options = array() ]] )
Parameters
filename
The name of the file.
extra
Other metadata to add to the file saved.
options
Options for the store.
* "safe"
Check that this store succeeded.
Return Values
Returns the _id of the saved object.
Errors/Exceptions
Throws MongoCursorException if the "safe" option is set and the insert
fails.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoGridFS::storeUpload
(PECL mongo >=0.9.0)
MongoGridFS::storeUpload - Saves an uploaded file to the database
Description
public mixed MongoGridFS::storeUpload ( string $name [, string $filename ]
)
Parameters
name
The name field of the uploaded file.
filename
String to be used as filename field in the database.
Return Values
Returns the _id of the uploaded file.
----------------------------------------------------------------------
Table of Contents
* MongoGridFS::__construct - Creates new file collections
* MongoGridFS::delete - Delete a file from the database
* MongoGridFS::drop - Drops the files and chunks collections
* MongoGridFS::find - Queries for files
* MongoGridFS::findOne - Returns a single file matching the criteria
* MongoGridFS::get - Retrieve a file from the database
* MongoGridFS::put - Stores a file in the database
* MongoGridFS::remove - Removes files from the collections
* MongoGridFS::storeBytes - Chunkifies and stores bytes in the database
* MongoGridFS::storeFile - Stores a file in the database
* MongoGridFS::storeUpload - Saves an uploaded file to the database
----------------------------------------------------------------------
----------------------------------------------------------------------
The MongoGridFSFile class
Introduction
A database file object.
Class synopsis
MongoGridFSFile {
/* Fields */
public array $MongoGridFSFile->file = NULL ;
protected MongoGridFS $gridfs = NULL ;
/* Methods */
MongoGridfsFile::__construct ( MongoGridFS $gridfs , array $file )
public string MongoGridFSFile::getBytes ( void )
public string MongoGridFSFile::getFilename ( void )
public int MongoGridFSFile::getSize ( void )
public int MongoGridFSFile::write ([ string $filename = NULL ] )
}
----------------------------------------------------------------------
MongoGridfsFile::__construct
(PECL mongo >=0.9.0)
MongoGridfsFile::__construct - Create a new GridFS file
Description
MongoGridfsFile::__construct ( MongoGridFS $gridfs , array $file )
Parameters
gridfs
The parent MongoGridFS instance.
file
A file from the database.
Return Values
Returns a new MongoGridFSFile.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoGridFSFile::getBytes
(PECL mongo >=0.9.0)
MongoGridFSFile::getBytes - Returns this file's contents as a string of
bytes
Description
public string MongoGridFSFile::getBytes ( void )
Warning: this will load the file into memory. If the file is bigger than
your memory, this will cause problems!
Parameters
This function has no parameters.
Return Values
Returns a string of the bytes in the file.
Examples
Example #1 MongoGridFSFile::getBytes() example
my_db->getGridFS('images');
$image = $images->findOne('jwage.png');
header('Content-type: image/png;');
echo $image->getBytes();
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoGridFSFile::getFilename
(PECL mongo >=0.9.0)
MongoGridFSFile::getFilename - Returns this file's filename
Description
public string MongoGridFSFile::getFilename ( void )
Parameters
This function has no parameters.
Return Values
Returns the filename.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoGridFSFile::getSize
(PECL mongo >=0.9.0)
MongoGridFSFile::getSize - Returns this file's size
Description
public int MongoGridFSFile::getSize ( void )
Parameters
This function has no parameters.
Return Values
Returns this file's size
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoGridFSFile::write
(PECL mongo >=0.9.0)
MongoGridFSFile::write - Writes this file to the filesystem
Description
public int MongoGridFSFile::write ([ string $filename = NULL ] )
Parameters
filename
The location to which to write the file. If none is given, the
stored filename will be used.
Return Values
Returns the number of bytes written.
Examples
Example #1 MongoGridFSFile::write() example
my_db->getGridFS('images');
$image = $images->findOne('jwage.png');
$image->write('/path/to/write/jwage.png');
?>
----------------------------------------------------------------------
Table of Contents
* MongoGridfsFile::__construct - Create a new GridFS file
* MongoGridFSFile::getBytes - Returns this file's contents as a string
of bytes
* MongoGridFSFile::getFilename - Returns this file's filename
* MongoGridFSFile::getSize - Returns this file's size
* MongoGridFSFile::write - Writes this file to the filesystem
----------------------------------------------------------------------
----------------------------------------------------------------------
The MongoGridFSCursor class
Introduction
Cursor for database file results.
Class synopsis
extends MongoCursor {
/* Fields */
protected MongoGridFS $MongoGridFSCursor->gridfs = NULL ;
/* Methods */
MongoGridFSCursor::__construct ( MongoGridFS $gridfs , resource
$connection , string $ns , array $query , array $fields )
public MongoGridFSFile MongoGridFSCursor::current ( void )
public MongoGridFSFile MongoGridFSCursor::getNext ( void )
public string MongoGridFSCursor::key ( void )
}
----------------------------------------------------------------------
MongoGridFSCursor::__construct
(PECL mongo >=0.9.0)
MongoGridFSCursor::__construct - Create a new cursor
Description
MongoGridFSCursor::__construct ( MongoGridFS $gridfs , resource
$connection , string $ns , array $query , array $fields )
Parameters
gridfs
Related GridFS collection.
connection
Database connection.
ns
Full name of database and collection.
query
Database query.
fields
Fields to return.
Return Values
Returns the new cursor.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoGridFSCursor::current
(PECL mongo >=0.9.0)
MongoGridFSCursor::current - Returns the current file
Description
public MongoGridFSFile MongoGridFSCursor::current ( void )
Parameters
This function has no parameters.
Return Values
The current file.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoGridFSCursor::getNext
(PECL mongo >=0.9.0)
MongoGridFSCursor::getNext - Return the next file to which this cursor
points, and advance the cursor
Description
public MongoGridFSFile MongoGridFSCursor::getNext ( void )
Parameters
This function has no parameters.
Return Values
Returns the next file.
----------------------------------------------------------------------
----------------------------------------------------------------------
MongoGridFSCursor::key
(PECL mongo >=0.9.0)
MongoGridFSCursor::key - Returns the current result's filename
Description
public string MongoGridFSCursor::key ( void )
Parameters
This function has no parameters.
Return Values
The current result's filename.
----------------------------------------------------------------------
Table of Contents
* MongoGridFSCursor::__construct - Create a new cursor
* MongoGridFSCursor::current - Returns the current file
* MongoGridFSCursor::getNext - Return the next file to which this cursor
points, and advance the cursor
* MongoGridFSCursor::key - Returns the current result's filename
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Functions
Table of Contents
* Mongo Functions
----------------------------------------------------------------------
Mongo Functions
----------------------------------------------------------------------
bson_decode
(PECL mongo >=1.0.1)
bson_decode - Deserializes a BSON object into a PHP array
Description
array bson_decode ( string $bson )
This function is very beta and entirely useless for 99% of users. It is
only useful if you're doing something weird, such as writing your own
driver on top of the PHP driver.
Parameters
bson
The BSON to be deserialized.
Return Values
Returns the deserialized BSON object.
----------------------------------------------------------------------
----------------------------------------------------------------------
bson_encode
(PECL mongo >=1.0.1)
bson_encode - Serializes a PHP variable into a BSON string
Description
string bson_encode ( mixed $anything )
This function is very beta and entirely useless for 99% of users. It is
only useful if you're doing something weird, such as writing your own
driver on top of the PHP driver.
Parameters
anything
The variable to be serialized.
Return Values
Returns the serialized string.
----------------------------------------------------------------------
Table of Contents
* bson_decode - Deserializes a BSON object into a PHP array
* bson_encode - Serializes a PHP variable into a BSON string
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Exceptions
Table of Contents
* MongoException
* MongoCursorException
* MongoCursorTimeoutException
* MongoConnectionException
* MongoGridFSException
VMWare Oddities
If you are running VMWare on Windows and are using CIFS, pausing the VM
will cause CIFS to go out of sync and cause weird errors on un-pausing it
("The Mongo object has not been correctly initialized by its
constructor"). Permanently mounting the Windows shares will fix this and
you'll be able to pause and unpause at will.
To permanently mount the Windows shares, run:
$ sudo update-rc.d -f umountnfs.sh remove
$ sudo update-rc.d umountnfs.sh stop 15 0 6 .
See >> the Ubuntu docs for the most up-to-date instructions.
----------------------------------------------------------------------
The MongoException class
Introduction
Default Mongo exception.
This covers a bunch of different error conditions that may eventually be
moved to more specific exceptions, but will always extend MongoException.
* The MongoSomething object has not been correctly initialized by its
constructor
Code: 0
Probably your Mongo object is not connected to a database server.
* zero-length keys are not allowed, did you use $ with double quotes?
Code: 1
You tried to save "" as a key. You generally should not do this. ""
can mess up subobject access and is used by MongoDB internally.
However, if you really want, you can set mongo.allow_empty_keys to
true in your php.ini file to override this sanity check. If you
override this, it is highly recommended that you set error checking to
strict to avoid string interpolation errors.
* '.' not allowed in key:
Code: 2
You attempted to write a key with '.' in it, which is prohibited.
* insert too large: , max:
Code: 3
You're attempting to send too much data to the database at once: the
database will only accept inserts up to a certain size (currently 16
MB).
* no elements in doc
Code: 4
You're attempting to save a document with no fields.
* size of BSON doc is bytes, max MB
Code: 5
You're attempting to save a document that is larger than MongoDB can
save.
* no documents given
Code: 6
You're attempting to batch insert an empty array of documents.
* MongoCollection::group takes an array, object, or MongoCode key
Code: 7
Wrong type parameter send to MongoCollection::group().
* field names must be strings
Code: 8
You should format field selectors as array("field1" => 1, "field2" =>
1, ..., "fieldN" => 1).
* invalid regex
Code: 8
The regex passed to MongoRegex is not of the correct form.
* MongoDBRef::get: $ref field must be a string
Code: 10
* MongoDBRef::get: $db field must be a string
Code: 11
* non-utf8 string:
Code: 12
This error occurs if you attempt to send a non-utf8 string to the
database. All strings going into the database should be UTF8. See
php.ini options for the transition option of quieting this exception.
* mutex error:
Code: 13
The driver uses mutexes for synchronizing requests and responses in
multithreaded environments. This is a fairly serious error and may not
have a stack trace. It's unusual and should be reported to maintainers
with any system information and steps to reproduce that you can
provide.
* index name too long: , max characters
Code: 14
Indexes with names longer than 128 characters cannot be created. If
you get this error, you should use MongoCollection::ensureIndex()'s
"name" option to create a shorter name for your index.
Class synopsis
extends Exception {
}
----------------------------------------------------------------------
----------------------------------------------------------------------
The MongoCursorException class
Introduction
Caused by accessing a cursor incorrectly or a error receiving a reply.
If there is an error receiving a reply, there will be a more specific
error message to help diagnose the problem. As it is a bit
programmatically awkward to parse an exception message, there is also an
error code associated with each cause of the exception.
* cannot modify cursor after beginning iteration
Code: 0
You are calling a method that sets up the query after executing the
query. Reset the cursor and try again.
* Get next batch send errors
Code: 1
Could not send the query to the database. Make sure the database is
still up and the network is okay.
* cursor not found
Code: 2
The driver was trying to fetch more results from the database, but the
database did not have a record of the query. This usually means that
the cursor timed out on the server side: after a few minutes of
inactivity, the database will kill a cursor (see
MongoCursor::immortal() for information on preventing this).
* Couldn't get response header.
Code: 4
* cursor->buf.pos is null
Code: 3
This may indicate you are out of hard driver space or some other
extraordinary circumstance.
* couldn't get response header
Code: 4
The driver could not fetch a reply header from the database, so it
gave up. Check if the database is still up and the network is
connected and try the query again.
* no db response
Code: 5
This may not even be an error, for example, the database command
"shutdown" returns no response. However, if you were expecting a
response, this means the database didn't give one.
* bad response length: %d, max: %d, did the db assert?
Code: 6
This means that the database said that its response was greater than
4Mb or less than 0. Generally, a number greater than 5Mb should be
reported to the developers as a potential database bug (max response
length is 4Mb). A response of less than 0 often means a database
assertion occured.
* incomplete header
Code: 7
Highly unusual. Occurs if the database response started out correctly,
but broke off in the middle. Probably indicates a network problem.
* incomplete response
Code: 8
Highly unusual. Occurs if the database response started out correctly,
but broke off in the middle. Probably indicates a network problem.
* couldn't find a response
Code: 9
If the response was cached and now cannot be located.
* error getting socket
Code: 10
The socket was closed or encountered an error. The driver should
automatically reconnect (if possible) on the next operation.
* couldn't find reply, please try again
Code: 11
The driver saves any database responses it cannot immediately match
with a request. This exception occurs if the driver has already passed
your request's response and cannot find your response in its cache.
* error getting database response: errstr
WSA error getting database response: errstr
"errstr" is an io error reported directly from the C socket subsystem.
On Windows, the error message is prefixed with "WSA".
* Timeout error
Code: 13
If there was an error while waiting for a query to complete.
* couldn't send query:
Code: 14
C socket error on send.
Errors passed through by the database
Database errors should always trigger MongoCursorExceptions on queries.
Error messages and codes are sent directly from the database and you
should be able to see matching errors in the database log.
A few common database errors are listed below:
* E11000 duplicate key error index: foo.bar.$X dup key: { /* ... */ }
Code: 11000
Database error for duplicate keys.
* not master
Codes: 10107, 13435, and 10058
Not master errors, piped through by the database. Each of these will
cause the driver to disconnect and attempt to find a new master. The
actual error you get on failover may not be a "not master" error,
depending on when the change in master occurs.
Class synopsis
extends MongoException {
}
----------------------------------------------------------------------
----------------------------------------------------------------------
The MongoCursorTimeoutException class
Introduction
Caused by a query timing out. You can set the length of time to wait
before this exception is thrown by calling MongoCursor::timeout() on the
cursor or setting MongoCursor::$timeout. The static variable is useful for
queries such as database commands and MongoCollection::findOne(), both of
which implicitly use cursors.
Class synopsis
extends MongoCursorException {
}
----------------------------------------------------------------------
----------------------------------------------------------------------
The MongoConnectionException class
Introduction
Thrown when the driver fails to connect to the database.
There are a number of possible error messages to help you diagnose the
connection problem. These are:
* No server name given.
This error occurs if you pass in "" as the server name, probably
because of an typo with string interpolation, e.g., "$servr" instead
of "$server".
* failed to get host [hostname] or port [portnum] from [server].
This indicated that the server string was malformed. "[hostname]" and
"[portnum]" will be as much as the driver could dicipher of it.
* Operation in progress
Connecting to the database timed out.
* Transport endpoint is not connected
Generally means that the connection string isn't correct, the driver
couldn't even find the database server.
* couldn't determine master
Neither server in a paired connection appeared to be master.
* couldn't get host info for [server]
This indicated that DNS could not resolve the server address you gave.
This could easily be caused by a typo, for example, "server" instead
of "$server".
* Invalid Argument
This can be caused by attempting to connect to a machine that is up
but that the database isn't actually running on. Make sure that you've
started the database server before connecting.
* Permission denied
This means that the socket could not be opened due to permissions
issues. On Red Hat variants, this can be caused by a default setting
that does not allow Apache to create network connections. You can
override this setting by running:
$ /usr/sbin/setsebool -P httpd_can_network_connect 1
then restarting Apache.
If the error message is not listed above, it is probably an error from the
C socket, and you can search the web for its usual cause.
Class synopsis
extends MongoException {
}
----------------------------------------------------------------------
----------------------------------------------------------------------
The MongoGridFSException class
Introduction
Thrown when there are errors reading or writing files to or from the
database.
Class synopsis
extends MongoException {
}
----------------------------------------------------------------------
----------------------------------------------------------------------
* Manual
* Installation
* Tutorial
* SQL to Mongo Mapping Chart
* Connecting
* Writes
* Querying
* Updates
* php.ini Options
* Security
* Running the Driver's Tests
* Troubleshooting
* Core Classes
* Mongo - The Mongo class
* MongoDB - The MongoDB class
* MongoCollection - The MongoCollection class
* MongoCursor - The MongoCursor class
* Types
* MongoId - The MongoId class
* MongoCode - The MongoCode class
* MongoDate - The MongoDate class
* MongoRegex - The MongoRegex class
* MongoBinData - The MongoBinData class
* MongoInt32 - The MongoInt32 class
* MongoInt64 - The MongoInt64 class
* MongoDBRef - The MongoDBRef class
* MongoMinKey - The MongoMinKey class
* MongoMaxKey - The MongoMaxKey class
* MongoTimestamp - The MongoTimestamp class
* GridFS Classes
* MongoGridFS - The MongoGridFS class
* MongoGridFSFile - The MongoGridFSFile class
* MongoGridFSCursor - The MongoGridFSCursor class
* Functions
* Mongo Functions
* Exceptions
* MongoException - The MongoException class
* MongoCursorException - The MongoCursorException class
* MongoCursorTimeoutException - The MongoCursorTimeoutException
class
* MongoConnectionException - The MongoConnectionException class
* MongoGridFSException - The MongoGridFSException class
----------------------------------------------------------------------
----------------------------------------------------------------------
mSQL
----------------------------------------------------------------------
Introduction
These functions allow you to access mSQL database servers. More
information about mSQL can be found at >> http://www.hughes.com.au/.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
In order to have these functions available, you must compile PHP with msql
support by using the --with-msql[=DIR] option. DIR is the mSQL base
install directory, defaults to /usr/local/msql3.
Note: Note to Win32 Users
In order for this extension to work, there are DLL files that must be
available to the Windows system PATH. For information on how to do this,
see the FAQ entitled "How do I add my PHP directory to the PATH on
Windows". Although copying DLL files from the PHP folder into the
Windows system directory also works (because the system directory is by
default in the system's PATH), this is not recommended. This extension
requires the following files to be in the PATH: msql.dll
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
mSQL configuration options
Name Default Changeable Changelog
msql.allow_persistent "1" PHP_INI_ALL
msql.max_persistent "-1" PHP_INI_ALL
msql.max_links "-1" PHP_INI_ALL
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
msql.allow_persistent boolean
Whether to allow persistent mSQL connections.
msql.max_persistent integer
The maximum number of persistent mSQL connections per process.
msql.max_links integer
The maximum number of mSQL connections per process, including
persistent connections.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
There are two resource types used in the mSQL module. The first one is the
link identifier for a database connection, the second a resource which
holds the result of a query.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
MSQL_ASSOC (integer)
MSQL_NUM (integer)
MSQL_BOTH (integer)
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Table of Contents
* Basic usage
----------------------------------------------------------------------
Basic usage
This simple example shows how to connect, execute a query, print resulting
rows and disconnect from a mSQL database.
Example #1 mSQL usage example
\n";
while ($row = msql_fetch_array($result, MSQL_ASSOC)) {
echo "\t\n";
foreach ($row as $col_value) {
echo "\t\t$col_value \n";
}
echo "\t \n";
}
echo "
\n";
/* Free result set */
msql_free_result($result);
/* Close connection */
msql_close($link);
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
mSQL Functions
----------------------------------------------------------------------
msql_affected_rows
(PHP 4, PHP 5)
msql_affected_rows - Returns number of affected rows
Description
int msql_affected_rows ( resource $result )
Returns number of affected rows by the last SELECT, UPDATE or DELETE query
associated with result.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to msql_query().
Return Values
Returns the number of affected rows on success, or FALSE on error.
See Also
* msql_query() - Send mSQL query
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_close
(PHP 4, PHP 5)
msql_close - Close mSQL connection
Description
bool msql_close ([ resource $link_identifier ] )
msql_close() closes the non-persistent connection to the mSQL server
that's associated with the specified link identifier.
Using msql_close() isn't usually necessary, as non-persistent open links
are automatically closed at the end of the script's execution. See also
freeing resources.
Parameters
link_identifier
The mSQL connection. If not specified, the last link opened by
msql_connect() is assumed. If no such link is found, the function
will try to establish a link as if msql_connect() was called, and
use it.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* msql_connect() - Open mSQL connection
* msql_pconnect() - Open persistent mSQL connection
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_connect
(PHP 4, PHP 5)
msql_connect - Open mSQL connection
Description
resource msql_connect ([ string $hostname ] )
msql_connect() establishes a connection to a mSQL server.
In case a second call is made to msql_connect() with the same arguments,
no new link will be established, but instead, the link identifier of the
already opened link will be returned.
The link to the server will be closed as soon as the execution of the
script ends, unless it's closed earlier by explicitly calling
msql_close().
Parameters
hostname
The hostname can also include a port number. e.g. hostname,port.
If not specified, the connection is established by the means of a
Unix domain socket, being then more efficient then a localhost TCP
socket connection.
Note:
While this function will accept a colon (:) as a host/port
separator, a comma (,) is the preferred method.
Return Values
Returns a positive mSQL link identifier on success, or FALSE on error.
See Also
* msql_pconnect() - Open persistent mSQL connection
* msql_close() - Close mSQL connection
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_create_db
(PHP 4, PHP 5)
msql_create_db - Create mSQL database
Description
bool msql_create_db ( string $database_name [, resource $link_identifier ]
)
msql_create_db() attempts to create a new database on the mSQL server.
Parameters
database_name
The name of the mSQL database.
link_identifier
The mSQL connection. If not specified, the last link opened by
msql_connect() is assumed. If no such link is found, the function
will try to establish a link as if msql_connect() was called, and
use it.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* msql_drop_db() - Drop (delete) mSQL database
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_createdb
(PHP 4, PHP 5)
msql_createdb - Alias of msql_create_db()
Description
This function is an alias of: msql_create_db().
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_data_seek
(PHP 4, PHP 5)
msql_data_seek - Move internal row pointer
Description
bool msql_data_seek ( resource $result , int $row_number )
msql_data_seek() moves the internal row pointer of the mSQL result
associated with the specified query identifier to point to the specified
row number. The next call to msql_fetch_row() would return that row.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to msql_query().
row_number
The seeked row number.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* msql_fetch_array() - Fetch row as array
* msql_fetch_object() - Fetch row as object
* msql_fetch_row() - Get row as enumerated array
* msql_result() - Get result data
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_db_query
(PHP 4, PHP 5)
msql_db_query - Send mSQL query
Description
resource msql_db_query ( string $database , string $query [, resource
$link_identifier ] )
msql_db_query() selects a database and executes a query on it.
Parameters
database
The name of the mSQL database.
query
The SQL query.
link_identifier
The mSQL connection. If not specified, the last link opened by
msql_connect() is assumed. If no such link is found, the function
will try to establish a link as if msql_connect() was called, and
use it.
Return Values
Returns a positive mSQL query identifier to the query result, or FALSE on
error.
See Also
* msql_query() - Send mSQL query
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_dbname
(PHP 4, PHP 5)
msql_dbname - Alias of msql_result()
Description
This function is an alias of: msql_result().
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_drop_db
(PHP 4, PHP 5)
msql_drop_db - Drop (delete) mSQL database
Description
bool msql_drop_db ( string $database_name [, resource $link_identifier ] )
msql_drop_db() attempts to drop (remove) a database from the mSQL server.
Parameters
database_name
The name of the database.
link_identifier
The mSQL connection. If not specified, the last link opened by
msql_connect() is assumed. If no such link is found, the function
will try to establish a link as if msql_connect() was called, and
use it.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* msql_create_db() - Create mSQL database
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_error
(PHP 4, PHP 5)
msql_error - Returns error message of last msql call
Description
string msql_error ( void )
msql_error() returns the last issued error by the mSQL server. Note that
only the last error message is accessible with msql_error().
Return Values
The last error message or an empty string if no error was issued.
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_fetch_array
(PHP 4, PHP 5)
msql_fetch_array - Fetch row as array
Description
array msql_fetch_array ( resource $result [, int $result_type ] )
msql_fetch_array() is an extended version of msql_fetch_row(). In addition
to storing the data in the numeric indices of the result array, it also
stores the data in associative indices, using the field names as keys.
An important thing to note is that using msql_fetch_array() is NOT
significantly slower than using msql_fetch_row(), while it provides a
significant added value.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to msql_query().
result_type
A constant that can take the following values: MSQL_ASSOC,
MSQL_NUM, and MSQL_BOTH with MSQL_BOTH being the default.
Return Values
Returns an array that corresponds to the fetched row, or FALSE if there
are no more rows.
Examples
Example #1 msql_fetch_array() example
Changelog
Version Description
A bug was fixed when retrieving data from columns
4.3.11 and 5.0.4 containing NULL values. Such columns were not placed into
the resulting array.
See Also
* msql_fetch_row() - Get row as enumerated array
* msql_fetch_object() - Fetch row as object
* msql_data_seek() - Move internal row pointer
* msql_result() - Get result data
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_fetch_field
(PHP 4, PHP 5)
msql_fetch_field - Get field information
Description
object msql_fetch_field ( resource $result [, int $field_offset = 0 ] )
msql_fetch_field() can be used in order to obtain information about fields
in a certain query result.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to msql_query().
field_offset
The field offset. If not specified, the next field that wasn't yet
retrieved by msql_fetch_field() is retrieved.
Return Values
Returns an object containing field information. The properties of the
object are:
* name - column name
* table - name of the table the column belongs to
* not_null - 1 if the column cannot be NULL
* unique - 1 if the column is a unique key
* type - the type of the column
See Also
* msql_field_seek() - Set field offset
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_fetch_object
(PHP 4, PHP 5)
msql_fetch_object - Fetch row as object
Description
object msql_fetch_object ( resource $result )
msql_fetch_object() is similar to msql_fetch_array(), with one difference
- an object is returned, instead of an array. Indirectly, that means that
you can only access the data by the field names, and not by their offsets
(numbers are illegal property names).
Speed-wise, the function is identical to msql_fetch_array(), and almost as
quick as msql_fetch_row() (the difference is insignificant).
Parameters
result
The result resource that is being evaluated. This result comes
from a call to msql_query().
Return Values
Returns an object with properties that correspond to the fetched row, or
FALSE if there are no more rows.
Examples
Example #1 msql_fetch_object() example
id . ': ' . $row->name . "\n";
}
msql_free_result($result);
?>
Changelog
Version Description
A bug was fixed when retrieving data from columns
4.3.11 and 5.0.4 containing NULL values. Such columns were not placed into
the resulting array.
See Also
* msql_fetch_array() - Fetch row as array
* msql_fetch_row() - Get row as enumerated array
* msql_data_seek() - Move internal row pointer
* msql_result() - Get result data
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_fetch_row
(PHP 4, PHP 5)
msql_fetch_row - Get row as enumerated array
Description
array msql_fetch_row ( resource $result )
msql_fetch_row() fetches one row of data from the result associated with
the specified query identifier. The row is returned as an array. Each
result column is stored in an array offset, starting at offset 0.
Subsequent call to msql_fetch_row() would return the next row in the
result set, or FALSE if there are no more rows.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to msql_query().
Return Values
Returns an array that corresponds to the fetched row, or FALSE if there
are no more rows.
Examples
Example #1 msql_fetch_row() example
Changelog
Version Description
A bug was fixed when retrieving data from columns
4.3.11 and 5.0.4 containing NULL values. Such columns were not placed into
the resulting array.
See Also
* msql_fetch_array() - Fetch row as array
* msql_fetch_object() - Fetch row as object
* msql_data_seek() - Move internal row pointer
* msql_result() - Get result data
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_field_flags
(PHP 4, PHP 5)
msql_field_flags - Get field flags
Description
string msql_field_flags ( resource $result , int $field_offset )
msql_field_flags() returns the field flags of the specified field.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to msql_query().
field_offset
The numerical field offset. The field_offset starts at 1.
Return Values
Returns a string containing the field flags of the specified key. This can
be: primary key not null, not null, primary key, unique not null or
unique.
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_field_len
(PHP 4, PHP 5)
msql_field_len - Get field length
Description
int msql_field_len ( resource $result , int $field_offset )
msql_field_len() returns the length of the specified field.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to msql_query().
field_offset
The numerical field offset. The field_offset starts at 1.
Return Values
Returns the length of the specified field or FALSE on error.
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_field_name
(PHP 4, PHP 5)
msql_field_name - Get the name of the specified field in a result
Description
string msql_field_name ( resource $result , int $field_offset )
msql_field_name() gets the name of the specified field index.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to msql_query().
field_offset
The numerical field offset. The field_offset starts at 1.
Return Values
The name of the field or FALSE on failure.
See Also
* msql_field_len() - Get field length
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_field_seek
(PHP 4, PHP 5)
msql_field_seek - Set field offset
Description
bool msql_field_seek ( resource $result , int $field_offset )
Seeks to the specified field offset. If the next call to
msql_fetch_field() won't include a field offset, this field would be
returned.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to msql_query().
field_offset
The numerical field offset. The field_offset starts at 1.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* msql_fetch_field() - Get field information
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_field_table
(PHP 4, PHP 5)
msql_field_table - Get table name for field
Description
int msql_field_table ( resource $result , int $field_offset )
Returns the name of the table that the specified field is in.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to msql_query().
field_offset
The numerical field offset. The field_offset starts at 1.
Return Values
The name of the table on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_field_type
(PHP 4, PHP 5)
msql_field_type - Get field type
Description
string msql_field_type ( resource $result , int $field_offset )
msql_field_type() gets the type of the specified field index.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to msql_query().
field_offset
The numerical field offset. The field_offset starts at 1.
Return Values
The type of the field. One of int, char, real, ident, null or unknown.
This functions will return FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_fieldflags
(PHP 4, PHP 5)
msql_fieldflags - Alias of msql_field_flags()
Description
This function is an alias of msql_field_flags().
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_fieldlen
(PHP 4, PHP 5)
msql_fieldlen - Alias of msql_field_len()
Description
This function is an alias of msql_field_len().
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_fieldname
(PHP 4, PHP 5)
msql_fieldname - Alias of msql_field_name()
Description
This function is an alias of msql_field_name().
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_fieldtable
(PHP 4, PHP 5)
msql_fieldtable - Alias of msql_field_table()
Description
This function is an alias of msql_field_table().
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_fieldtype
(PHP 4, PHP 5)
msql_fieldtype - Alias of msql_field_type()
Description
This function is an alias of msql_field_type().
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_free_result
(PHP 4, PHP 5)
msql_free_result - Free result memory
Description
bool msql_free_result ( resource $result )
msql_free_result() frees the memory associated with query_identifier. When
PHP completes a request, this memory is freed automatically, so you only
need to call this function when you want to make sure you don't use too
much memory while the script is running.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to msql_query().
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_list_dbs
(PHP 4, PHP 5)
msql_list_dbs - List mSQL databases on server
Description
resource msql_list_dbs ([ resource $link_identifier ] )
msql_list_tables() lists the databases available on the specified
link_identifier.
Parameters
link_identifier
The mSQL connection. If not specified, the last link opened by
msql_connect() is assumed. If no such link is found, the function
will try to establish a link as if msql_connect() was called, and
use it.
Return Values
Returns a result set which may be traversed with any function that fetches
result sets, such as msql_fetch_array(). On failure, this function will
return FALSE.
See Also
* msql_list_tables() - List tables in an mSQL database
* msql_list_fields() - List result fields
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_list_fields
(PHP 4, PHP 5)
msql_list_fields - List result fields
Description
resource msql_list_fields ( string $database , string $tablename [,
resource $link_identifier ] )
msql_list_fields() returns information about the given table.
Parameters
database
The name of the database.
tablename
The name of the table.
link_identifier
The mSQL connection. If not specified, the last link opened by
msql_connect() is assumed. If no such link is found, the function
will try to establish a link as if msql_connect() was called, and
use it.
Return Values
Returns a result set which may be traversed with any function that fetches
result sets, such as msql_fetch_array(). On failure, this function will
return FALSE.
See Also
* msql_list_tables() - List tables in an mSQL database
* msql_list_dbs() - List mSQL databases on server
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_list_tables
(PHP 4, PHP 5)
msql_list_tables - List tables in an mSQL database
Description
resource msql_list_tables ( string $database [, resource $link_identifier
] )
msql_list_tables() lists the tables on the specified database.
Parameters
database
The name of the database.
link_identifier
The mSQL connection. If not specified, the last link opened by
msql_connect() is assumed. If no such link is found, the function
will try to establish a link as if msql_connect() was called, and
use it.
Return Values
Returns a result set which may be traversed with any function that fetches
result sets, such as msql_fetch_array(). On failure, this function will
return FALSE.
See Also
* msql_list_fields() - List result fields
* msql_list_dbs() - List mSQL databases on server
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_num_fields
(PHP 4, PHP 5)
msql_num_fields - Get number of fields in result
Description
int msql_num_fields ( resource $result )
msql_num_fields() returns the number of fields in a result set.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to msql_query().
Return Values
Returns the number of fields in the result set.
See Also
* msql_query() - Send mSQL query
* msql_fetch_field() - Get field information
* msql_num_rows() - Get number of rows in result
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_num_rows
(PHP 4, PHP 5)
msql_num_rows - Get number of rows in result
Description
int msql_num_rows ( resource $query_identifier )
msql_num_rows() returns the number of rows in a result set.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to msql_query().
Return Values
Returns the number of rows in the result set.
See Also
* msql_num_fields() - Get number of fields in result
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_numfields
(PHP 4, PHP 5)
msql_numfields - Alias of msql_num_fields()
Description
This function is an alias of msql_num_fields().
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_numrows
(PHP 4, PHP 5)
msql_numrows - Alias of msql_num_rows()
Description
This function is an alias of msql_num_rows().
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_pconnect
(PHP 4, PHP 5)
msql_pconnect - Open persistent mSQL connection
Description
resource msql_pconnect ([ string $hostname ] )
msql_pconnect() acts very much like msql_connect() with two major
differences.
First, when connecting, the function would first try to find a
(persistent) link that's already open with the same host. If one is found,
an identifier for it will be returned instead of opening a new connection.
Second, the connection to the SQL server will not be closed when the
execution of the script ends. Instead, the link will remain open for
future use (msql_close() will not close links established by this
function).
Parameters
hostname
The hostname can also include a port number. e.g. hostname,port.
If not specified, the connection is established by the means of a
Unix domain socket, being more efficient than a localhost TCP
socket connection.
Note: While this function will accept a colon (:) as a host/port
separator, a comma (,) is the preferred method.
Return Values
Returns a positive mSQL link identifier on success, or FALSE on error.
See Also
* msql_connect() - Open mSQL connection
* msql_close() - Close mSQL connection
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_query
(PHP 4, PHP 5)
msql_query - Send mSQL query
Description
resource msql_query ( string $query [, resource $link_identifier ] )
msql_query() sends a query to the currently active database on the server
that's associated with the specified link identifier.
Parameters
query
The SQL query.
link_identifier
The mSQL connection. If not specified, the last link opened by
msql_connect() is assumed. If no such link is found, the function
will try to establish a link as if msql_connect() was called, and
use it.
Return Values
Returns a positive mSQL query identifier on success, or FALSE on error.
Examples
Example #1 msql_query() example
See Also
* msql_db_query() - Send mSQL query
* msql_select_db() - Select mSQL database
* msql_connect() - Open mSQL connection
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_regcase
(PHP 4, PHP 5)
msql_regcase - Alias of sql_regcase()
Description
This function is an alias of sql_regcase().
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_result
(PHP 4, PHP 5)
msql_result - Get result data
Description
string msql_result ( resource $result , int $row [, mixed $field ] )
msql_result() returns the contents of one cell from a mSQL result set.
When working on large result sets, you should consider using one of the
functions that fetch an entire row (specified below). As these functions
return the contents of multiple cells in one function call, they are often
much quicker than msql_result().
Recommended high-performance alternatives: msql_fetch_row(),
msql_fetch_array(), and msql_fetch_object().
Parameters
result
The result resource that is being evaluated. This result comes
from a call to msql_query().
row
The row offset.
field
Can be the field's offset, or the field's name, or the field's
table dot field's name (tablename.fieldname.). If the column name
has been aliased ('select foo as bar from ...'), use the alias
instead of the column name.
Note:
Specifying a numeric field offset is much quicker than
specifying a fieldname or tablename.fieldname.
Return Values
Returns the contents of the cell at the row and offset in the specified
mSQL result set.
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_select_db
(PHP 4, PHP 5)
msql_select_db - Select mSQL database
Description
bool msql_select_db ( string $database_name [, resource $link_identifier ]
)
msql_select_db() sets the current active database on the server that's
associated with the specified link_identifier.
Subsequent calls to msql_query() will be made on the active database.
Parameters
database_name
The database name.
link_identifier
The mSQL connection. If not specified, the last link opened by
msql_connect() is assumed. If no such link is found, the function
will try to establish a link as if msql_connect() was called, and
use it.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* msql_connect() - Open mSQL connection
* msql_pconnect() - Open persistent mSQL connection
* msql_query() - Send mSQL query
----------------------------------------------------------------------
----------------------------------------------------------------------
msql_tablename
(PHP 4, PHP 5)
msql_tablename - Alias of msql_result()
Description
This function is an alias of msql_result().
----------------------------------------------------------------------
----------------------------------------------------------------------
msql
(PHP 4, PHP 5)
msql - Alias of msql_db_query()
Description
This function is an alias of msql_db_query().
----------------------------------------------------------------------
Table of Contents
* msql_affected_rows - Returns number of affected rows
* msql_close - Close mSQL connection
* msql_connect - Open mSQL connection
* msql_create_db - Create mSQL database
* msql_createdb - Alias of msql_create_db
* msql_data_seek - Move internal row pointer
* msql_db_query - Send mSQL query
* msql_dbname - Alias of msql_result
* msql_drop_db - Drop (delete) mSQL database
* msql_error - Returns error message of last msql call
* msql_fetch_array - Fetch row as array
* msql_fetch_field - Get field information
* msql_fetch_object - Fetch row as object
* msql_fetch_row - Get row as enumerated array
* msql_field_flags - Get field flags
* msql_field_len - Get field length
* msql_field_name - Get the name of the specified field in a result
* msql_field_seek - Set field offset
* msql_field_table - Get table name for field
* msql_field_type - Get field type
* msql_fieldflags - Alias of msql_field_flags
* msql_fieldlen - Alias of msql_field_len
* msql_fieldname - Alias of msql_field_name
* msql_fieldtable - Alias of msql_field_table
* msql_fieldtype - Alias of msql_field_type
* msql_free_result - Free result memory
* msql_list_dbs - List mSQL databases on server
* msql_list_fields - List result fields
* msql_list_tables - List tables in an mSQL database
* msql_num_fields - Get number of fields in result
* msql_num_rows - Get number of rows in result
* msql_numfields - Alias of msql_num_fields
* msql_numrows - Alias of msql_num_rows
* msql_pconnect - Open persistent mSQL connection
* msql_query - Send mSQL query
* msql_regcase - Alias of sql_regcase
* msql_result - Get result data
* msql_select_db - Select mSQL database
* msql_tablename - Alias of msql_result
* msql - Alias of msql_db_query
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* Basic usage
* mSQL Functions
* msql_affected_rows - Returns number of affected rows
* msql_close - Close mSQL connection
* msql_connect - Open mSQL connection
* msql_create_db - Create mSQL database
* msql_createdb - Alias of msql_create_db
* msql_data_seek - Move internal row pointer
* msql_db_query - Send mSQL query
* msql_dbname - Alias of msql_result
* msql_drop_db - Drop (delete) mSQL database
* msql_error - Returns error message of last msql call
* msql_fetch_array - Fetch row as array
* msql_fetch_field - Get field information
* msql_fetch_object - Fetch row as object
* msql_fetch_row - Get row as enumerated array
* msql_field_flags - Get field flags
* msql_field_len - Get field length
* msql_field_name - Get the name of the specified field in a result
* msql_field_seek - Set field offset
* msql_field_table - Get table name for field
* msql_field_type - Get field type
* msql_fieldflags - Alias of msql_field_flags
* msql_fieldlen - Alias of msql_field_len
* msql_fieldname - Alias of msql_field_name
* msql_fieldtable - Alias of msql_field_table
* msql_fieldtype - Alias of msql_field_type
* msql_free_result - Free result memory
* msql_list_dbs - List mSQL databases on server
* msql_list_fields - List result fields
* msql_list_tables - List tables in an mSQL database
* msql_num_fields - Get number of fields in result
* msql_num_rows - Get number of rows in result
* msql_numfields - Alias of msql_num_fields
* msql_numrows - Alias of msql_num_rows
* msql_pconnect - Open persistent mSQL connection
* msql_query - Send mSQL query
* msql_regcase - Alias of sql_regcase
* msql_result - Get result data
* msql_select_db - Select mSQL database
* msql_tablename - Alias of msql_result
* msql - Alias of msql_db_query
----------------------------------------------------------------------
----------------------------------------------------------------------
Microsoft SQL Server
----------------------------------------------------------------------
Introduction
These functions allow you to access MS SQL Server database.
This extension is not available anymore on Windows with PHP 5.3 or later.
SQLSRV, an alternative driver for MS SQL is available from Microsoft:
>> http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
Requirements for Win32 platforms.
The extension requires the MS SQL Client Tools to be installed on the
system where PHP is installed. The Client Tools can be installed from the
MS SQL Server CD or by copying ntwdblib.dll from \winnt\system32 on the
server to \winnt\system32 on the PHP box. Copying ntwdblib.dll will only
provide access through named pipes. Configuration of the client will
require installation of all the tools.
This extension is not available anymore on Windows with PHP 5.3 or later.
SqlSrv, an alternative driver for MS SQL is available from Microsoft:
>> http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.
Requirements for Unix/Linux platforms.
To use the MSSQL extension on Unix/Linux, you first need to build and
install the FreeTDS library. Source code and installation instructions are
available at the FreeTDS home page: >> http://www.freetds.org/
Note:
On Windows, the DBLIB from Microsoft is used. Functions that return a
column name are based on the dbcolname() function in DBLIB. DBLIB was
developed for SQL Server 6.x where the max identifier length is 30. For
this reason, the maximum column length is 30 characters. On platforms
where FreeTDS is used (Linux), this is not a problem.
Note:
On Windows, if you're using MSSQL 2005 or greater you must copy the
ntwdblib.dll into the directory where you have installed php and
overwrite the one thats already in there. This is due to the version
distributed is old and outdated. Alternatively you can use the
>> http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx, ODBC,
PDO_DBLIB or PDO_ODBC extensions, to talk to MSSQL.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
The MSSQL extension is enabled by adding extension=php_mssql.dll to
php.ini.
To get these functions to work, you have to compile PHP with
--with-mssql[=DIR] , where DIR is the FreeTDS install prefix. And FreeTDS
should be compiled using --enable-msdblib .
Warning
MS SQL functions are aliases to Sybase functions if PHP is compiled with
Sybase extension and without MS SQL extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
MS SQL Server configuration options
Name Default Changeable Changelog
mssql.allow_persistent "1" PHP_INI_SYSTEM
mssql.max_persistent "-1" PHP_INI_SYSTEM
mssql.max_links "-1" PHP_INI_SYSTEM
mssql.min_error_severity "10" PHP_INI_ALL
mssql.min_message_severity "10" PHP_INI_ALL
mssql.compatability_mode "0" PHP_INI_ALL
mssql.connect_timeout "5" PHP_INI_ALL
mssql.timeout "60" PHP_INI_ALL Available since PHP
4.1.0.
mssql.textsize "-1" PHP_INI_ALL
mssql.textlimit "-1" PHP_INI_ALL
mssql.batchsize "0" PHP_INI_ALL Available since PHP
4.0.4.
mssql.datetimeconvert "1" PHP_INI_ALL Available since PHP
4.2.0.
mssql.secure_connection "0" PHP_INI_SYSTEM Available since PHP
4.3.0.
mssql.max_procs "-1" PHP_INI_ALL Available since PHP
4.3.0.
Available since PHP
mssql.charset "" PHP_INI_ALL 5.1.2 when built with
FreeTDS 7.0 or greater.
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
mssql link
A connection link returned by mssql_connect() and mssql_pconnect().
mssql result
A result handle returned by mssql_query() on SELECT queries.
mssql statement
A statement handle returned by mssql_init().
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
MSSQL_ASSOC (integer)
Return an associative array. Used on mssql_fetch_array()'s
result_type parameter.
MSSQL_NUM (integer)
Return an array with numeric keys. Used on mssql_fetch_array()'s
result_type parameter.
MSSQL_BOTH (integer)
Return an array with both numeric keys and keys with their field
name. This is the default value for mssql_fetch_array()'s
result_type parameter.
SQLTEXT (integer)
Indicates the 'TEXT' type in MSSQL, used by mssql_bind()'s type
parameter.
SQLVARCHAR (integer)
Indicates the 'VARCHAR' type in MSSQL, used by mssql_bind()'s type
parameter.
SQLCHAR (integer)
Indicates the 'CHAR' type in MSSQL, used by mssql_bind()'s type
parameter.
SQLINT1 (integer)
Represents one byte, with a range of -128 to 127.
SQLINT2 (integer)
Represents two bytes, with a range of -32768 to 32767.
SQLINT4 (integer)
Represents four bytes, with a range of -2147483648 to 2147483647.
SQLBIT (integer)
Indicates the 'BIT' type in MSSQL, used by mssql_bind()'s type
parameter.
SQLFLT4 (integer)
Represents an four byte float.
SQLFLT8 (integer)
Represents an eight byte float.
----------------------------------------------------------------------
----------------------------------------------------------------------
Mssql Functions
----------------------------------------------------------------------
mssql_bind
(PHP 4 >= 4.0.7, PHP 5, PECL odbtp >= 1.1.1)
mssql_bind - Adds a parameter to a stored procedure or a remote stored
procedure
Description
bool mssql_bind ( resource $stmt , string $param_name , mixed &$var , int
$type [, bool $is_output = false [, bool $is_null = false [, int $maxlen =
-1 ]]] )
Binds a parameter to a stored procedure or a remote stored procedure.
Parameters
stmt
Statement resource, obtained with mssql_init().
param_name
The parameter name, as a string.
Note:
You have to include the @ character, like in the T-SQL syntax.
See the explanation included in mssql_execute().
var
The PHP variable you'll bind the MSSQL parameter to. It is passed
by reference, to retrieve OUTPUT and RETVAL values after the
procedure execution.
type
One of: SQLTEXT, SQLVARCHAR, SQLCHAR, SQLINT1, SQLINT2, SQLINT4,
SQLBIT, SQLFLT4, SQLFLT8, SQLFLTN.
is_output
Whether the value is an OUTPUT parameter or not. If it's an OUTPUT
parameter and you don't mention it, it will be treated as a normal
input parameter and no error will be thrown.
is_null
Whether the parameter is NULL or not. Passing the NULL value as
var will not do the job.
maxlen
Used with char/varchar values. You have to indicate the length of
the data so if the parameter is a varchar(50), the type must be
SQLVARCHAR and this value 50.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 mssql_bind() example
See Also
* mssql_execute() - Executes a stored procedure on a MS SQL server
database
* mssql_free_statement() - Free statement memory
* mssql_init() - Initializes a stored procedure or a remote stored
procedure
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_close
(PHP 4, PHP 5, PECL odbtp >= 1.1.1)
mssql_close - Close MS SQL Server connection
Description
bool mssql_close ([ resource $link_identifier ] )
Closes the link to a MS SQL Server database that's associated with the
specified link identifier. If the link identifier isn't specified, the
last opened link is assumed.
Note that this isn't usually necessary, as non-persistent open links are
automatically closed at the end of the script's execution.
Parameters
link_identifier
A MS SQL link identifier, returned by mssql_connect().
This function will not close persistent links generated by
mssql_pconnect().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 mssql_close() example
See Also
* mssql_connect() - Open MS SQL server connection
* mssql_pconnect() - Open persistent MS SQL connection
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_connect
(PHP 4, PHP 5, PECL odbtp >= 1.1.1)
mssql_connect - Open MS SQL server connection
Description
resource mssql_connect ([ string $servername [, string $username [, string
$password [, bool $new_link = false ]]]] )
mssql_connect() establishes a connection to a MS SQL server.
The link to the server will be closed as soon as the execution of the
script ends, unless it's closed earlier by explicitly calling
mssql_close().
Parameters
servername
The MS SQL server. It can also include a port number, e.g.
hostname:port (Linux), or hostname,port (Windows).
username
The username.
password
The password.
new_link
If a second call is made to mssql_connect() with the same
arguments, no new link will be established, but instead, the link
identifier of the already opened link will be returned. This
parameter modifies this behavior and makes mssql_connect() always
open a new link, even if mssql_connect() was called before with
the same parameters.
Return Values
Returns a MS SQL link identifier on success, or FALSE on error.
Changelog
Version Description
4.4.1 and 5.1.0 The new_link parameter was added
Examples
Example #1 mssql_connect() example
\ or
// , when using a non default port number
$server = 'KALLESPC\SQLEXPRESS';
// Connect to MSSQL
$link = mssql_connect($server, 'sa', 'phpfi');
if (!$link) {
die('Something went wrong while connecting to MSSQL');
}
?>
See Also
* mssql_close() - Close MS SQL Server connection
* mssql_pconnect() - Open persistent MS SQL connection
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_data_seek
(PHP 4, PHP 5, PECL odbtp >= 1.1.1)
mssql_data_seek - Moves internal row pointer
Description
bool mssql_data_seek ( resource $result_identifier , int $row_number )
mssql_data_seek() moves the internal row pointer of the MS SQL result
associated with the specified result identifier to point to the specified
row number, first row being number 0. The next call to mssql_fetch_row()
would return that row.
Parameters
result_identifier
The result resource that is being evaluated.
row_number
The desired row number of the new result pointer.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 mssql_data_seek() example
= 13');
if (!$result) {
die('Query failed.');
}
// Select every 4th student in the results
for ($i = mssql_num_rows($result) - 1; $i % 4; $i++) {
if (!mssql_data_seek($result, $i)) {
continue;
}
// Fetch the row ...
}
// Free the query result
mssql_free_result($result);
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_execute
(PHP 4 >= 4.0.7, PHP 5, PECL odbtp >= 1.1.1)
mssql_execute - Executes a stored procedure on a MS SQL server database
Description
mixed mssql_execute ( resource $stmt [, bool $skip_results = false ] )
Executes a stored procedure on a MS SQL server database
Parameters
stmt
Statement handle obtained with mssql_init().
skip_results
Whenever to skip the results or not.
Examples
Example #1 mssql_execute() example
Notes
Note:
If the stored procedure returns parameters or a return value these will
be available after the call to mssql_execute() unless the stored
procedure returns more than one result set. In that case use
mssql_next_result() to shift through the results. When the last result
has been processed the output parameters and return values will be
available.
See Also
* mssql_bind() - Adds a parameter to a stored procedure or a remote
stored procedure
* mssql_free_statement() - Free statement memory
* mssql_init() - Initializes a stored procedure or a remote stored
procedure
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_fetch_array
(PHP 4, PHP 5, PECL odbtp >= 1.1.1)
mssql_fetch_array - Fetch a result row as an associative array, a numeric
array, or both
Description
array mssql_fetch_array ( resource $result [, int $result_type =
MSSQL_BOTH ] )
mssql_fetch_array() is an extended version of mssql_fetch_row(). In
addition to storing the data in the numeric indices of the result array,
it also stores the data in associative indices, using the field names as
keys.
An important thing to note is that using mssql_fetch_array() is NOT
significantly slower than using mssql_fetch_row(), while it provides a
significant added value.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mssql_query().
result_type
The type of array that is to be fetched. It's a constant and can
take the following values: MSSQL_ASSOC, MSSQL_NUM, and MSSQL_BOTH.
Return Values
Returns an array that corresponds to the fetched row, or FALSE if there
are no more rows.
Examples
Example #1 mssql_fetch_array() example
Notes
Note: Field names returned by this function are case-sensitive.
Note: This function sets NULL fields to the PHP NULL value.
See Also
* mssql_fetch_row() - Get row as enumerated array
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_fetch_assoc
(PHP 4 >= 4.2.0, PHP 5, PECL odbtp >= 1.1.1)
mssql_fetch_assoc - Returns an associative array of the current row in the
result
Description
array mssql_fetch_assoc ( resource $result_id )
Returns an associative array that corresponds to the fetched row and moves
the internal data pointer ahead. mssql_fetch_assoc() is equivalent to
calling mssql_fetch_array() with MSSQL_ASSOC for the optional second
parameter.
Parameters
result_id
The result resource that is being evaluated. This result comes
from a call to mssql_query().
Return Values
Returns an associative array that corresponds to the fetched row, or FALSE
if there are no more rows.
Examples
Example #1 mssql_fetch_assoc() example
';
while ($row = mssql_fetch_assoc($query)) {
echo '' . $row['name'] . ' (' . $row['username'] . ') ';
}
echo '';
}
// Free the query result
mssql_free_result($query);
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_fetch_batch
(PHP 4 >= 4.0.4, PHP 5, PECL odbtp >= 1.1.1)
mssql_fetch_batch - Returns the next batch of records
Description
int mssql_fetch_batch ( resource $result )
Returns the next batch of records
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mssql_query().
Return Values
Returns the batch number as an integer.
Examples
Example #1 mssql_fetch_batch() example
= 0) {
while ($row = mssql_fetch_assoc($result)) {
// Do stuff ...
}
--$records;
}
if ($batchsize = mssql_fetch_batch($result)) {
// $batchsize is the number of records left
// in the result, but not shown above
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_fetch_field
(PHP 4, PHP 5, PECL odbtp >= 1.1.1)
mssql_fetch_field - Get field information
Description
object mssql_fetch_field ( resource $result [, int $field_offset = -1 ] )
mssql_fetch_field() can be used in order to obtain information about
fields in a certain query result.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mssql_query().
field_offset
The numerical field offset. If the field offset is not specified,
the next field that was not yet retrieved by this function is
retrieved. The field_offset starts at 0.
Return Values
Returns an object containing field information.
The properties of the object are:
* name - column name. if the column is a result of a function, this
property is set to computed#N, where #N is a serial number.
* column_source - the table from which the column was taken
* max_length - maximum length of the column
* numeric - 1 if the column is numeric
* type - the column type.
Examples
Example #1 mssql_fetch_field() example
Table structure for \'persons\'';
echo '';
// Table header
echo '';
echo '';
echo 'Field name ';
echo 'Data type ';
echo 'Max length ';
echo ' ';
echo ' ';
// Dump all fields
echo '';
for ($i = 0; $i < mssql_num_fields($query); ++$i) {
// Fetch the field information
$field = mssql_fetch_field($query, $i);
// Print the row
echo '';
echo '' . $field->name . ' ';
echo '' . strtoupper($field->type) . ' ';
echo '' . $field->max_length . ' ';
echo ' ';
}
echo ' ';
echo '
';
// Free the query result
mssql_free_result($query);
?>
See Also
* mssql_field_seek() - Seeks to the specified field offset
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_fetch_object
(PHP 4, PHP 5, PECL odbtp >= 1.1.1)
mssql_fetch_object - Fetch row as object
Description
object mssql_fetch_object ( resource $result )
mssql_fetch_object() is similar to mssql_fetch_array(), with one
difference - an object is returned, instead of an array. Indirectly, that
means that you can only access the data by the field names, and not by
their offsets (numbers are illegal property names).
Speed-wise, the function is identical to mssql_fetch_array(), and almost
as quick as mssql_fetch_row() (the difference is insignificant).
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mssql_query().
Return Values
Returns an object with properties that correspond to the fetched row, or
FALSE if there are no more rows.
Examples
Example #1 mssql_fetch_object() example
';
while ($row = mssql_fetch_object($query)) {
echo '' . $row->name . ' (' . $row->username . ') ';
}
echo '';
}
// Free the query result
mssql_free_result($query);
?>
Notes
Note: Field names returned by this function are case-sensitive.
Note: This function sets NULL fields to the PHP NULL value.
See Also
* mssql_fetch_array() - Fetch a result row as an associative array, a
numeric array, or both
* mssql_fetch_row() - Get row as enumerated array
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_fetch_row
(PHP 4, PHP 5, PECL odbtp >= 1.1.1)
mssql_fetch_row - Get row as enumerated array
Description
array mssql_fetch_row ( resource $result )
mssql_fetch_row() fetches one row of data from the result associated with
the specified result identifier. The row is returned as an array. Each
result column is stored in an array offset, starting at offset 0.
Subsequent call to mssql_fetch_row() would return the next row in the
result set, or FALSE if there are no more rows.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mssql_query().
Return Values
Returns an array that corresponds to the fetched row, or FALSE if there
are no more rows.
Examples
Example #1 mssql_fetch_row() example
The above example will output something similar to:
Quote #42: "The answer to everything..."
Notes
Note: This function sets NULL fields to the PHP NULL value.
See Also
* mssql_fetch_array() - Fetch a result row as an associative array, a
numeric array, or both
* mssql_fetch_object() - Fetch row as object
* mssql_data_seek() - Moves internal row pointer
* mssql_result() - Get result data
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_field_length
(PHP 4, PHP 5, PECL odbtp >= 1.1.1)
mssql_field_length - Get the length of a field
Description
int mssql_field_length ( resource $result [, int $offset = -1 ] )
Returns the length of field no. offset in result.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mssql_query().
offset
The field offset, starts at 0. If omitted, the current field is
used.
Return Values
The length of the specified field index on success or FALSE on failure.
Examples
Example #1 mssql_field_length() example
The above example will output something similar to:
The field 'age' has a data length of 4
Notes
Note: Note to Windows Users
Due to a limitation in the underlying API used by PHP (MS DBLib C API),
the length of VARCHAR fields is limited to 255. If you need to store
more data, use a TEXT field instead.
See Also
* mssql_field_name() - Get the name of a field
* mssql_field_type() - Gets the type of a field
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_field_name
(PHP 4, PHP 5, PECL odbtp >= 1.1.1)
mssql_field_name - Get the name of a field
Description
string mssql_field_name ( resource $result [, int $offset = -1 ] )
Returns the name of field no. offset in result.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mssql_query().
offset
The field offset, starts at 0. If omitted, the current field is
used.
Return Values
The name of the specified field index on success or FALSE on failure.
Examples
Example #1 mssql_field_name() example
The above example will output something similar to:
Result set contains the following field(s):
- username
- name
- email
See Also
* mssql_field_length() - Get the length of a field
* mssql_field_type() - Gets the type of a field
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_field_seek
(PHP 4, PHP 5, PECL odbtp >= 1.1.1)
mssql_field_seek - Seeks to the specified field offset
Description
bool mssql_field_seek ( resource $result , int $field_offset )
Seeks to the specified field offset. If the next call to
mssql_fetch_field() won't include a field offset, this field would be
returned.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mssql_query().
field_offset
The field offset, starts at 0.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Using mssql_field_seek() on the example for mssql_fetch_field()
Table structure for \'persons\'';
echo '';
// Table header
echo '';
echo '';
echo 'Field name ';
echo 'Data type ';
echo 'Max length ';
echo ' ';
echo ' ';
// Dump all fields
echo '';
for ($i = 0; $i < mssql_num_fields($query); ++$i) {
// Fetch the field information, notice the
// field_offset parameter is not set. See
// the mssql_field_seek call below
$field = mssql_fetch_field($query);
// Print the row
echo '';
echo '' . $field->name . ' ';
echo '' . strtoupper($field->type) . ' ';
echo '' . $field->max_length . ' ';
echo ' ';
// Move the internal seek pointer to the next
// row in the result set
mssql_field_seek($query, $i + 1);
}
echo ' ';
echo '
';
// Free the query result
mssql_free_result($query);
?>
See Also
* mssql_fetch_field() - Get field information
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_field_type
(PHP 4, PHP 5, PECL odbtp >= 1.1.1)
mssql_field_type - Gets the type of a field
Description
string mssql_field_type ( resource $result [, int $offset = -1 ] )
Returns the type of field no. offset in result.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mssql_query().
offset
The field offset, starts at 0. If omitted, the current field is
used.
Return Values
The type of the specified field index on success or FALSE on failure.
Examples
Example #1 mssql_field_type() example
The above example will output something similar to:
'name' is a type of CHAR(50)
See Also
* mssql_field_length() - Get the length of a field
* mssql_field_name() - Get the name of a field
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_free_result
(PHP 4, PHP 5, PECL odbtp >= 1.1.1)
mssql_free_result - Free result memory
Description
bool mssql_free_result ( resource $result )
mssql_free_result() only needs to be called if you are worried about using
too much memory while your script is running. All result memory will
automatically be freed when the script ends. You may call
mssql_free_result() with the result identifier as an argument and the
associated result memory will be freed.
Parameters
result
The result resource that is being freed. This result comes from a
call to mssql_query().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 mssql_free_result() example
See Also
* mssql_free_statement() - Free statement memory
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_free_statement
(PHP 4 >= 4.3.2, PHP 5, PECL odbtp >= 1.1.1)
mssql_free_statement - Free statement memory
Description
bool mssql_free_statement ( resource $stmt )
mssql_free_statement() only needs to be called if you are worried about
using too much memory while your script is running. All statement memory
will automatically be freed when the script ends. You may call
mssql_free_statement() with the statement identifier as an argument and
the associated statement memory will be freed.
Parameters
stmt
Statement resource, obtained with mssql_init().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 mssql_free_statement() example
See Also
* mssql_bind() - Adds a parameter to a stored procedure or a remote
stored procedure
* mssql_execute() - Executes a stored procedure on a MS SQL server
database
* mssql_init() - Initializes a stored procedure or a remote stored
procedure
* mssql_free_result() - Free result memory
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_get_last_message
(PHP 4, PHP 5, PECL odbtp >= 1.1.1)
mssql_get_last_message - Returns the last message from the server
Description
string mssql_get_last_message ( void )
Gets the last message from the MS-SQL server
Parameters
This function has no parameters.
Return Values
Returns last error message from server, or an empty string if no error
messages are returned from MSSQL.
Examples
Example #1 mssql_get_last_message() example
The above example will output something similar to:
MSSQL error: Invalid object name 'php.dbo.not-found'.
See Also
* mssql_min_error_severity() - Sets the minimum error severity
* mssql_min_message_severity() - Sets the minimum message severity
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_guid_string
(PHP 4 >= 4.0.7, PHP 5, PECL odbtp >= 1.1.1)
mssql_guid_string - Converts a 16 byte binary GUID to a string
Description
string mssql_guid_string ( string $binary [, bool $short_format = false ]
)
Converts a 16 byte binary GUID to a string.
Parameters
binary
A 16 byte binary GUID.
short_format
Whenever to use short format.
Return Values
Returns the converted string on success.
Examples
Example #1 mssql_guid_string() example
The above example will output:
string(36) "35353931-3035-3138-3937-373830383630"
string(32) "31393535353038313937373830383630"
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_init
(PHP 4 >= 4.0.7, PHP 5, PECL odbtp >= 1.1.1)
mssql_init - Initializes a stored procedure or a remote stored procedure
Description
resource mssql_init ( string $sp_name [, resource $link_identifier ] )
Initializes a stored procedure or a remote stored procedure.
Parameters
sp_name
Stored procedure name, like ownew.sp_name or
otherdb.owner.sp_name.
link_identifier
A MS SQL link identifier, returned by mssql_connect().
Return Values
Returns a resource identifier "statement", used in subsequent calls to
mssql_bind() and mssql_execute(), or FALSE on errors.
Examples
Example #1 mssql_init() example
See Also
* mssql_bind() - Adds a parameter to a stored procedure or a remote
stored procedure
* mssql_execute() - Executes a stored procedure on a MS SQL server
database
* mssql_free_statement() - Free statement memory
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_min_error_severity
(PHP 4, PHP 5, PECL odbtp >= 1.1.1)
mssql_min_error_severity - Sets the minimum error severity
Description
void mssql_min_error_severity ( int $severity )
Sets the minimum error severity.
Parameters
severity
The new error severity.
Return Values
No value is returned.
Examples
Example #1 mssql_min_error_severity() example
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_min_message_severity
(PHP 4, PHP 5, PECL odbtp >= 1.1.1)
mssql_min_message_severity - Sets the minimum message severity
Description
void mssql_min_message_severity ( int $severity )
Sets the minimum message severity.
Parameters
severity
The new message severity.
Return Values
No value is returned.
Examples
Example #1 mssql_min_message_severity() example
The above example will output:
mssql_select_db(): Unable to select database: THIS_DATABASE_DOES_NOT_EXISTS
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_next_result
(PHP 4 >= 4.0.5, PHP 5, PECL odbtp >= 1.1.1)
mssql_next_result - Move the internal result pointer to the next result
Description
bool mssql_next_result ( resource $result_id )
When sending more than one SQL statement to the server or executing a
stored procedure with multiple results, it will cause the server to return
multiple result sets. This function will test for additional results
available form the server. If an additional result set exists it will free
the existing result set and prepare to fetch the rows from the new result
set.
Parameters
result_id
The result resource that is being evaluated. This result comes
from a call to mssql_query().
Return Values
Returns TRUE if an additional result set was available or FALSE otherwise.
Examples
Example #1 mssql_next_result() example
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_num_fields
(PHP 4, PHP 5, PECL odbtp >= 1.1.1)
mssql_num_fields - Gets the number of fields in result
Description
int mssql_num_fields ( resource $result )
mssql_num_fields() returns the number of fields in a result set.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mssql_query().
Return Values
Returns the number of fields, as an integer.
Examples
Example #1 mssql_num_fields() example
';
$header = false;
// Iterate through returned results
while ($row = mssql_fetch_array($data)) {
// Build the table header
if (!$header) {
echo '';
echo '';
for ($i = 1; ($i + 1) <= mssql_num_fields($data); ++$i) {
echo '' . ucfirst($row[$i]) . ' ';
}
echo ' ';
echo ' ';
echo '';
$header = true;
}
// Build the row
echo '';
foreach($row as $value) {
echo '' . $value . ' ';
}
echo ' ';
}
// Close table
echo ' ';
echo '';
// Clean up
mssql_free_result($data);
mssql_close($link);
?>
See Also
* mssql_query() - Send MS SQL query
* mssql_fetch_field() - Get field information
* mssql_num_rows() - Gets the number of rows in result
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_num_rows
(PHP 4, PHP 5, PECL odbtp >= 1.1.1)
mssql_num_rows - Gets the number of rows in result
Description
int mssql_num_rows ( resource $result )
mssql_num_rows() returns the number of rows in a result set.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mssql_query().
Return Values
Returns the number of rows, as an integer.
Examples
Example #1 mssql_num_rows() example
See Also
* mssql_query() - Send MS SQL query
* mssql_fetch_row() - Get row as enumerated array
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_pconnect
(PHP 4, PHP 5, PECL odbtp >= 1.1.1)
mssql_pconnect - Open persistent MS SQL connection
Description
resource mssql_pconnect ([ string $servername [, string $username [,
string $password [, bool $new_link = false ]]]] )
mssql_pconnect() acts very much like mssql_connect() with two major
differences.
First, when connecting, the function would first try to find a
(persistent) link that's already open with the same host, username and
password. If one is found, an identifier for it will be returned instead
of opening a new connection.
Second, the connection to the SQL server will not be closed when the
execution of the script ends. Instead, the link will remain open for
future use (mssql_close() will not close links established by
mssql_pconnect()).
This type of links is therefore called 'persistent'.
Parameters
servername
The MS SQL server. It can also include a port number. e.g.
hostname:port.
username
The username.
password
The password.
new_link
If a second call is made to mssql_pconnect() with the same
arguments, no new link will be established, but instead, the link
identifier of the already opened link will be returned. This
parameter modifies this behavior and makes mssql_pconnect() always
open a new link, even if mssql_pconnect() was called before with
the same parameters.
Return Values
Returns a positive MS SQL persistent link identifier on success, or FALSE
on error.
Examples
Example #1 mssql_pconnect() using the new_link parameter
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_query
(PHP 4, PHP 5, PECL odbtp >= 1.1.1)
mssql_query - Send MS SQL query
Description
mixed mssql_query ( string $query [, resource $link_identifier [, int
$batch_size = 0 ]] )
mssql_query() sends a query to the currently active database on the server
that's associated with the specified link identifier.
Parameters
query
An SQL query.
link_identifier
A MS SQL link identifier, returned by mssql_connect() or
mssql_pconnect().
If the link identifier isn't specified, the last opened link is
assumed. If no link is open, the function tries to establish a
link as if mssql_connect() was called, and use it.
batch_size
The number of records to batch in the buffer.
Return Values
Returns a MS SQL result resource on success, TRUE if no rows were
returned, or FALSE on error.
Examples
Example #1 mssql_query() example
Notes
Note:
If the query returns multiple results then it is necessary to fetch all
results by mssql_next_result() or free the results by
mssql_free_result() before executing next query.
See Also
* mssql_select_db() - Select MS SQL database
* mssql_connect() - Open MS SQL server connection
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_result
(PHP 4, PHP 5, PECL odbtp >= 1.1.1)
mssql_result - Get result data
Description
string mssql_result ( resource $result , int $row , mixed $field )
mssql_result() returns the contents of one cell from a MS SQL result set.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mssql_query().
row
The row number.
field
Can be the field's offset, the field's name or the field's table
dot field's name (tablename.fieldname). If the column name has
been aliased ('select foo as bar from...'), it uses the alias
instead of the column name.
Note:
Specifying a numeric offset for the field argument is much
quicker than specifying a fieldname or tablename.fieldname
argument.
Return Values
Returns the contents of the specified cell.
Examples
Example #1 mssql_result() example
The above example will output something similar to:
Kalle
Felipe
Emil
Ross
Example #2 Faster alternative to above example
Notes
Note:
When working on large result sets, you should consider using one of the
functions that fetch an entire row (specified below). As these functions
return the contents of multiple cells in one function call, they're MUCH
quicker than mssql_result().
See Also
Recommended high-performance alternatives:
* mssql_fetch_row() - Get row as enumerated array
* mssql_fetch_array() - Fetch a result row as an associative array, a
numeric array, or both
* mssql_fetch_assoc() - Returns an associative array of the current row
in the result
* mssql_fetch_object() - Fetch row as object
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_rows_affected
(PHP 4 >= 4.0.4, PHP 5, PECL odbtp >= 1.1.1)
mssql_rows_affected - Returns the number of records affected by the query
Description
int mssql_rows_affected ( resource $link_identifier )
Returns the number of records affected by the last write query.
Parameters
link_identifier
A MS SQL link identifier, returned by mssql_connect() or
mssql_pconnect().
Return Values
Returns the number of records affected by last operation.
Examples
Example #1 mssql_rows_affected() example
----------------------------------------------------------------------
----------------------------------------------------------------------
mssql_select_db
(PHP 4, PHP 5, PECL odbtp >= 1.1.1)
mssql_select_db - Select MS SQL database
Description
bool mssql_select_db ( string $database_name [, resource $link_identifier
] )
mssql_select_db() sets the current active database on the server that's
associated with the specified link identifier.
Every subsequent call to mssql_query() will be made on the active
database.
Parameters
database_name
The database name.
To escape the name of a database that contains spaces, hyphens
("-"), or any other exceptional characters, the database name must
be enclosed in brackets, as is shown in the example, below. This
technique must also be applied when selecting a database name that
is also a reserved word (such as primary).
link_identifier
A MS SQL link identifier, returned by mssql_connect() or
mssql_pconnect().
If no link identifier is specified, the last opened link is
assumed. If no link is open, the function will try to establish a
link as if mssql_connect() was called, and use it.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 mssql_select_db() example
Example #2 Escaping the database name with square brackets
See Also
* mssql_connect() - Open MS SQL server connection
* mssql_pconnect() - Open persistent MS SQL connection
* mssql_query() - Send MS SQL query
----------------------------------------------------------------------
Table of Contents
* mssql_bind - Adds a parameter to a stored procedure or a remote stored
procedure
* mssql_close - Close MS SQL Server connection
* mssql_connect - Open MS SQL server connection
* mssql_data_seek - Moves internal row pointer
* mssql_execute - Executes a stored procedure on a MS SQL server
database
* mssql_fetch_array - Fetch a result row as an associative array, a
numeric array, or both
* mssql_fetch_assoc - Returns an associative array of the current row in
the result
* mssql_fetch_batch - Returns the next batch of records
* mssql_fetch_field - Get field information
* mssql_fetch_object - Fetch row as object
* mssql_fetch_row - Get row as enumerated array
* mssql_field_length - Get the length of a field
* mssql_field_name - Get the name of a field
* mssql_field_seek - Seeks to the specified field offset
* mssql_field_type - Gets the type of a field
* mssql_free_result - Free result memory
* mssql_free_statement - Free statement memory
* mssql_get_last_message - Returns the last message from the server
* mssql_guid_string - Converts a 16 byte binary GUID to a string
* mssql_init - Initializes a stored procedure or a remote stored
procedure
* mssql_min_error_severity - Sets the minimum error severity
* mssql_min_message_severity - Sets the minimum message severity
* mssql_next_result - Move the internal result pointer to the next
result
* mssql_num_fields - Gets the number of fields in result
* mssql_num_rows - Gets the number of rows in result
* mssql_pconnect - Open persistent MS SQL connection
* mssql_query - Send MS SQL query
* mssql_result - Get result data
* mssql_rows_affected - Returns the number of records affected by the
query
* mssql_select_db - Select MS SQL database
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Mssql Functions
* mssql_bind - Adds a parameter to a stored procedure or a remote
stored procedure
* mssql_close - Close MS SQL Server connection
* mssql_connect - Open MS SQL server connection
* mssql_data_seek - Moves internal row pointer
* mssql_execute - Executes a stored procedure on a MS SQL server
database
* mssql_fetch_array - Fetch a result row as an associative array, a
numeric array, or both
* mssql_fetch_assoc - Returns an associative array of the current
row in the result
* mssql_fetch_batch - Returns the next batch of records
* mssql_fetch_field - Get field information
* mssql_fetch_object - Fetch row as object
* mssql_fetch_row - Get row as enumerated array
* mssql_field_length - Get the length of a field
* mssql_field_name - Get the name of a field
* mssql_field_seek - Seeks to the specified field offset
* mssql_field_type - Gets the type of a field
* mssql_free_result - Free result memory
* mssql_free_statement - Free statement memory
* mssql_get_last_message - Returns the last message from the server
* mssql_guid_string - Converts a 16 byte binary GUID to a string
* mssql_init - Initializes a stored procedure or a remote stored
procedure
* mssql_min_error_severity - Sets the minimum error severity
* mssql_min_message_severity - Sets the minimum message severity
* mssql_next_result - Move the internal result pointer to the next
result
* mssql_num_fields - Gets the number of fields in result
* mssql_num_rows - Gets the number of rows in result
* mssql_pconnect - Open persistent MS SQL connection
* mssql_query - Send MS SQL query
* mssql_result - Get result data
* mssql_rows_affected - Returns the number of records affected by
the query
* mssql_select_db - Select MS SQL database
----------------------------------------------------------------------
----------------------------------------------------------------------
MySQL
----------------------------------------------------------------------
Introduction
These functions allow you to access MySQL database servers. More
information about MySQL can be found at >> http://www.mysql.com/.
Documentation for MySQL can be found at >> http://dev.mysql.com/doc/.
For an overview of MySQL database connectivity terms and products see
Overview.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
In order to have these functions available, you must compile PHP with
MySQL support.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
For compiling, simply use the --with-mysql[=DIR] configuration option
where the optional [DIR] points to the MySQL installation directory.
Although this MySQL extension is compatible with MySQL 4.1.0 and greater,
it doesn't support the extra functionality that these versions provide.
For that, use the MySQLi extension.
If you would like to install the mysql extension along with the mysqli
extension you have to use the same client library to avoid any conflicts.
Installation on Linux Systems
PHP 4
The option --with-mysql is enabled by default. This default behavior may
be disabled with the --without-mysql configure option. If MySQL is enabled
without specifying the path to the MySQL install DIR, PHP will use the
bundled MySQL client libraries.
Users who run other applications that use MySQL (for example, auth-mysql)
should not use the bundled library, but rather specify the path to MySQL's
install directory, like so: --with-mysql=/path/to/mysql . This will force
PHP to use the client libraries installed by MySQL, thus avoiding any
conflicts.
PHP 5.0.x, 5.1.x, 5.2.x
MySQL is not enabled by default, nor is the MySQL library bundled with
PHP. Read this FAQ for details on why. Use the --with-mysql[=DIR]
configure option to include MySQL support. You can download headers and
libraries from >> MySQL.
PHP 5.3.0+
In PHP 5.3.0 and above the MySQL-related database extensions use the MySQL
Native Driver by default. This means that the MySQL Client Library
(libmysql) is no longer required in order to support connection to a MySQL
database. The extensions mysql, mysqli, and PHP_PDO_MYSQL are all enabled
by default in PHP 5.3.0+, and all use the MySQL Native Driver by default.
In each case no further installation steps are required in order to use
these extensions, although you may want to set some preferences in php.ini
depending on your requirements.
Installation on Windows Systems
PHP 4
The PHP MySQL extension is compiled into PHP.
PHP 5.0.x, 5.1.x, 5.2.x
MySQL is no longer enabled by default, so the php_mysql.dll DLL must be
enabled inside of php.ini. Also, PHP needs access to the MySQL client
library. A file named libmysql.dll is included in the Windows PHP
distribution and in order for PHP to talk to MySQL this file needs to be
available to the Windows systems PATH. See the FAQ titled "How do I add my
PHP directory to the PATH on Windows" for information on how to do this.
Although copying libmysql.dll to the Windows system directory also works
(because the system directory is by default in the system's PATH), it's
not recommended.
As with enabling any PHP extension (such as php_mysql.dll), the PHP
directive extension_dir should be set to the directory where the PHP
extensions are located. See also the Manual Windows Installation
Instructions. An example extension_dir value for PHP 5 is c:\php\ext
Note:
If when starting the web server an error similar to the following
occurs: "Unable to load dynamic library './php_mysql.dll'", this is
because php_mysql.dll and/or libmysql.dll cannot be found by the system.
PHP 5.3.0+
Please refer to these notes on installing MySQL support on PHP 5.3.0 and
above.
MySQL Installation Notes
Warning
Crashes and startup problems of PHP may be encountered when loading this
extension in conjunction with the recode extension. See the recode
extension for more information.
Note:
If you need charsets other than latin (default), you have to install
external (not bundled) libmysql with compiled charset support.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
MySQL Configuration Options
Name Default Changeable Changelog
mysql.allow_persistent "1" PHP_INI_SYSTEM
mysql.max_persistent "-1" PHP_INI_SYSTEM
mysql.max_links "-1" PHP_INI_SYSTEM
mysql.trace_mode "0" PHP_INI_ALL Available since PHP 4.3.0.
mysql.default_port NULL PHP_INI_ALL
mysql.default_socket NULL PHP_INI_ALL Available since PHP 4.0.1.
mysql.default_host NULL PHP_INI_ALL
mysql.default_user NULL PHP_INI_ALL
mysql.default_password NULL PHP_INI_ALL
PHP_INI_SYSTEM in PHP <=
mysql.connect_timeout "60" PHP_INI_ALL 4.3.2. Available since PHP
4.3.0.
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
mysql.allow_persistent boolean
Whether to allow persistent connections to MySQL.
mysql.max_persistent integer
The maximum number of persistent MySQL connections per process.
mysql.max_links integer
The maximum number of MySQL connections per process, including
persistent connections.
mysql.trace_mode boolean
Trace mode. When mysql.trace_mode is enabled, warnings for
table/index scans, non free result sets, and SQL-Errors will be
displayed. (Introduced in PHP 4.3.0)
mysql.default_port string
The default TCP port number to use when connecting to the database
server if no other port is specified. If no default is specified,
the port will be obtained from the MYSQL_TCP_PORT environment
variable, the mysql-tcp entry in /etc/services or the compile-time
MYSQL_PORT constant, in that order. Win32 will only use the
MYSQL_PORT constant.
mysql.default_socket string
The default socket name to use when connecting to a local database
server if no other socket name is specified.
mysql.default_host string
The default server host to use when connecting to the database
server if no other host is specified. Doesn't apply in SQL safe
mode.
mysql.default_user string
The default user name to use when connecting to the database
server if no other name is specified. Doesn't apply in SQL safe
mode.
mysql.default_password string
The default password to use when connecting to the database server
if no other password is specified. Doesn't apply in SQL safe mode.
mysql.connect_timeout integer
Connect timeout in seconds. On Linux this timeout is also used for
waiting for the first answer from the server.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
There are two resource types used in the MySQL module. The first one is
the link identifier for a database connection, the second a resource which
holds the result of a query.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
Since PHP 4.3.0 it is possible to specify additional client flags for the
mysql_connect() and mysql_pconnect() functions. The following constants
are defined:
MySQL client constants
Constant Description
MYSQL_CLIENT_COMPRESS Use compression protocol
MYSQL_CLIENT_IGNORE_SPACE Allow space after function names
Allow interactive_timeout seconds (instead of
MYSQL_CLIENT_INTERACTIVE wait_timeout ) of inactivity before closing the
connection.
Use SSL encryption. This flag is only available
MYSQL_CLIENT_SSL with version 4.x of the MySQL client library or
newer. Version 3.23.x is bundled both with PHP 4
and Windows binaries of PHP 5.
The function mysql_fetch_array() uses a constant for the different types
of result arrays. The following constants are defined:
MySQL fetch constants
Constant Description
MYSQL_ASSOC Columns are returned into the array having the fieldname as
the array index.
MYSQL_BOTH Columns are returned into the array having both a numerical
index and the fieldname as the array index.
Columns are returned into the array having a numerical index
MYSQL_NUM to the fields. This index starts with 0, the first field in
the result.
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Table of Contents
* MySQL extension overview example
----------------------------------------------------------------------
MySQL extension overview example
This simple example shows how to connect, execute a query, print resulting
rows and disconnect from a MySQL database.
Example #1 MySQL extension overview example
\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t\n";
foreach ($line as $col_value) {
echo "\t\t$col_value \n";
}
echo "\t \n";
}
echo "\n";
// Free resultset
mysql_free_result($result);
// Closing connection
mysql_close($link);
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
MySQL Functions
Notes
Note:
Most MySQL functions accept link_identifier as the last optional
parameter. If it is not provided, last opened connection is used. If it
doesn't exist, connection is tried to establish with default parameters
defined in php.ini. If it is not successful, functions return FALSE.
----------------------------------------------------------------------
mysql_affected_rows
(PHP 4, PHP 5)
mysql_affected_rows - Get number of affected rows in previous MySQL
operation
Description
int mysql_affected_rows ([ resource $link_identifier ] )
Get the number of affected rows by the last INSERT, UPDATE, REPLACE or
DELETE query associated with link_identifier.
Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
Returns the number of affected rows on success, and -1 if the last query
failed.
If the last query was a DELETE query with no WHERE clause, all of the
records will have been deleted from the table but this function will
return zero with MySQL versions prior to 4.1.2.
When using UPDATE, MySQL will not update columns where the new value is
the same as the old value. This creates the possibility that
mysql_affected_rows() may not actually equal the number of rows matched,
only the number of rows that were literally affected by the query.
The REPLACE statement first deletes the record with the same primary key
and then inserts the new record. This function returns the number of
deleted records plus the number of inserted records.
Examples
Example #1 mysql_affected_rows() example
The above example will output something similar to:
Records deleted: 10
Records deleted: 0
Example #2 mysql_affected_rows() example using transactions
The above example will output something similar to:
Updated Records: 10
Notes
Note: Transactions
If you are using transactions, you need to call mysql_affected_rows()
after your INSERT, UPDATE, or DELETE query, not after the COMMIT.
Note: SELECT Statements
To retrieve the number of rows returned by a SELECT, it is possible to
use mysql_num_rows().
Note: Cascaded Foreign Keys
mysql_affected_rows() does not count rows affected implicitly through
the use of ON DELETE CASCADE and/or ON UPDATE CASCADE in foreign key
constraints.
See Also
* mysql_num_rows() - Get number of rows in result
* mysql_info() - Get information about the most recent query
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_client_encoding
(PHP 4 >= 4.3.0, PHP 5)
mysql_client_encoding - Returns the name of the character set
Description
string mysql_client_encoding ([ resource $link_identifier ] )
Retrieves the character_set variable from MySQL.
Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
Returns the default character set name for the current connection.
Examples
Example #1 mysql_client_encoding() example
The above example will output something similar to:
The current character set is: latin1
See Also
* mysql_set_charset() - Sets the client character set
* mysql_real_escape_string() - Escapes special characters in a string
for use in an SQL statement
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_close
(PHP 4, PHP 5)
mysql_close - Close MySQL connection
Description
bool mysql_close ([ resource $link_identifier ] )
mysql_close() closes the non-persistent connection to the MySQL server
that's associated with the specified link identifier. If link_identifier
isn't specified, the last opened link is used.
Using mysql_close() isn't usually necessary, as non-persistent open links
are automatically closed at the end of the script's execution. See also
freeing resources.
Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 mysql_close() example
The above example will output:
Connected successfully
Notes
Note:
mysql_close() will not close persistent links created by
mysql_pconnect().
See Also
* mysql_connect() - Open a connection to a MySQL Server
* mysql_free_result() - Free result memory
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_connect
(PHP 4, PHP 5)
mysql_connect - Open a connection to a MySQL Server
Description
resource mysql_connect ([ string $server = ini_get("mysql.default_host")
[, string $username = ini_get("mysql.default_user") [, string $password =
ini_get("mysql.default_password") [, bool $new_link = false [, int
$client_flags = 0 ]]]]] )
Opens or reuses a connection to a MySQL server.
Parameters
server
The MySQL server. It can also include a port number. e.g.
"hostname:port" or a path to a local socket e.g.
":/path/to/socket" for the localhost.
If the PHP directive mysql.default_host is undefined (default),
then the default value is 'localhost:3306'. In SQL safe mode, this
parameter is ignored and value 'localhost:3306' is always used.
username
The username. Default value is defined by mysql.default_user. In
SQL safe mode, this parameter is ignored and the name of the user
that owns the server process is used.
password
The password. Default value is defined by mysql.default_password.
In SQL safe mode, this parameter is ignored and empty password is
used.
new_link
If a second call is made to mysql_connect() with the same
arguments, no new link will be established, but instead, the link
identifier of the already opened link will be returned. The
new_link parameter modifies this behavior and makes
mysql_connect() always open a new link, even if mysql_connect()
was called before with the same parameters. In SQL safe mode, this
parameter is ignored.
client_flags
The client_flags parameter can be a combination of the following
constants: 128 (enable LOAD DATA LOCAL handling),
MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE
or MYSQL_CLIENT_INTERACTIVE. Read the section about MySQL client
constants for further information. In SQL safe mode, this
parameter is ignored.
Return Values
Returns a MySQL link identifier on success or FALSE on failure.
Changelog
Version Description
4.3.0 Added the client_flags parameter.
4.2.0 Added the new_link parameter.
Examples
Example #1 mysql_connect() example
Example #2 mysql_connect() example using hostname:port syntax
Example #3 mysql_connect() example using ":/path/to/socket" syntax
Notes
Note:
Whenever you specify "localhost" or "localhost:port" as server, the
MySQL client library will override this and try to connect to a local
socket (named pipe on Windows). If you want to use TCP/IP, use
"127.0.0.1" instead of "localhost". If the MySQL client library tries to
connect to the wrong local socket, you should set the correct path as in
your PHP configuration and leave the server field blank.
Note:
The link to the server will be closed as soon as the execution of the
script ends, unless it's closed earlier by explicitly calling
mysql_close().
Note:
You can suppress the error message on failure by prepending a @ to the
function name.
Note:
Error "Can't create TCP/IP socket (10106)" usually means that the
variables_order configure directive doesn't contain character E. On
Windows, if the environment is not copied the SYSTEMROOT environment
variable won't be available and PHP will have problems loading Winsock.
See Also
* mysql_pconnect() - Open a persistent connection to a MySQL server
* mysql_close() - Close MySQL connection
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_create_db
(PHP 4, PHP 5)
mysql_create_db - Create a MySQL database
Description
bool mysql_create_db ( string $database_name [, resource $link_identifier
] )
mysql_create_db() attempts to create a new database on the server
associated with the specified link identifier.
Parameters
database_name
The name of the database being created.
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 mysql_create_db() alternative example
The function mysql_create_db() is deprecated. It is preferable to use
mysql_query() to issue an sql CREATE DATABASE statement instead.
The above example will output something similar to:
Database my_db created successfully
Notes
Note:
For backward compatibility, the following deprecated alias may be used:
mysql_createdb()
Note:
This function will not be available if the MySQL extension was built
against a MySQL 4.x client library.
See Also
* mysql_query() - Send a MySQL query
* mysql_select_db() - Select a MySQL database
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_data_seek
(PHP 4, PHP 5)
mysql_data_seek - Move internal result pointer
Description
bool mysql_data_seek ( resource $result , int $row_number )
mysql_data_seek() moves the internal row pointer of the MySQL result
associated with the specified result identifier to point to the specified
row number. The next call to a MySQL fetch function, such as
mysql_fetch_assoc(), would return that row.
row_number starts at 0. The row_number should be a value in the range from
0 to mysql_num_rows() - 1. However if the result set is empty
(mysql_num_rows() == 0), a seek to 0 will fail with a E_WARNING and
mysql_data_seek() will return FALSE.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mysql_query().
row_number
The desired row number of the new result pointer.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 mysql_data_seek() example
= 0; $i--) {
if (!mysql_data_seek($result, $i)) {
echo "Cannot seek to row $i: " . mysql_error() . "\n";
continue;
}
if (!($row = mysql_fetch_assoc($result))) {
continue;
}
echo $row['last_name'] . ' ' . $row['first_name'] . " \n";
}
mysql_free_result($result);
?>
Notes
Note:
The function mysql_data_seek() can be used in conjunction only with
mysql_query(), not with mysql_unbuffered_query().
See Also
* mysql_query() - Send a MySQL query
* mysql_num_rows() - Get number of rows in result
* mysql_fetch_row() - Get a result row as an enumerated array
* mysql_fetch_assoc() - Fetch a result row as an associative array
* mysql_fetch_array() - Fetch a result row as an associative array, a
numeric array, or both
* mysql_fetch_object() - Fetch a result row as an object
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_db_name
(PHP 4, PHP 5)
mysql_db_name - Retrieves database name from the call to mysql_list_dbs()
Description
string mysql_db_name ( resource $result , int $row [, mixed $field ] )
Retrieve the database name from a call to mysql_list_dbs().
Parameters
result
The result pointer from a call to mysql_list_dbs().
row
The index into the result set.
field
The field name.
Return Values
Returns the database name on success, and FALSE on failure. If FALSE is
returned, use mysql_error() to determine the nature of the error.
Examples
Example #1 mysql_db_name() example
Notes
Note:
For backward compatibility, the following deprecated alias may be used:
mysql_dbname()
See Also
* mysql_list_dbs() - List databases available on a MySQL server
* mysql_tablename() - Get table name of field
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_db_query
(PHP 4, PHP 5)
mysql_db_query - Selects a database and executes a query on it
Description
resource mysql_db_query ( string $database , string $query [, resource
$link_identifier ] )
mysql_db_query() selects a database, and executes a query on it.
Warning
This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature
is highly discouraged.
Parameters
database
The name of the database that will be selected.
query
The MySQL query.
Data inside the query should be properly escaped.
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
Returns a positive MySQL result resource to the query result, or FALSE on
error. The function also returns TRUE/FALSE for INSERT/UPDATE/DELETE
queries to indicate success/failure.
Changelog
Version Description
5.3.0 This function now throws an E_DEPRECATED notice.
4.0.6 This function is deprecated, do not use this function. Use
mysql_select_db() and mysql_query() instead.
Examples
Example #1 mysql_db_query() alternative example
Notes
Note:
Be aware that this function does NOT switch back to the database you
were connected before. In other words, you can't use this function to
temporarily run a sql query on another database, you would have to
manually switch back. Users are strongly encouraged to use the
database.table syntax in their sql queries or mysql_select_db() instead
of this function.
See Also
* mysql_query() - Send a MySQL query
* mysql_select_db() - Select a MySQL database
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_drop_db
(PHP 4, PHP 5)
mysql_drop_db - Drop (delete) a MySQL database
Description
bool mysql_drop_db ( string $database_name [, resource $link_identifier ]
)
mysql_drop_db() attempts to drop (remove) an entire database from the
server associated with the specified link identifier. This function is
deprecated, it is preferable to use mysql_query() to issue an sql DROP
DATABASE statement instead.
Parameters
database_name
The name of the database that will be deleted.
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 mysql_drop_db() alternative example
Notes
Warning
This function will not be available if the MySQL extension was built
against a MySQL 4.x client library.
Note:
For backward compatibility, the following deprecated alias may be used:
mysql_dropdb()
See Also
* mysql_query() - Send a MySQL query
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_errno
(PHP 4, PHP 5)
mysql_errno - Returns the numerical value of the error message from
previous MySQL operation
Description
int mysql_errno ([ resource $link_identifier ] )
Returns the error number from the last MySQL function.
Errors coming back from the MySQL database backend no longer issue
warnings. Instead, use mysql_errno() to retrieve the error code. Note that
this function only returns the error code from the most recently executed
MySQL function (not including mysql_error() and mysql_errno()), so if you
want to use it, make sure you check the value before calling another MySQL
function.
Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
Returns the error number from the last MySQL function, or 0 (zero) if no
error occurred.
Examples
Example #1 mysql_errno() example
The above example will output something similar to:
1049: Unknown database 'nonexistentdb'
1146: Table 'kossu.nonexistenttable' doesn't exist
See Also
* mysql_error() - Returns the text of the error message from previous
MySQL operation
* >> MySQL error codes
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_error
(PHP 4, PHP 5)
mysql_error - Returns the text of the error message from previous MySQL
operation
Description
string mysql_error ([ resource $link_identifier ] )
Returns the error text from the last MySQL function. Errors coming back
from the MySQL database backend no longer issue warnings. Instead, use
mysql_error() to retrieve the error text. Note that this function only
returns the error text from the most recently executed MySQL function (not
including mysql_error() and mysql_errno()), so if you want to use it, make
sure you check the value before calling another MySQL function.
Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
Returns the error text from the last MySQL function, or '' (empty string)
if no error occurred.
Examples
Example #1 mysql_error() example
The above example will output something similar to:
1049: Unknown database 'nonexistentdb'
1146: Table 'kossu.nonexistenttable' doesn't exist
See Also
* mysql_errno() - Returns the numerical value of the error message from
previous MySQL operation
* >> MySQL error codes
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_escape_string
(PHP 4 >= 4.0.3, PHP 5)
mysql_escape_string - Escapes a string for use in a mysql_query
Description
string mysql_escape_string ( string $unescaped_string )
This function will escape the unescaped_string, so that it is safe to
place it in a mysql_query(). This function is deprecated.
This function is identical to mysql_real_escape_string() except that
mysql_real_escape_string() takes a connection handler and escapes the
string according to the current character set. mysql_escape_string() does
not take a connection argument and does not respect the current charset
setting.
Warning
This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature
is highly discouraged.
Parameters
unescaped_string
The string that is to be escaped.
Return Values
Returns the escaped string.
Changelog
Version Description
5.3.0 This function now throws an E_DEPRECATED notice.
4.3.0 This function became deprecated, do not use this function.
Instead, use mysql_real_escape_string().
Examples
Example #1 mysql_escape_string() example
The above example will output:
Escaped string: Zak\'s Laptop
Notes
Note:
mysql_escape_string() does not escape % and _.
See Also
* mysql_real_escape_string() - Escapes special characters in a string
for use in an SQL statement
* addslashes() - Quote string with slashes
* The magic_quotes_gpc directive.
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_fetch_array
(PHP 4, PHP 5)
mysql_fetch_array - Fetch a result row as an associative array, a numeric
array, or both
Description
array mysql_fetch_array ( resource $result [, int $result_type =
MYSQL_BOTH ] )
Returns an array that corresponds to the fetched row and moves the
internal data pointer ahead.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mysql_query().
result_type
The type of array that is to be fetched. It's a constant and can
take the following values: MYSQL_ASSOC, MYSQL_NUM, and MYSQL_BOTH.
Return Values
Returns an array of strings that corresponds to the fetched row, or FALSE
if there are no more rows. The type of returned array depends on how
result_type is defined. By using MYSQL_BOTH (default), you'll get an array
with both associative and number indices. Using MYSQL_ASSOC, you only get
associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you
only get number indices (as mysql_fetch_row() works).
If two or more columns of the result have the same field names, the last
column will take precedence. To access the other column(s) of the same
name, you must use the numeric index of the column or make an alias for
the column. For aliased columns, you cannot access the contents with the
original column name.
Examples
Example #1 Query with aliased duplicate field names
SELECT table1.field AS foo, table2.field AS bar FROM table1, table2
Example #2 mysql_fetch_array() with MYSQL_NUM
Example #3 mysql_fetch_array() with MYSQL_ASSOC
Example #4 mysql_fetch_array() with MYSQL_BOTH
Notes
Note: Performance
An important thing to note is that using mysql_fetch_array() is not
significantly slower than using mysql_fetch_row(), while it provides a
significant added value.
Note: Field names returned by this function are case-sensitive.
Note: This function sets NULL fields to the PHP NULL value.
See Also
* mysql_fetch_row() - Get a result row as an enumerated array
* mysql_fetch_assoc() - Fetch a result row as an associative array
* mysql_data_seek() - Move internal result pointer
* mysql_query() - Send a MySQL query
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_fetch_assoc
(PHP 4 >= 4.0.3, PHP 5)
mysql_fetch_assoc - Fetch a result row as an associative array
Description
array mysql_fetch_assoc ( resource $result )
Returns an associative array that corresponds to the fetched row and moves
the internal data pointer ahead. mysql_fetch_assoc() is equivalent to
calling mysql_fetch_array() with MYSQL_ASSOC for the optional second
parameter. It only returns an associative array.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mysql_query().
Return Values
Returns an associative array of strings that corresponds to the fetched
row, or FALSE if there are no more rows.
If two or more columns of the result have the same field names, the last
column will take precedence. To access the other column(s) of the same
name, you either need to access the result with numeric indices by using
mysql_fetch_row() or add alias names. See the example at the
mysql_fetch_array() description about aliases.
Examples
Example #1 An expanded mysql_fetch_assoc() example
Notes
Note: Performance
An important thing to note is that using mysql_fetch_assoc() is not
significantly slower than using mysql_fetch_row(), while it provides a
significant added value.
Note: Field names returned by this function are case-sensitive.
Note: This function sets NULL fields to the PHP NULL value.
See Also
* mysql_fetch_row() - Get a result row as an enumerated array
* mysql_fetch_array() - Fetch a result row as an associative array, a
numeric array, or both
* mysql_data_seek() - Move internal result pointer
* mysql_query() - Send a MySQL query
* mysql_error() - Returns the text of the error message from previous
MySQL operation
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_fetch_field
(PHP 4, PHP 5)
mysql_fetch_field - Get column information from a result and return as an
object
Description
object mysql_fetch_field ( resource $result [, int $field_offset = 0 ] )
Returns an object containing field information. This function can be used
to obtain information about fields in the provided query result.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mysql_query().
field_offset
The numerical field offset. If the field offset is not specified,
the next field that was not yet retrieved by this function is
retrieved. The field_offset starts at 0.
Return Values
Returns an object containing field information. The properties of the
object are:
* name - column name
* table - name of the table the column belongs to
* max_length - maximum length of the column
* not_null - 1 if the column cannot be NULL
* primary_key - 1 if the column is a primary key
* unique_key - 1 if the column is a unique key
* multiple_key - 1 if the column is a non-unique key
* numeric - 1 if the column is numeric
* blob - 1 if the column is a BLOB
* type - the type of the column
* unsigned - 1 if the column is unsigned
* zerofill - 1 if the column is zero-filled
Examples
Example #1 mysql_fetch_field() example
\n";
$meta = mysql_fetch_field($result, $i);
if (!$meta) {
echo "No information available \n";
}
echo "
blob: $meta->blob
max_length: $meta->max_length
multiple_key: $meta->multiple_key
name: $meta->name
not_null: $meta->not_null
numeric: $meta->numeric
primary_key: $meta->primary_key
table: $meta->table
type: $meta->type
unique_key: $meta->unique_key
unsigned: $meta->unsigned
zerofill: $meta->zerofill
";
$i++;
}
mysql_free_result($result);
?>
Notes
Note: Field names returned by this function are case-sensitive.
See Also
* mysql_field_seek() - Set result pointer to a specified field offset
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_fetch_lengths
(PHP 4, PHP 5)
mysql_fetch_lengths - Get the length of each output in a result
Description
array mysql_fetch_lengths ( resource $result )
Returns an array that corresponds to the lengths of each field in the last
row fetched by MySQL.
mysql_fetch_lengths() stores the lengths of each result column in the last
row returned by mysql_fetch_row(), mysql_fetch_assoc(),
mysql_fetch_array(), and mysql_fetch_object() in an array, starting at
offset 0.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mysql_query().
Return Values
An array of lengths on success or FALSE on failure.
Examples
Example #1 A mysql_fetch_lengths() example
The above example will output something similar to:
Array
(
[id] => 42
[email] => user@example.com
)
Array
(
[0] => 2
[1] => 16
)
See Also
* mysql_field_len() - Returns the length of the specified field
* mysql_fetch_row() - Get a result row as an enumerated array
* strlen() - Get string length
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_fetch_object
(PHP 4, PHP 5)
mysql_fetch_object - Fetch a result row as an object
Description
object mysql_fetch_object ( resource $result [, string $class_name [,
array $params ]] )
Returns an object with properties that correspond to the fetched row and
moves the internal data pointer ahead.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mysql_query().
class_name
The name of the class to instantiate, set the properties of and
return. If not specified, a stdClass object is returned.
params
An optional array of parameters to pass to the constructor for
class_name objects.
Return Values
Returns an object with string properties that correspond to the fetched
row, or FALSE if there are no more rows.
Changelog
Version Description
5.0.0 Added the ability to return as a different object.
Examples
Example #1 mysql_fetch_object() example
user_id;
echo $row->fullname;
}
mysql_free_result($result);
?>
Example #2 mysql_fetch_object() example
Notes
Note: Performance
Speed-wise, the function is identical to mysql_fetch_array(), and almost
as quick as mysql_fetch_row() (the difference is insignificant).
Note:
mysql_fetch_object() is similar to mysql_fetch_array(), with one
difference - an object is returned, instead of an array. Indirectly,
that means that you can only access the data by the field names, and not
by their offsets (numbers are illegal property names).
Note: Field names returned by this function are case-sensitive.
Note: This function sets NULL fields to the PHP NULL value.
See Also
* mysql_fetch_array() - Fetch a result row as an associative array, a
numeric array, or both
* mysql_fetch_assoc() - Fetch a result row as an associative array
* mysql_fetch_row() - Get a result row as an enumerated array
* mysql_data_seek() - Move internal result pointer
* mysql_query() - Send a MySQL query
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_fetch_row
(PHP 4, PHP 5)
mysql_fetch_row - Get a result row as an enumerated array
Description
array mysql_fetch_row ( resource $result )
Returns a numerical array that corresponds to the fetched row and moves
the internal data pointer ahead.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mysql_query().
Return Values
Returns an numerical array of strings that corresponds to the fetched row,
or FALSE if there are no more rows.
mysql_fetch_row() fetches one row of data from the result associated with
the specified result identifier. The row is returned as an array. Each
result column is stored in an array offset, starting at offset 0.
Examples
Example #1 Fetching one row with mysql_fetch_row()
Notes
Note: This function sets NULL fields to the PHP NULL value.
See Also
* mysql_fetch_array() - Fetch a result row as an associative array, a
numeric array, or both
* mysql_fetch_assoc() - Fetch a result row as an associative array
* mysql_fetch_object() - Fetch a result row as an object
* mysql_data_seek() - Move internal result pointer
* mysql_fetch_lengths() - Get the length of each output in a result
* mysql_result() - Get result data
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_field_flags
(PHP 4, PHP 5)
mysql_field_flags - Get the flags associated with the specified field in a
result
Description
string mysql_field_flags ( resource $result , int $field_offset )
mysql_field_flags() returns the field flags of the specified field. The
flags are reported as a single word per flag separated by a single space,
so that you can split the returned value using explode().
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mysql_query().
field_offset
The numerical field offset. The field_offset starts at 0. If
field_offset does not exist, an error of level E_WARNING is also
issued.
Return Values
Returns a string of flags associated with the result or FALSE on failure.
The following flags are reported, if your version of MySQL is current
enough to support them: "not_null", "primary_key", "unique_key",
"multiple_key", "blob", "unsigned", "zerofill", "binary", "enum",
"auto_increment" and "timestamp".
Examples
Example #1 A mysql_field_flags() example
The above example will output something similar to:
not_null primary_key auto_increment
Array
(
[0] => not_null
[1] => primary_key
[2] => auto_increment
)
Notes
Note:
For backward compatibility, the following deprecated alias may be used:
mysql_fieldflags()
See Also
* mysql_field_type() - Get the type of the specified field in a result
* mysql_field_len() - Returns the length of the specified field
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_field_len
(PHP 4, PHP 5)
mysql_field_len - Returns the length of the specified field
Description
int mysql_field_len ( resource $result , int $field_offset )
mysql_field_len() returns the length of the specified field.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mysql_query().
field_offset
The numerical field offset. The field_offset starts at 0. If
field_offset does not exist, an error of level E_WARNING is also
issued.
Return Values
The length of the specified field index on success or FALSE on failure.
Examples
Example #1 mysql_field_len() example
Notes
Note:
For backward compatibility, the following deprecated alias may be used:
mysql_fieldlen()
See Also
* mysql_fetch_lengths() - Get the length of each output in a result
* strlen() - Get string length
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_field_name
(PHP 4, PHP 5)
mysql_field_name - Get the name of the specified field in a result
Description
string mysql_field_name ( resource $result , int $field_offset )
mysql_field_name() returns the name of the specified field index.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mysql_query().
field_offset
The numerical field offset. The field_offset starts at 0. If
field_offset does not exist, an error of level E_WARNING is also
issued.
Return Values
The name of the specified field index on success or FALSE on failure.
Examples
Example #1 mysql_field_name() example
The above example will output:
user_id
password
Notes
Note: Field names returned by this function are case-sensitive.
Note:
For backward compatibility, the following deprecated alias may be used:
mysql_fieldname()
See Also
* mysql_field_type() - Get the type of the specified field in a result
* mysql_field_len() - Returns the length of the specified field
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_field_seek
(PHP 4, PHP 5)
mysql_field_seek - Set result pointer to a specified field offset
Description
bool mysql_field_seek ( resource $result , int $field_offset )
Seeks to the specified field offset. If the next call to
mysql_fetch_field() doesn't include a field offset, the field offset
specified in mysql_field_seek() will be returned.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mysql_query().
field_offset
The numerical field offset. The field_offset starts at 0. If
field_offset does not exist, an error of level E_WARNING is also
issued.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* mysql_fetch_field() - Get column information from a result and return
as an object
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_field_table
(PHP 4, PHP 5)
mysql_field_table - Get name of the table the specified field is in
Description
string mysql_field_table ( resource $result , int $field_offset )
Returns the name of the table that the specified field is in.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mysql_query().
field_offset
The numerical field offset. The field_offset starts at 0. If
field_offset does not exist, an error of level E_WARNING is also
issued.
Return Values
The name of the table on success.
Examples
Example #1 A mysql_field_table() example
Notes
Note:
For backward compatibility, the following deprecated alias may be used:
mysql_fieldtable()
See Also
* mysql_list_tables() - List tables in a MySQL database
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_field_type
(PHP 4, PHP 5)
mysql_field_type - Get the type of the specified field in a result
Description
string mysql_field_type ( resource $result , int $field_offset )
mysql_field_type() is similar to the mysql_field_name() function. The
arguments are identical, but the field type is returned instead.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mysql_query().
field_offset
The numerical field offset. The field_offset starts at 0. If
field_offset does not exist, an error of level E_WARNING is also
issued.
Return Values
The returned field type will be one of "int", "real", "string", "blob",
and others as detailed in the >> MySQL documentation.
Examples
Example #1 mysql_field_type() example
The above example will output something similar to:
Your 'func' table has 4 fields and 1 record(s)
The table has the following fields:
string name 64 not_null primary_key binary
int ret 1 not_null
string dl 128 not_null
string type 9 not_null enum
Notes
Note:
For backward compatibility, the following deprecated alias may be used:
mysql_fieldtype()
See Also
* mysql_field_name() - Get the name of the specified field in a result
* mysql_field_len() - Returns the length of the specified field
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_free_result
(PHP 4, PHP 5)
mysql_free_result - Free result memory
Description
bool mysql_free_result ( resource $result )
mysql_free_result() will free all memory associated with the result
identifier result.
mysql_free_result() only needs to be called if you are concerned about how
much memory is being used for queries that return large result sets. All
associated result memory is automatically freed at the end of the script's
execution.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mysql_query().
Return Values
Returns TRUE on success or FALSE on failure.
If a non-resource is used for the result, an error of level E_WARNING will
be emitted. It's worth noting that mysql_query() only returns a resource
for SELECT, SHOW, EXPLAIN, and DESCRIBE queries.
Examples
Example #1 A mysql_free_result() example
Notes
Note:
For backward compatibility, the following deprecated alias may be used:
mysql_freeresult()
See Also
* mysql_query() - Send a MySQL query
* is_resource() - Finds whether a variable is a resource
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_get_client_info
(PHP 4 >= 4.0.5, PHP 5)
mysql_get_client_info - Get MySQL client info
Description
string mysql_get_client_info ( void )
mysql_get_client_info() returns a string that represents the client
library version.
Return Values
The MySQL client version.
Examples
Example #1 mysql_get_client_info() example
The above example will output something similar to:
MySQL client info: 3.23.39
See Also
* mysql_get_host_info() - Get MySQL host info
* mysql_get_proto_info() - Get MySQL protocol info
* mysql_get_server_info() - Get MySQL server info
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_get_host_info
(PHP 4 >= 4.0.5, PHP 5)
mysql_get_host_info - Get MySQL host info
Description
string mysql_get_host_info ([ resource $link_identifier ] )
Describes the type of connection in use for the connection, including the
server host name.
Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
Returns a string describing the type of MySQL connection in use for the
connection or FALSE on failure.
Examples
Example #1 mysql_get_host_info() example
The above example will output something similar to:
MySQL host info: Localhost via UNIX socket
See Also
* mysql_get_client_info() - Get MySQL client info
* mysql_get_proto_info() - Get MySQL protocol info
* mysql_get_server_info() - Get MySQL server info
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_get_proto_info
(PHP 4 >= 4.0.5, PHP 5)
mysql_get_proto_info - Get MySQL protocol info
Description
int mysql_get_proto_info ([ resource $link_identifier ] )
Retrieves the MySQL protocol.
Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
Returns the MySQL protocol on success or FALSE on failure.
Examples
Example #1 mysql_get_proto_info() example
The above example will output something similar to:
MySQL protocol version: 10
See Also
* mysql_get_client_info() - Get MySQL client info
* mysql_get_host_info() - Get MySQL host info
* mysql_get_server_info() - Get MySQL server info
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_get_server_info
(PHP 4 >= 4.0.5, PHP 5)
mysql_get_server_info - Get MySQL server info
Description
string mysql_get_server_info ([ resource $link_identifier ] )
Retrieves the MySQL server version.
Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
Returns the MySQL server version on success or FALSE on failure.
Examples
Example #1 mysql_get_server_info() example
The above example will output something similar to:
MySQL server version: 4.0.1-alpha
See Also
* mysql_get_client_info() - Get MySQL client info
* mysql_get_host_info() - Get MySQL host info
* mysql_get_proto_info() - Get MySQL protocol info
* phpversion() - Gets the current PHP version
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_info
(PHP 4 >= 4.3.0, PHP 5)
mysql_info - Get information about the most recent query
Description
string mysql_info ([ resource $link_identifier ] )
Returns detailed information about the last query.
Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
Returns information about the statement on success, or FALSE on failure.
See the example below for which statements provide information, and what
the returned value may look like. Statements that are not listed will
return FALSE.
Examples
Example #1 Relevant MySQL Statements
Statements that return string values. The numbers are only for
illustrating purpose; their values will correspond to the query.
INSERT INTO ... SELECT ...
String format: Records: 23 Duplicates: 0 Warnings: 0
INSERT INTO ... VALUES (...),(...),(...)...
String format: Records: 37 Duplicates: 0 Warnings: 0
LOAD DATA INFILE ...
String format: Records: 42 Deleted: 0 Skipped: 0 Warnings: 0
ALTER TABLE
String format: Records: 60 Duplicates: 0 Warnings: 0
UPDATE
String format: Rows matched: 65 Changed: 65 Warnings: 0
Notes
Note:
mysql_info() returns a non-FALSE value for the INSERT ... VALUES
statement only if multiple value lists are specified in the statement.
See Also
* mysql_affected_rows() - Get number of affected rows in previous MySQL
operation
* mysql_insert_id() - Get the ID generated in the last query
* mysql_stat() - Get current system status
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_insert_id
(PHP 4, PHP 5)
mysql_insert_id - Get the ID generated in the last query
Description
int mysql_insert_id ([ resource $link_identifier ] )
Retrieves the ID generated for an AUTO_INCREMENT column by the previous
query (usually INSERT).
Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
The ID generated for an AUTO_INCREMENT column by the previous query on
success, 0 if the previous query does not generate an AUTO_INCREMENT
value, or FALSE if no MySQL connection was established.
Examples
Example #1 mysql_insert_id() example
Notes
Caution
mysql_insert_id() will convert the return type of the native MySQL C API
function mysql_insert_id() to a type of long (named int in PHP). If your
AUTO_INCREMENT column has a column type of BIGINT (64 bits) the conversion
may result in an incorrect value. Instead, use the internal MySQL SQL
function LAST_INSERT_ID() in an SQL query. For more information about
PHP's maximum integer values, please see the integer documentation.
Note:
Because mysql_insert_id() acts on the last performed query, be sure to
call mysql_insert_id() immediately after the query that generates the
value.
Note:
The value of the MySQL SQL function LAST_INSERT_ID() always contains the
most recently generated AUTO_INCREMENT value, and is not reset between
queries.
See Also
* mysql_query() - Send a MySQL query
* mysql_info() - Get information about the most recent query
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_list_dbs
(PHP 4, PHP 5)
mysql_list_dbs - List databases available on a MySQL server
Description
resource mysql_list_dbs ([ resource $link_identifier ] )
Returns a result pointer containing the databases available from the
current mysql daemon.
Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
Returns a result pointer resource on success, or FALSE on failure. Use the
mysql_tablename() function to traverse this result pointer, or any
function for result tables, such as mysql_fetch_array().
Examples
Example #1 mysql_list_dbs() example
Database . "\n";
}
?>
The above example will output something similar to:
database1
database2
database3
Notes
Note:
For backward compatibility, the following deprecated alias may be used:
mysql_listdbs()
See Also
* mysql_db_name() - Retrieves database name from the call to
mysql_list_dbs
* mysql_select_db() - Select a MySQL database
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_list_fields
(PHP 4, PHP 5)
mysql_list_fields - List MySQL table fields
Description
resource mysql_list_fields ( string $database_name , string $table_name [,
resource $link_identifier ] )
Retrieves information about the given table name.
This function is deprecated. It is preferable to use mysql_query() to
issue an SQL SHOW COLUMNS FROM table [LIKE 'name'] statement instead.
Parameters
database_name
The name of the database that's being queried.
table_name
The name of the table that's being queried.
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
A result pointer resource on success, or FALSE on failure.
The returned result can be used with mysql_field_flags(),
mysql_field_len(), mysql_field_name() and mysql_field_type().
Examples
Example #1 Alternate to deprecated mysql_list_fields()
0) {
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
}
?>
The above example will output something similar to:
Array
(
[Field] => id
[Type] => int(7)
[Null] =>
[Key] => PRI
[Default] =>
[Extra] => auto_increment
)
Array
(
[Field] => email
[Type] => varchar(100)
[Null] =>
[Key] =>
[Default] =>
[Extra] =>
)
Notes
Note:
For backward compatibility, the following deprecated alias may be used:
mysql_listfields()
See Also
* mysql_field_flags() - Get the flags associated with the specified
field in a result
* mysql_info() - Get information about the most recent query
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_list_processes
(PHP 4 >= 4.3.0, PHP 5)
mysql_list_processes - List MySQL processes
Description
resource mysql_list_processes ([ resource $link_identifier ] )
Retrieves the current MySQL server threads.
Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
A result pointer resource on success or FALSE on failure.
Examples
Example #1 mysql_list_processes() example
The above example will output something similar to:
1 localhost test Processlist 0
4 localhost mysql sleep 5
See Also
* mysql_thread_id() - Return the current thread ID
* mysql_stat() - Get current system status
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_list_tables
(PHP 4, PHP 5)
mysql_list_tables - List tables in a MySQL database
Description
resource mysql_list_tables ( string $database [, resource $link_identifier
] )
Retrieves a list of table names from a MySQL database.
This function is deprecated. It is preferable to use mysql_query() to
issue an SQL SHOW TABLES [FROM db_name] [LIKE 'pattern'] statement
instead.
Parameters
database
The name of the database
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
A result pointer resource on success or FALSE on failure.
Use the mysql_tablename() function to traverse this result pointer, or any
function for result tables, such as mysql_fetch_array().
Changelog
Version Description
4.3.7 This function became deprecated.
Examples
Example #1 mysql_list_tables() alternative example
Notes
Note:
For backward compatibility, the following deprecated alias may be used:
mysql_listtables()
See Also
* mysql_list_dbs() - List databases available on a MySQL server
* mysql_tablename() - Get table name of field
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_num_fields
(PHP 4, PHP 5)
mysql_num_fields - Get number of fields in result
Description
int mysql_num_fields ( resource $result )
Retrieves the number of fields from a query.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mysql_query().
Return Values
Returns the number of fields in the result set resource on success or
FALSE on failure.
Examples
Example #1 A mysql_num_fields() example
Notes
Note:
For backward compatibility, the following deprecated alias may be used:
mysql_numfields()
See Also
* mysql_select_db() - Select a MySQL database
* mysql_query() - Send a MySQL query
* mysql_fetch_field() - Get column information from a result and return
as an object
* mysql_num_rows() - Get number of rows in result
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_num_rows
(PHP 4, PHP 5)
mysql_num_rows - Get number of rows in result
Description
int mysql_num_rows ( resource $result )
Retrieves the number of rows from a result set. This command is only valid
for statements like SELECT or SHOW that return an actual result set. To
retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or
DELETE query, use mysql_affected_rows().
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mysql_query().
Return Values
The number of rows in a result set on success or FALSE on failure.
Examples
Example #1 mysql_num_rows() example
Notes
Note:
If you use mysql_unbuffered_query(), mysql_num_rows() will not return
the correct value until all the rows in the result set have been
retrieved.
Note:
For backward compatibility, the following deprecated alias may be used:
mysql_numrows()
See Also
* mysql_affected_rows() - Get number of affected rows in previous MySQL
operation
* mysql_connect() - Open a connection to a MySQL Server
* mysql_data_seek() - Move internal result pointer
* mysql_select_db() - Select a MySQL database
* mysql_query() - Send a MySQL query
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_pconnect
(PHP 4, PHP 5)
mysql_pconnect - Open a persistent connection to a MySQL server
Description
resource mysql_pconnect ([ string $server = ini_get("mysql.default_host")
[, string $username = ini_get("mysql.default_user") [, string $password =
ini_get("mysql.default_password") [, int $client_flags ]]]] )
Establishes a persistent connection to a MySQL server.
mysql_pconnect() acts very much like mysql_connect() with two major
differences.
First, when connecting, the function would first try to find a
(persistent) link that's already open with the same host, username and
password. If one is found, an identifier for it will be returned instead
of opening a new connection.
Second, the connection to the SQL server will not be closed when the
execution of the script ends. Instead, the link will remain open for
future use (mysql_close() will not close links established by
mysql_pconnect()).
This type of link is therefore called 'persistent'.
Parameters
server
The MySQL server. It can also include a port number. e.g.
"hostname:port" or a path to a local socket e.g.
":/path/to/socket" for the localhost.
If the PHP directive mysql.default_host is undefined (default),
then the default value is 'localhost:3306'
username
The username. Default value is the name of the user that owns the
server process.
password
The password. Default value is an empty password.
client_flags
The client_flags parameter can be a combination of the following
constants: 128 (enable LOAD DATA LOCAL handling),
MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE
or MYSQL_CLIENT_INTERACTIVE.
Return Values
Returns a MySQL persistent link identifier on success, or FALSE on
failure.
Changelog
Version Description
4.3.0 Added the client_flags parameter.
Notes
Note:
Note, that these kind of links only work if you are using a module
version of PHP. See the Persistent Database Connections section for more
information.
Warning
Using persistent connections can require a bit of tuning of your Apache
and MySQL configurations to ensure that you do not exceed the number of
connections allowed by MySQL.
Note:
You can suppress the error message on failure by prepending a @ to the
function name.
See Also
* mysql_connect() - Open a connection to a MySQL Server
* Persistent Database Connections
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_ping
(PHP 4 >= 4.3.0, PHP 5)
mysql_ping - Ping a server connection or reconnect if there is no
connection
Description
bool mysql_ping ([ resource $link_identifier ] )
Checks whether or not the connection to the server is working. If it has
gone down, an automatic reconnection is attempted. This function can be
used by scripts that remain idle for a long while, to check whether or not
the server has closed the connection and reconnect if necessary.
Note:
Since MySQL 5.0.13, automatic reconnection feature is disabled.
Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
Returns TRUE if the connection to the server MySQL server is working,
otherwise FALSE.
Examples
Example #1 A mysql_ping() example
See Also
* mysql_thread_id() - Return the current thread ID
* mysql_list_processes() - List MySQL processes
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_query
(PHP 4, PHP 5)
mysql_query - Send a MySQL query
Description
resource mysql_query ( string $query [, resource $link_identifier ] )
mysql_query() sends a unique query (multiple queries are not supported) to
the currently active database on the server that's associated with the
specified link_identifier.
Parameters
query
An SQL query
The query string should not end with a semicolon. Data inside the
query should be properly escaped.
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning
resultset, mysql_query() returns a resource on success, or FALSE on error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc,
mysql_query() returns TRUE on success or FALSE on error.
The returned result resource should be passed to mysql_fetch_array(), and
other functions for dealing with result tables, to access the returned
data.
Use mysql_num_rows() to find out how many rows were returned for a SELECT
statement or mysql_affected_rows() to find out how many rows were affected
by a DELETE, INSERT, REPLACE, or UPDATE statement.
mysql_query() will also fail and return FALSE if the user does not have
permission to access the table(s) referenced by the query.
Examples
Example #1 Invalid Query
The following query is syntactically invalid, so mysql_query() fails and
returns FALSE.
Example #2 Valid Query
The following query is valid, so mysql_query() returns a resource.
See Also
* mysql_connect() - Open a connection to a MySQL Server
* mysql_error() - Returns the text of the error message from previous
MySQL operation
* mysql_real_escape_string() - Escapes special characters in a string
for use in an SQL statement
* mysql_result() - Get result data
* mysql_fetch_assoc() - Fetch a result row as an associative array
* mysql_unbuffered_query() - Send an SQL query to MySQL without fetching
and buffering the result rows.
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_real_escape_string
(PHP 4 >= 4.3.0, PHP 5)
mysql_real_escape_string - Escapes special characters in a string for use
in an SQL statement
Description
string mysql_real_escape_string ( string $unescaped_string [, resource
$link_identifier ] )
Escapes special characters in the unescaped_string, taking into account
the current character set of the connection so that it is safe to place it
in a mysql_query(). If binary data is to be inserted, this function must
be used.
mysql_real_escape_string() calls MySQL's library function
mysql_real_escape_string, which prepends backslashes to the following
characters: \x00, \n, \r, \, ', " and \x1a.
This function must always (with few exceptions) be used to make data safe
before sending a query to MySQL.
Parameters
unescaped_string
The string that is to be escaped.
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
Returns the escaped string, or FALSE on error.
Examples
Example #1 Simple mysql_real_escape_string() example
Example #2 An example SQL Injection Attack
The query sent to MySQL:
SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''
This would allow anyone to log in without a valid password.
Notes
Note:
A MySQL connection is required before using mysql_real_escape_string()
otherwise an error of level E_WARNING is generated, and FALSE is
returned. If link_identifier isn't defined, the last MySQL connection is
used.
Note:
If magic_quotes_gpc is enabled, first apply stripslashes() to the data.
Using this function on data which has already been escaped will escape
the data twice.
Note:
If this function is not used to escape data, the query is vulnerable to
SQL Injection Attacks.
Note: mysql_real_escape_string() does not escape % and _. These are
wildcards in MySQL if combined with LIKE, GRANT, or REVOKE.
See Also
* mysql_client_encoding() - Returns the name of the character set
* addslashes() - Quote string with slashes
* stripslashes() - Un-quotes a quoted string
* The magic_quotes_gpc directive
* The magic_quotes_runtime directive
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_result
(PHP 4, PHP 5)
mysql_result - Get result data
Description
string mysql_result ( resource $result , int $row [, mixed $field = 0 ] )
Retrieves the contents of one cell from a MySQL result set.
When working on large result sets, you should consider using one of the
functions that fetch an entire row (specified below). As these functions
return the contents of multiple cells in one function call, they're MUCH
quicker than mysql_result(). Also, note that specifying a numeric offset
for the field argument is much quicker than specifying a fieldname or
tablename.fieldname argument.
Parameters
result
The result resource that is being evaluated. This result comes
from a call to mysql_query().
row
The row number from the result that's being retrieved. Row numbers
start at 0.
field
The name or offset of the field being retrieved.
It can be the field's offset, the field's name, or the field's
table dot field name (tablename.fieldname). If the column name has
been aliased ('select foo as bar from...'), use the alias instead
of the column name. If undefined, the first field is retrieved.
Return Values
The contents of one cell from a MySQL result set on success, or FALSE on
failure.
Examples
Example #1 mysql_result() example
Notes
Note:
Calls to mysql_result() should not be mixed with calls to other
functions that deal with the result set.
See Also
* mysql_fetch_row() - Get a result row as an enumerated array
* mysql_fetch_array() - Fetch a result row as an associative array, a
numeric array, or both
* mysql_fetch_assoc() - Fetch a result row as an associative array
* mysql_fetch_object() - Fetch a result row as an object
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_select_db
(PHP 4, PHP 5)
mysql_select_db - Select a MySQL database
Description
bool mysql_select_db ( string $database_name [, resource $link_identifier
] )
Sets the current active database on the server that's associated with the
specified link identifier. Every subsequent call to mysql_query() will be
made on the active database.
Parameters
database_name
The name of the database that is to be selected.
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 mysql_select_db() example
Notes
Note:
For backward compatibility, the following deprecated alias may be used:
mysql_selectdb()
See Also
* mysql_connect() - Open a connection to a MySQL Server
* mysql_pconnect() - Open a persistent connection to a MySQL server
* mysql_query() - Send a MySQL query
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_set_charset
(PHP 5 >= 5.2.3)
mysql_set_charset - Sets the client character set
Description
bool mysql_set_charset ( string $charset [, resource $link_identifier ] )
Sets the default character set for the current connection.
Parameters
charset
A valid character set name.
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
Returns TRUE on success or FALSE on failure.
Notes
Note:
This function requires MySQL 5.0.7 or later.
Note:
This is the preferred way to change the charset. Using mysql_query() to
execute SET NAMES .. is not recommended.
See Also
* mysql_client_encoding() - Returns the name of the character set
* >> List of character sets that MySQL supports
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_stat
(PHP 4 >= 4.3.0, PHP 5)
mysql_stat - Get current system status
Description
string mysql_stat ([ resource $link_identifier ] )
mysql_stat() returns the current server status.
Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
Returns a string with the status for uptime, threads, queries, open
tables, flush tables and queries per second. For a complete list of other
status variables, you have to use the SHOW STATUS SQL command. If
link_identifier is invalid, NULL is returned.
Examples
Example #1 mysql_stat() example
The above example will output something similar to:
Array
(
[0] => Uptime: 5380
[1] => Threads: 2
[2] => Questions: 1321299
[3] => Slow queries: 0
[4] => Opens: 26
[5] => Flush tables: 1
[6] => Open tables: 17
[7] => Queries per second avg: 245.595
)
Example #2 Alternative mysql_stat() example
The above example will output something similar to:
back_log = 50
basedir = /usr/local/
bdb_cache_size = 8388600
bdb_log_buffer_size = 32768
bdb_home = /var/db/mysql/
bdb_max_lock = 10000
bdb_logdir =
bdb_shared_data = OFF
bdb_tmpdir = /var/tmp/
...
See Also
* mysql_get_server_info() - Get MySQL server info
* mysql_list_processes() - List MySQL processes
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_tablename
(PHP 4, PHP 5)
mysql_tablename - Get table name of field
Description
string mysql_tablename ( resource $result , int $i )
Retrieves the table name from a result.
This function is deprecated. It is preferable to use mysql_query() to
issue an SQL SHOW TABLES [FROM db_name] [LIKE 'pattern'] statement
instead.
Parameters
result
A result pointer resource that's returned from
mysql_list_tables().
i
The integer index (row/table number)
Return Values
The name of the table on success or FALSE on failure.
Use the mysql_tablename() function to traverse this result pointer, or any
function for result tables, such as mysql_fetch_array().
Examples
Example #1 mysql_tablename() example
Notes
Note:
The mysql_num_rows() function may be used to determine the number of
tables in the result pointer.
See Also
* mysql_list_tables() - List tables in a MySQL database
* mysql_field_table() - Get name of the table the specified field is in
* mysql_db_name() - Retrieves database name from the call to
mysql_list_dbs
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_thread_id
(PHP 4 >= 4.3.0, PHP 5)
mysql_thread_id - Return the current thread ID
Description
int mysql_thread_id ([ resource $link_identifier ] )
Retrieves the current thread ID. If the connection is lost, and a
reconnect with mysql_ping() is executed, the thread ID will change. This
means only retrieve the thread ID when needed.
Parameters
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
The thread ID on success or FALSE on failure.
Examples
Example #1 mysql_thread_id() example
The above example will output something similar to:
current thread id is 73
See Also
* mysql_ping() - Ping a server connection or reconnect if there is no
connection
* mysql_list_processes() - List MySQL processes
----------------------------------------------------------------------
----------------------------------------------------------------------
mysql_unbuffered_query
(PHP 4 >= 4.0.6, PHP 5)
mysql_unbuffered_query - Send an SQL query to MySQL without fetching and
buffering the result rows.
Description
resource mysql_unbuffered_query ( string $query [, resource
$link_identifier ] )
mysql_unbuffered_query() sends the SQL query query to MySQL without
automatically fetching and buffering the result rows as mysql_query()
does. This saves a considerable amount of memory with SQL queries that
produce large result sets, and you can start working on the result set
immediately after the first row has been retrieved as you don't have to
wait until the complete SQL query has been performed. To use
mysql_unbuffered_query() while multiple database connections are open, you
must specify the optional parameter link_identifier to identify which
connection you want to use.
Parameters
query
The SQL query to execute.
Data inside the query should be properly escaped.
link_identifier
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If no connection is found or established, an
E_WARNING level error is generated.
Return Values
For SELECT, SHOW, DESCRIBE or EXPLAIN statements, mysql_unbuffered_query()
returns a resource on success, or FALSE on error.
For other type of SQL statements, UPDATE, DELETE, DROP, etc,
mysql_unbuffered_query() returns TRUE on success or FALSE on error.
Notes
Note:
The benefits of mysql_unbuffered_query() come at a cost: you cannot use
mysql_num_rows() and mysql_data_seek() on a result set returned from
mysql_unbuffered_query(). You also have to fetch all result rows from an
unbuffered SQL query before you can send a new SQL query to MySQL.
See Also
* mysql_query() - Send a MySQL query
----------------------------------------------------------------------
Table of Contents
* mysql_affected_rows - Get number of affected rows in previous MySQL
operation
* mysql_client_encoding - Returns the name of the character set
* mysql_close - Close MySQL connection
* mysql_connect - Open a connection to a MySQL Server
* mysql_create_db - Create a MySQL database
* mysql_data_seek - Move internal result pointer
* mysql_db_name - Retrieves database name from the call to
mysql_list_dbs
* mysql_db_query - Selects a database and executes a query on it
* mysql_drop_db - Drop (delete) a MySQL database
* mysql_errno - Returns the numerical value of the error message from
previous MySQL operation
* mysql_error - Returns the text of the error message from previous
MySQL operation
* mysql_escape_string - Escapes a string for use in a mysql_query
* mysql_fetch_array - Fetch a result row as an associative array, a
numeric array, or both
* mysql_fetch_assoc - Fetch a result row as an associative array
* mysql_fetch_field - Get column information from a result and return as
an object
* mysql_fetch_lengths - Get the length of each output in a result
* mysql_fetch_object - Fetch a result row as an object
* mysql_fetch_row - Get a result row as an enumerated array
* mysql_field_flags - Get the flags associated with the specified field
in a result
* mysql_field_len - Returns the length of the specified field
* mysql_field_name - Get the name of the specified field in a result
* mysql_field_seek - Set result pointer to a specified field offset
* mysql_field_table - Get name of the table the specified field is in
* mysql_field_type - Get the type of the specified field in a result
* mysql_free_result - Free result memory
* mysql_get_client_info - Get MySQL client info
* mysql_get_host_info - Get MySQL host info
* mysql_get_proto_info - Get MySQL protocol info
* mysql_get_server_info - Get MySQL server info
* mysql_info - Get information about the most recent query
* mysql_insert_id - Get the ID generated in the last query
* mysql_list_dbs - List databases available on a MySQL server
* mysql_list_fields - List MySQL table fields
* mysql_list_processes - List MySQL processes
* mysql_list_tables - List tables in a MySQL database
* mysql_num_fields - Get number of fields in result
* mysql_num_rows - Get number of rows in result
* mysql_pconnect - Open a persistent connection to a MySQL server
* mysql_ping - Ping a server connection or reconnect if there is no
connection
* mysql_query - Send a MySQL query
* mysql_real_escape_string - Escapes special characters in a string for
use in an SQL statement
* mysql_result - Get result data
* mysql_select_db - Select a MySQL database
* mysql_set_charset - Sets the client character set
* mysql_stat - Get current system status
* mysql_tablename - Get table name of field
* mysql_thread_id - Return the current thread ID
* mysql_unbuffered_query - Send an SQL query to MySQL without fetching
and buffering the result rows.
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* MySQL extension overview example
* MySQL Functions
* mysql_affected_rows - Get number of affected rows in previous
MySQL operation
* mysql_client_encoding - Returns the name of the character set
* mysql_close - Close MySQL connection
* mysql_connect - Open a connection to a MySQL Server
* mysql_create_db - Create a MySQL database
* mysql_data_seek - Move internal result pointer
* mysql_db_name - Retrieves database name from the call to
mysql_list_dbs
* mysql_db_query - Selects a database and executes a query on it
* mysql_drop_db - Drop (delete) a MySQL database
* mysql_errno - Returns the numerical value of the error message
from previous MySQL operation
* mysql_error - Returns the text of the error message from previous
MySQL operation
* mysql_escape_string - Escapes a string for use in a mysql_query
* mysql_fetch_array - Fetch a result row as an associative array, a
numeric array, or both
* mysql_fetch_assoc - Fetch a result row as an associative array
* mysql_fetch_field - Get column information from a result and
return as an object
* mysql_fetch_lengths - Get the length of each output in a result
* mysql_fetch_object - Fetch a result row as an object
* mysql_fetch_row - Get a result row as an enumerated array
* mysql_field_flags - Get the flags associated with the specified
field in a result
* mysql_field_len - Returns the length of the specified field
* mysql_field_name - Get the name of the specified field in a
result
* mysql_field_seek - Set result pointer to a specified field offset
* mysql_field_table - Get name of the table the specified field is
in
* mysql_field_type - Get the type of the specified field in a
result
* mysql_free_result - Free result memory
* mysql_get_client_info - Get MySQL client info
* mysql_get_host_info - Get MySQL host info
* mysql_get_proto_info - Get MySQL protocol info
* mysql_get_server_info - Get MySQL server info
* mysql_info - Get information about the most recent query
* mysql_insert_id - Get the ID generated in the last query
* mysql_list_dbs - List databases available on a MySQL server
* mysql_list_fields - List MySQL table fields
* mysql_list_processes - List MySQL processes
* mysql_list_tables - List tables in a MySQL database
* mysql_num_fields - Get number of fields in result
* mysql_num_rows - Get number of rows in result
* mysql_pconnect - Open a persistent connection to a MySQL server
* mysql_ping - Ping a server connection or reconnect if there is no
connection
* mysql_query - Send a MySQL query
* mysql_real_escape_string - Escapes special characters in a string
for use in an SQL statement
* mysql_result - Get result data
* mysql_select_db - Select a MySQL database
* mysql_set_charset - Sets the client character set
* mysql_stat - Get current system status
* mysql_tablename - Get table name of field
* mysql_thread_id - Return the current thread ID
* mysql_unbuffered_query - Send an SQL query to MySQL without
fetching and buffering the result rows.
----------------------------------------------------------------------
----------------------------------------------------------------------
MySQL Improved Extension
----------------------------------------------------------------------
Introduction
The mysqli extension allows you to access the functionality provided by
MySQL 4.1 and above. More information about the MySQL Database server can
be found at >> http://www.mysql.com/
An overview of software available for using MySQL from PHP can be found at
Overview
Documentation for MySQL can be found at >> http://dev.mysql.com/doc/.
Parts of this documentation included from MySQL manual with permissions of
Oracle Corporation.
Examples
All examples in the mysqli documentation use the world database. The world
database can be found at >> http://downloads.mysql.com/docs/world.sql.gz
----------------------------------------------------------------------
----------------------------------------------------------------------
Overview
This section provides an introduction to the options available to you when
developing a PHP application that needs to interact with a MySQL database.
What is an API?
An Application Programming Interface, or API, defines the classes,
methods, functions and variables that your application will need to call
in order to carry out its desired task. In the case of PHP applications
that need to communicate with databases the necessary APIs are usually
exposed via PHP extensions.
APIs can be procedural or object-oriented. With a procedural API you call
functions to carry out tasks, with the object-oriented API you instantiate
classes and then call methods on the resulting objects. Of the two the
latter is usually the preferred interface, as it is more modern and leads
to better organised code.
When writing PHP applications that need to connect to the MySQL server
there are several API options available. This document discusses what is
available and how to select the best solution for your application.
What is a Connector?
In the MySQL documentation, the term connector refers to a piece of
software that allows your application to connect to the MySQL database
server. MySQL provides connectors for a variety of languages, including
PHP.
If your PHP application needs to communicate with a database server you
will need to write PHP code to perform such activities as connecting to
the database server, querying the database and other database-related
functions. Software is required to provide the API that your PHP
application will use, and also handle the communication between your
application and the database server, possibly using other intermediate
libraries where necessary. This software is known generically as a
connector, as it allows your application to connect to a database server.
What is a Driver?
A driver is a piece of software designed to communicate with a specific
type of database server. The driver may also call a library, such as the
MySQL Client Library or the MySQL Native Driver. These libraries implement
the low-level protocol used to communicate with the MySQL database server.
By way of an example, the PHP Data Objects (PDO) database abstraction
layer may use one of several database-specific drivers. One of the drivers
it has available is the PDO MYSQL driver, which allows it to interface
with the MySQL server.
Sometimes people use the terms connector and driver interchangeably, this
can be confusing. In the MySQL-related documentation the term "driver" is
reserved for software that provides the database-specific part of a
connector package.
What is an Extension?
In the PHP documentation you will come across another term - extension.
The PHP code consists of a core, with optional extensions to the core
functionality. PHP's MySQL-related extensions, such as the mysqli
extension, and the mysql extension, are implemented using the PHP
extension framework.
An extension typically exposes an API to the PHP programmer, to allow its
facilities to be used programmatically. However, some extensions which use
the PHP extension framework do not expose an API to the PHP programmer.
The PDO MySQL driver extension, for example, does not expose an API to the
PHP programmer, but provides an interface to the PDO layer above it.
The terms API and extension should not be taken to mean the same thing, as
an extension may not necessarily expose an API to the programmer.
What are the main PHP API offerings for using MySQL?
There are three main API options when considering connecting to a MySQL
database server:
* PHP's MySQL Extension
* PHP's mysqli Extension
* PHP Data Objects (PDO)
Each has its own advantages and disadvantages. The following discussion
aims to give a brief introduction to the key aspects of each API.
What is PHP's MySQL Extension?
This is the original extension designed to allow you to develop PHP
applications that interact with a MySQL database. The mysql extension
provides a procedural interface and is intended for use only with MySQL
versions older than 4.1.3. This extension can be used with versions of
MySQL 4.1.3 or newer, but not all of the latest MySQL server features will
be available.
Note:
If you are using MySQL versions 4.1.3 or later it is strongly
recommended that you use the mysqli extension instead.
The mysql extension source code is located in the PHP extension directory
ext/mysql.
For further information on the mysql extension, see MySQL.
What is PHP's mysqli Extension?
The mysqli extension, or as it is sometimes known, the MySQL improved
extension, was developed to take advantage of new features found in MySQL
systems versions 4.1.3 and newer. The mysqli extension is included with
PHP versions 5 and later.
The mysqli extension has a number of benefits, the key enhancements over
the mysql extension being:
* Object-oriented interface
* Support for Prepared Statements
* Support for Multiple Statements
* Support for Transactions
* Enhanced debugging capabilities
* Embedded server support
Note:
If you are using MySQL versions 4.1.3 or later it is strongly
recommended that you use this extension.
As well as the object-oriented interface the extension also provides a
procedural interface.
The mysqli extension is built using the PHP extension framework, its
source code is located in the directory ext/mysqli.
For further information on the mysqli extension, see Mysqli.
What is PDO?
PHP Data Objects, or PDO, is a database abstraction layer specifically for
PHP applications. PDO provides a consistent API for your PHP application
regardless of the type of database server your application will connect
to. In theory, if you are using the PDO API, you could switch the database
server you used, from say Firebird to MySQL, and only need to make minor
changes to your PHP code.
Other examples of database abstraction layers include JDBC for Java
applications and DBI for Perl.
While PDO has its advantages, such as a clean, simple, portable API, its
main disadvantage is that it doesn't allow you to use all of the advanced
features that are available in the latest versions of MySQL server. For
example, PDO does not allow you to use MySQL's support for Multiple
Statements.
PDO is implemented using the PHP extension framework, its source code is
located in the directory ext/pdo.
For further information on PDO, see the PDO.
What is the PDO MYSQL driver?
The PDO MYSQL driver is not an API as such, at least from the PHP
programmer's perspective. In fact the PDO MYSQL driver sits in the layer
below PDO itself and provides MySQL-specific functionality. The programmer
still calls the PDO API, but PDO uses the PDO MYSQL driver to carry out
communication with the MySQL server.
The PDO MYSQL driver is one of several available PDO drivers. Other PDO
drivers available include those for the Firebird and PostgreSQL database
servers.
The PDO MYSQL driver is implemented using the PHP extension framework. Its
source code is located in the directory ext/pdo_mysql. It does not expose
an API to the PHP programmer.
For further information on the PDO MYSQL driver, see MySQL (PDO).
What is PHP's MySQL Native Driver?
In order to communicate with the MySQL database server the mysql
extension, mysqli and the PDO MYSQL driver each use a low-level library
that implements the required protocol. In the past, the only available
library was the MySQL Client Library, otherwise known as libmysql.
However, the interface presented by libmysql was not optimized for
communication with PHP applications, as libmysql was originally designed
with C applications in mind. For this reason the MySQL Native Driver,
mysqlnd, was developed as an alternative to libmysql for PHP applications.
The mysql extension, the mysqli extension and the PDO MySQL driver can
each be individually configured to use either libmysql or mysqlnd. As
mysqlnd is designed specifically to be utilised in the PHP system it has
numerous memory and speed enhancements over libmysql. You are strongly
encouraged to take advantage of these improvements.
Note:
The MySQL Native Driver can only be used with MySQL server versions
4.1.3 and later.
The MySQL Native Driver is implemented using the PHP extension framework.
The source code is located in ext/mysqlnd. It does not expose an API to
the PHP programmer.
Comparison of Features
The following table compares the functionality of the three main methods
of connecting to MySQL from PHP:
PHP's mysqli PDO (Using PDO MySQL PHP's MySQL
Extension Driver and MySQL Native Extension
Driver)
PHP version 5.0 5.0 Prior to 3.0
introduced
Included with PHP 5.x yes yes Yes
MySQL development Active Active development as Maintenance
status development of PHP 5.3 only
Recommended by MySQL Yes - preferred Yes No
for new projects option
API supports Charsets Yes Yes No
API supports
server-side Prepared Yes Yes No
Statements
API supports
client-side Prepared No Yes No
Statements
API supports Stored Yes Yes No
Procedures
API supports Multiple Yes Most No
Statements
Supports all MySQL Yes Most No
4.1+ functionality
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
In order to have these functions available, you must compile PHP with
support for the mysqli extension.
Note:
The mysqli extension is designed to work with MySQL version 4.1.13 or
newer, or 5.0.7 or newer. For previous versions, please see the MySQL
extension documentation.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
The mysqli extension was introduced with PHP version 5.0.0. The MySQL
Native Driver was included in PHP version 5.3.0.
Installation on Linux
The common Unix distributions include binary versions of PHP that can be
installed. Although these binary versions are typically built with support
for MySQL extensions enabled, the extension libraries themselves may need
to be installed using an additional package. Check the package manager
than comes with your chosen distribution for availability.
Unless your Unix distribution comes with a binary package of PHP with the
mysqli extension available, you will need to build PHP from source code.
Building PHP from source allows you to specify the MySQL extensions you
want to use, as well as your choice of client library for each extension.
PHP 5.0, 5.1, 5.2
If building from source code, to ensure that the mysqli extension for PHP
is enabled, you will need to configure the PHP source code to use mysqli.
This is achieved by running the configure script with the option
--with-mysqli=mysql_config_path/mysql_config , prior to building PHP. This
will enable mysqli and it will use the MySQL Client Library (libmysql) to
communicate with the MySQL Server.
The mysql_config_path represents the location of the mysql_config program
that comes with MySQL Server.
PHP 5.3.0+
With versions of PHP 5.3.0 and newer, mysqli uses MySQL Native Driver by
default. This gives a number of benefits over libmysql.
This is the recommended option, as using the MySQL Native Driver results
in improved performance and gives access to features not available when
using the MySQL Client Library. Refer to What is PHP's MySQL Native
Driver? for a brief overview of the advantages of MySQL Native Driver.
To use MySQL Native Driver with mysqli you need to configure the PHP
source code using the --with-mysqli=mysqlnd option, prior to building PHP.
Note that it is possible to freely mix MySQL extensions and client
libraries. For example, it is possible to enable the MySQL extension to
use the MySQL Client Library (libmysql), while configuring the mysqli
extension to use the MySQL Native Driver. However, all permutations of
extension and client library are possible.
The following example builds the MySQL extension to use the MySQL Client
Library, and the mysqli and PDO MYSQL extensions to use the MySQL Native
Driver:
./configure --with-mysql=/usr/bin/mysql_config \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd
[other options]
Installation on Windows Systems
On Windows, PHP is most commonly installed using the binary installer.
PHP 5.0, 5.1, 5.2
Once PHP has been installed, some configuration is required to enable
mysqli and specify the client library you want it to use.
The mysqli extension is not enabled by default, so the php_mysqli.dll DLL
must be enabled inside of php.ini. In order to do this you need to find
the php.ini file (typically located in c:\php), and make sure you remove
the comment (semi-colon) from the start of the line
extension=php_mysqli.dll, in the section marked [PHP_MYSQLI].
Also, if you want to use the MySQL Client Library with mysqli, you need to
make sure PHP can access the client library file. The MySQL Client Library
is included as a file named libmysql.dll in the Windows PHP distribution.
This file needs to be available in the Windows system's PATH environment
variable, so that it can be successfully loaded. See the FAQ titled "How
do I add my PHP directory to the PATH on Windows" for information on how
to do this. Copying libmysql.dll to the Windows system directory
(typically c:\Windows\system) also works, as the system directory is by
default in the system's PATH. However, this practice is strongly
discouraged.
As with enabling any PHP extension (such as php_mysqli.dll), the PHP
directive extension_dir should be set to the directory where the PHP
extensions are located. See also the Manual Windows Installation
Instructions. An example extension_dir value for PHP 5 is c:\php\ext.
Note:
If when starting the web server an error similar to the following
occurs: "Unable to load dynamic library './php_mysqli.dll'", this is
because php_mysqli.dll and/or libmysql.dll cannot be found by the
system.
PHP 5.3.0+
On Windows, for PHP versions 5.3 and newer, the mysqli extension is
enabled and uses the MySQL Native Driver by default. This means you don't
need to worry about configuring access to libmysql.dll.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
MySQLi Configuration Options
Name Default Changeable Changelog
mysqli.allow_persistent "1" PHP_INI_SYSTEM Available since PHP
5.3.0.
mysqli.max_persistent "-1" PHP_INI_SYSTEM Available since PHP
5.3.0.
mysqli.max_links "-1" PHP_INI_SYSTEM Available since PHP
5.0.0.
mysqli.default_port "3306" PHP_INI_ALL Available since PHP
5.0.0.
mysqli.default_socket NULL PHP_INI_ALL Available since PHP
5.0.0.
mysqli.default_host NULL PHP_INI_ALL Available since PHP
5.0.0.
mysqli.default_user NULL PHP_INI_ALL Available since PHP
5.0.0.
mysqli.default_pw NULL PHP_INI_ALL Available since PHP
5.0.0.
mysqli.reconnect "0" PHP_INI_SYSTEM Available since PHP
4.3.5.
mysqli.allow_local_infile "1" PHP_INI_SYSTEM Available since PHP
5.2.4.
mysqli.cache_size "2000" PHP_INI_SYSTEM Available since PHP
5.3.0.
For further details and definitions of the preceding PHP_INI_* constants,
see the chapter on configuration changes.
Here's a short explanation of the configuration directives.
mysqli.allow_persistent integer
Enable the ability to create persistent connections using
mysqli_connect().
mysqli.max_persistent integer
Maximum of persistent connections that can be made. Set to 0 for
unlimited.
mysqli.max_links integer
The maximum number of MySQL connections per process.
mysqli.default_port integer
The default TCP port number to use when connecting to the database
server if no other port is specified. If no default is specified,
the port will be obtained from the MYSQL_TCP_PORT environment
variable, the mysql-tcp entry in /etc/services or the compile-time
MYSQL_PORT constant, in that order. Win32 will only use the
MYSQL_PORT constant.
mysqli.default_socket string
The default socket name to use when connecting to a local database
server if no other socket name is specified.
mysqli.default_host string
The default server host to use when connecting to the database
server if no other host is specified. Doesn't apply in safe mode.
mysqli.default_user string
The default user name to use when connecting to the database
server if no other name is specified. Doesn't apply in safe mode.
mysqli.default_pw string
The default password to use when connecting to the database server
if no other password is specified. Doesn't apply in safe mode.
mysqli.reconnect integer
Automatically reconnect if the connection was lost.
mysqli.allow_local_infile integer
mysqli.cache_size integer
Available only with mysqlnd.
Users cannot set MYSQL_OPT_READ_TIMEOUT through an API call or runtime
configuration setting. Note that if it were possible there would be
differences between how libmysql and streams would interpret the value of
MYSQL_OPT_READ_TIMEOUT.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
The mysqli Extension and Persistent Connections
Persistent connection support was introduced in PHP 5.3 for the mysqli
extension. Support was already present in PDO MYSQL and ext/mysql. The
idea behind persistent connections is that a connection between a client
process and a database can be reused by a client process, rather than
being created and destroyed multiple times. This reduces the overhead of
creating fresh connections every time one is required, as unused
connections are cached and ready to be reused.
Unlike the mysql extension, mysqli does not provide a separate function
for opening persistent connections. To open a persistent connection you
must prepend p: to the hostname when connecting.
The problem with persistent connections is that they can be left in
unpredictable states by clients. For example, a table lock might be
activated before a client terminates unexpectedly. A new client process
reusing this persistent connection will get the connection "as is". Any
cleanup would need to be done by the new client process before it could
make good use of the persistent connection, increasing the burden on the
programmer.
The persistent connection of the mysqli extension however provides
built-in cleanup handling code. The cleanup carried out by mysqli
includes:
* Rollback active transactions
* Close and drop temporary tables
* Unlock tables
* Reset session variables
* Close prepared statements (always happens with PHP)
* Close handler
* Release locks acquired with GET_LOCK()
This ensures that persistent connections are in a clean state on return
from the connection pool, before the client process uses them.
The mysqli extension does this cleanup by automatically calling the C-API
function mysql_change_user().
The automatic cleanup feature has advantages and disadvantages though. The
advantage is that the programmer no longer needs to worry about adding
cleanup code, as it is called automatically. However, the disadvantage is
that the code could potentially be a little slower, as the code to perform
the cleanup needs to run each time a connection is returned from the
connection pool.
It is possible to switch off the automatic cleanup code, by compiling PHP
with MYSQLI_NO_CHANGE_USER_ON_PCONNECT defined.
Note:
The mysqli extension supports persistent connections when using either
MySQL Native Driver or MySQL Client Library.
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
MYSQLI_READ_DEFAULT_GROUP
Read options from the named group from my.cnf or the file
specified with MYSQLI_READ_DEFAULT_FILE
MYSQLI_READ_DEFAULT_FILE
Read options from the named option file instead of from my.cnf
MYSQLI_OPT_CONNECT_TIMEOUT
Connect timeout in seconds
MYSQLI_OPT_LOCAL_INFILE
Enables command LOAD LOCAL INFILE
MYSQLI_INIT_COMMAND
Command to execute when connecting to MySQL server. Will
automatically be re-executed when reconnecting.
MYSQLI_CLIENT_SSL
Use SSL (encrypted protocol). This option should not be set by
application programs; it is set internally in the MySQL client
library
MYSQLI_CLIENT_COMPRESS
Use compression protocol
MYSQLI_CLIENT_INTERACTIVE
Allow interactive_timeout seconds (instead of wait_timeout
seconds) of inactivity before closing the connection. The client's
session wait_timeout variable will be set to the value of the
session interactive_timeout variable.
MYSQLI_CLIENT_IGNORE_SPACE
Allow spaces after function names. Makes all functions names
reserved words.
MYSQLI_CLIENT_NO_SCHEMA
Don't allow the db_name.tbl_name.col_name syntax.
MYSQLI_CLIENT_MULTI_QUERIES
Allows multiple semicolon-delimited queries in a single
mysqli_query() call.
MYSQLI_STORE_RESULT
For using buffered resultsets
MYSQLI_USE_RESULT
For using unbuffered resultsets
MYSQLI_ASSOC
Columns are returned into the array having the fieldname as the
array index.
MYSQLI_NUM
Columns are returned into the array having an enumerated index.
MYSQLI_BOTH
Columns are returned into the array having both a numerical index
and the fieldname as the associative index.
MYSQLI_NOT_NULL_FLAG
Indicates that a field is defined as NOT NULL
MYSQLI_PRI_KEY_FLAG
Field is part of a primary index
MYSQLI_UNIQUE_KEY_FLAG
Field is part of a unique index.
MYSQLI_MULTIPLE_KEY_FLAG
Field is part of an index.
MYSQLI_BLOB_FLAG
Field is defined as BLOB
MYSQLI_UNSIGNED_FLAG
Field is defined as UNSIGNED
MYSQLI_ZEROFILL_FLAG
Field is defined as ZEROFILL
MYSQLI_AUTO_INCREMENT_FLAG
Field is defined as AUTO_INCREMENT
MYSQLI_TIMESTAMP_FLAG
Field is defined as TIMESTAMP
MYSQLI_SET_FLAG
Field is defined as SET
MYSQLI_NUM_FLAG
Field is defined as NUMERIC
MYSQLI_PART_KEY_FLAG
Field is part of an multi-index
MYSQLI_GROUP_FLAG
Field is part of GROUP BY
MYSQLI_TYPE_DECIMAL
Field is defined as DECIMAL
MYSQLI_TYPE_NEWDECIMAL
Precision math DECIMAL or NUMERIC field (MySQL 5.0.3 and up)
MYSQLI_TYPE_BIT
Field is defined as BIT (MySQL 5.0.3 and up)
MYSQLI_TYPE_TINY
Field is defined as TINYINT
MYSQLI_TYPE_SHORT
Field is defined as SMALLINT
MYSQLI_TYPE_LONG
Field is defined as INT
MYSQLI_TYPE_FLOAT
Field is defined as FLOAT
MYSQLI_TYPE_DOUBLE
Field is defined as DOUBLE
MYSQLI_TYPE_NULL
Field is defined as DEFAULT NULL
MYSQLI_TYPE_TIMESTAMP
Field is defined as TIMESTAMP
MYSQLI_TYPE_LONGLONG
Field is defined as BIGINT
MYSQLI_TYPE_INT24
Field is defined as MEDIUMINT
MYSQLI_TYPE_DATE
Field is defined as DATE
MYSQLI_TYPE_TIME
Field is defined as TIME
MYSQLI_TYPE_DATETIME
Field is defined as DATETIME
MYSQLI_TYPE_YEAR
Field is defined as YEAR
MYSQLI_TYPE_NEWDATE
Field is defined as DATE
MYSQLI_TYPE_INTERVAL
Field is defined as INTERVAL
MYSQLI_TYPE_ENUM
Field is defined as ENUM
MYSQLI_TYPE_SET
Field is defined as SET
MYSQLI_TYPE_TINY_BLOB
Field is defined as TINYBLOB
MYSQLI_TYPE_MEDIUM_BLOB
Field is defined as MEDIUMBLOB
MYSQLI_TYPE_LONG_BLOB
Field is defined as LONGBLOB
MYSQLI_TYPE_BLOB
Field is defined as BLOB
MYSQLI_TYPE_VAR_STRING
Field is defined as VARCHAR
MYSQLI_TYPE_STRING
Field is defined as STRING
MYSQLI_TYPE_CHAR
Field is defined as CHAR
MYSQLI_TYPE_GEOMETRY
Field is defined as GEOMETRY
MYSQLI_NEED_DATA
More data available for bind variable
MYSQLI_NO_DATA
No more data available for bind variable
MYSQLI_DATA_TRUNCATED
Data truncation occurred. Available since PHP 5.1.0 and MySQL
5.0.5.
MYSQLI_ENUM_FLAG
Field is defined as ENUM. Available since PHP 5.3.0.
MYSQLI_CURSOR_TYPE_FOR_UPDATE
MYSQLI_CURSOR_TYPE_NO_CURSOR
MYSQLI_CURSOR_TYPE_READ_ONLY
MYSQLI_CURSOR_TYPE_SCROLLABLE
MYSQLI_STMT_ATTR_CURSOR_TYPE
MYSQLI_STMT_ATTR_PREFETCH_ROWS
MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH
MYSQLI_SET_CHARSET_NAME
----------------------------------------------------------------------
----------------------------------------------------------------------
Notes
Some implementation notes:
1. Support was added for MYSQL_TYPE_GEOMETRY to the MySQLi extension in
PHP 5.3.
2. Note there are different internal implementations within libmysql and
mysqlnd for handling columns of type MYSQL_TYPE_GEOMETRY. Generally
speaking, mysqlnd will allocate significantly less memory. For
example, if there is a POINT column in a result set, libmysql may
pre-allocate up to 4GB of RAM although less than 50 bytes are needed
for holding a POINT column in memory. Memory allocation is much lower,
less than 50 bytes, if using mysqlnd.
----------------------------------------------------------------------
----------------------------------------------------------------------
The MySQLi Extension Function Summary
MySQLi Class
OOP Interface Procedural Interface Alias (Do not use) Description
Properties
Gets the number of
$mysqli::affected_rows mysqli_affected_rows() N/A affected rows in a
previous MySQL
operation
Returns the MySQL
$mysqli::client_info mysqli_get_client_info() N/A client version as a
string
Returns MySQL client
$mysqli::client_version mysqli_get_client_version() N/A version info as an
integer
Returns the error
$mysqli::connect_errno mysqli_connect_errno() N/A code from last
connect call
Returns a string
$mysqli::connect_error mysqli_connect_error() N/A description of the
last connect error
Returns the error
$mysqli::errno mysqli_errno() N/A code for the most
recent function call
Returns a string
$mysqli::error mysqli_error() N/A description of the
last error
Returns the number
$mysqli::field_count mysqli_field_count() N/A of columns for the
most recent query
Returns a string
$mysqli::host_info mysqli_get_host_info() N/A representing the
type of connection
used
Returns the version
$mysqli::protocol_version mysqli_get_proto_info() N/A of the MySQL
protocol used
$mysqli::server_info mysqli_get_server_info() N/A Returns the version
of the MySQL server
Returns the version
$mysqli::server_version mysqli_get_server_version() N/A of the MySQL server
as an integer
Retrieves
$mysqli::info mysqli_info() N/A information about
the most recently
executed query
Returns the auto
$mysqli::insert_id mysqli_insert_id() N/A generated id used in
the last query
Returns the SQLSTATE
$mysqli::sqlstate mysqli_sqlstate() N/A error from previous
MySQL operation
Returns the number
$mysqli::warning_count mysqli_warning_count() N/A of warnings from the
last query for the
given link
Methods
Turns on or off
mysqli::autocommit() mysqli_autocommit() N/A auto-commiting
database
modifications
Changes the user of
mysqli::change_user() mysqli_change_user() N/A the specified
database connection
Returns the default
mysqli::character_set_name(), mysqli_character_set_name() mysqli_client_encoding() character set for
mysqli::client_encoding the database
connection
Closes a previously
mysqli::close() mysqli_close() N/A opened database
connection
mysqli::commit() mysqli_commit() N/A Commits the current
transaction
Open a new
connection to the
mysqli::__construct() mysqli_connect() N/A MySQL server [Note:
static (i.e. class)
method]
mysqli::debug() mysqli_debug() N/A Performs debugging
operations
Dump debugging
mysqli::dump_debug_info() mysqli_dump_debug_info() N/A information into the
log
mysqli::get_charset() mysqli_get_charset() N/A Returns a character
set object
Returns client
connection
mysqli::get_connection_stats() mysqli_get_connection_stats() N/A statistics.
Available only with
mysqlnd.
Returns the MySQL
mysqli::get_client_info() mysqli_get_client_info() N/A client version as a
string
Returns client
per-process
mysqli::get_client_stats() mysqli_get_client_stats() N/A statistics.
Available only with
mysqlnd.
Returns client Zval
mysqli::get_cache_stats() mysqli_get_cache_stats() N/A cache statistics.
Available only with
mysqlnd.
mysqli::get_server_info() mysqli_get_server_info() N/A NOT DOCUMENTED
mysqli::get_warnings() mysqli_get_warnings() N/A NOT DOCUMENTED
Initializes MySQLi
and returns a
resource for use
with
mysqli::init() mysqli_init() N/A mysqli_real_connect.
[Not called on an
object, as it
returns a $mysqli
object.]
mysqli::kill() mysqli_kill() N/A Asks the server to
kill a MySQL thread
Check if there are
mysqli::more_results() mysqli_more_results() N/A any more query
results from a multi
query
mysqli::multi_query() mysqli_multi_query() N/A Performs a query on
the database
mysqli::next_result() mysqli_next_result() N/A Prepare next result
from multi_query
mysqli::options() mysqli_options() mysqli_set_opt() Set options
Pings a server
connection, or tries
mysqli::ping() mysqli_ping() N/A to reconnect if the
connection has gone
down
Prepare an SQL
mysqli::prepare() mysqli_prepare() N/A statement for
execution
mysqli::query() mysqli_query() N/A Performs a query on
the database
mysqli::real_connect() mysqli_real_connect() N/A Opens a connection
to a mysql server
Escapes special
characters in a
mysqli::real_escape_string(), string for use in an
mysqli::escape_string() mysqli_real_escape_string() mysqli_escape_string() SQL statement,
taking into account
the current charset
of the connection
mysqli::real_query() mysqli_real_query() N/A Execute an SQL query
mysqli::rollback() mysqli_rollback() N/A Rolls back current
transaction
Selects the default
mysqli::select_db() mysqli_select_db() N/A database for
database queries
mysqli::set_charset() mysqli_set_charset() N/A Sets the default
client character set
Unsets user defined
mysqli::set_local_infile_default() mysqli_set_local_infile_default() N/A handler for load
local infile command
Set callback
mysqli::set_local_infile_handler() mysqli_set_local_infile_handler() N/A function for LOAD
DATA LOCAL INFILE
command
Used for
mysqli::ssl_set() mysqli_ssl_set() N/A establishing secure
connections using
SSL
mysqli::stat() mysqli_stat() N/A Gets the current
system status
Initializes a
statement and
mysqli::stmt_init() mysqli_stmt_init() N/A returns an object
for use with
mysqli_stmt_prepare
Transfers a result
mysqli::store_result() mysqli_store_result() N/A set from the last
query
Returns the thread
mysqli::thread_id() mysqli_thread_id() N/A ID for the current
connection
Returns whether
mysqli::thread_safe() mysqli_thread_safe() N/A thread safety is
given or not
mysqli::use_result() mysqli_use_result() N/A Initiate a result
set retrieval
MySQL_STMT
OOP Interface Procedural Interface Alias (Do not use) Description
Properties
Returns the total
number of rows
$mysqli_stmt::affected_rows mysqli_stmt_affected_rows() N/A changed, deleted, or
inserted by the last
executed statement
Returns the error code
$mysqli_stmt::errno mysqli_stmt_errno() N/A for the most recent
statement call
Returns a string
$mysqli_stmt::error mysqli_stmt_error() N/A description for last
statement error
Returns the number of
$mysqli_stmt::field_count mysqli_stmt_field_count() N/A field in the given
statement - not
documented
Get the ID generated
$mysqli_stmt::insert_id mysqli_stmt_insert_id() N/A from the previous
INSERT operation
Return the number of
$mysqli_stmt::num_rows mysqli_stmt_num_rows() N/A rows in statements
result set
Returns the number of
$mysqli_stmt::param_count mysqli_stmt_param_count() mysqli_param_count() parameter for the
given statement
Returns SQLSTATE error
$mysqli_stmt::sqlstate mysqli_stmt_sqlstate() N/A from previous
statement operation
Methods
Used to get the
mysqli_stmt::attr_get() mysqli_stmt_attr_get() N/A current value of a
statement attribute
Used to modify the
mysqli_stmt::attr_set() mysqli_stmt_attr_set() N/A behavior of a prepared
statement
Binds variables to a
mysqli_stmt::bind_param() mysqli_stmt_bind_param() mysqli_bind_param() prepared statement as
parameters
Binds variables to a
mysqli_stmt::bind_result() mysqli_stmt_bind_result() mysqli_bind_result() prepared statement for
result storage
mysqli_stmt::close() mysqli_stmt_close() N/A Closes a prepared
statement
Seeks to an arbitrary
mysqli_stmt::data_seek() mysqli_stmt_data_seek() N/A row in statement
result set
mysqli_stmt::execute() mysqli_stmt_execute() mysqli_execute() Executes a prepared
Query
Fetch results from a
mysqli_stmt::fetch() mysqli_stmt_fetch() mysqli_fetch() prepared statement
into the bound
variables
Frees stored result
mysqli_stmt::free_result() mysqli_stmt_free_result() N/A memory for the given
statement handle
Gets a result set from
mysqli_stmt::get_result() mysqli_stmt_get_result() N/A a prepared statement.
Available only with
mysqlnd.
mysqli_stmt::get_warnings() mysqli_stmt_get_warnings() N/A NOT DOCUMENTED
NOT DOCUMENTED
$mysqli_stmt::more_results() mysqli_stmt_more_results() N/A Available only with
mysqlnd.
NOT DOCUMENTED
$mysqli_stmt::next_result() mysqli_stmt_next_result() N/A Available only with
mysqlnd.
mysqli_stmt::num_rows() mysqli_stmt_num_rows() N/A See also property
$mysqli_stmt::num_rows
Prepare an SQL
mysqli_stmt::prepare() mysqli_stmt_prepare() N/A statement for
execution
mysqli_stmt::reset() mysqli_stmt_reset() N/A Resets a prepared
statement
Returns result set
mysqli_stmt::result_metadata() mysqli_stmt_result_metadata() mysqli_get_metadata() metadata from a
prepared statement
mysqli_stmt::send_long_data() mysqli_stmt_send_long_data() mysqli_send_long_data() Send data in blocks
Transfers a result set
mysqli_stmt::store_result() mysqli_stmt_store_result() N/A from a prepared
statement
MySQLi_RESULT
Alias
OOP Interface Procedural Interface (Do Description
not
use)
Properties
Get current
$mysqli_result::current_field mysqli_field_tell() N/A field offset
of a result
pointer
Get the
$mysqli_result::field_count mysqli_num_fields() N/A number of
fields in a
result
Returns the
lengths of
the columns
$mysqli_result::lengths mysqli_fetch_lengths() N/A of the
current row
in the
result set
Gets the
$mysqli_result::num_rows mysqli_num_rows() N/A number of
rows in a
result
Methods
Adjusts the
result
mysqli_result::data_seek() mysqli_data_seek() N/A pointer to
an arbitary
row in the
result
Fetches all
result rows
and returns
the result
set as an
associative
mysqli_result::fetch_all() mysqli_fetch_all() N/A array, a
numeric
array, or
both.
Available
only with
mysqlnd.
Fetch a
result row
as an
mysqli_result::fetch_array() mysqli_fetch_array() N/A associative,
a numeric
array, or
both
Fetch a
result row
mysqli_result::fetch_assoc() mysqli_fetch_assoc() N/A as an
associative
array
Fetch
mysqli_result::fetch_field_direct() mysqli_fetch_field_direct() N/A meta-data
for a single
field
Returns the
mysqli_result::fetch_field() mysqli_fetch_field() N/A next field
in the
result set
Returns an
array of
objects
mysqli_result::fetch_fields() mysqli_fetch_fields() N/A representing
the fields
in a result
set
Returns the
current row
mysqli_result::fetch_object() mysqli_fetch_object() N/A of a result
set as an
object
Get a result
mysqli_result::fetch_row() mysqli_fetch_row() N/A row as an
enumerated
array
Set result
mysqli_result::field_seek() mysqli_field_seek() N/A pointer to a
specified
field offset
Frees the
mysqli_result::free(), memory
mysqli_result::close, mysqli_free_result() N/A associated
mysqli_result::free_result with a
result
MySQL_Driver
Alias
OOP Interface Procedural Interface (Do Description
not
use)
Properties
N/A
Methods
mysqli_driver::embedded_server_end() mysqli_embedded_server_end() N/A NOT
DOCUMENTED
mysqli_driver::embedded_server_start() mysqli_embedded_server_start() N/A NOT
DOCUMENTED
Note:
Alias functions are provided for backward compatibility purposes only.
Do not use them in new projects.
----------------------------------------------------------------------
----------------------------------------------------------------------
The MySQLi class
Introduction
Represents a connection between PHP and a MySQL database.
Class synopsis
MySQLi {
/* Properties */
int $MySQLi->affected_rows;
string $client_info;
int $client_version;
string $connect_errno;
string $connect_error;
int $errno;
string $error;
int $field_count;
int $client_version;
string $host_info;
string $protocol_version;
string $server_info;
int $server_version;
string $info;
mixed $insert_id;
string $sqlstate;
int $thread_id;
int $warning_count;
/* Methods */
int mysqli_affected_rows ( mysqli $link )
bool mysqli::autocommit ( bool $mode )
bool mysqli::change_user ( string $user , string $password , string
$database )
string mysqli::character_set_name ( void )
string mysqli_get_client_info ( mysqli $link )
int mysqli_get_client_version ( mysqli $link )
bool mysqli::close ( void )
bool mysqli::commit ( void )
int mysqli_connect_errno ( void )
string mysqli_connect_error ( void )
mysqli mysqli_connect ([ string $host = ini_get("mysqli.default_host") [,
string $username = ini_get("mysqli.default_user") [, string $passwd =
ini_get("mysqli.default_pw") [, string $dbname = "" [, int $port =
ini_get("mysqli.default_port") [, string $socket =
ini_get("mysqli.default_socket") ]]]]]] )
bool mysqli::debug ( string $message )
bool mysqli::dump_debug_info ( void )
int mysqli_errno ( mysqli $link )
string mysqli_error ( mysqli $link )
int mysqli_field_count ( mysqli $link )
object mysqli::get_charset ( void )
string mysqli::get_client_info ( void )
array mysqli_get_client_stats ( void )
int mysqli_get_client_version ( mysqli $link )
bool mysqli::get_connection_stats ( void )
string mysqli_get_host_info ( mysqli $link )
int mysqli_get_proto_info ( mysqli $link )
string mysqli_get_server_info ( mysqli $link )
int mysqli_get_server_version ( mysqli $link )
mysqli_warning mysqli::get_warnings ( void )
string mysqli_info ( mysqli $link )
mysqli mysqli::init ( void )
mixed mysqli_insert_id ( mysqli $link )
bool mysqli::kill ( int $processid )
bool mysqli::more_results ( void )
bool mysqli::multi_query ( string $query )
bool mysqli::next_result ( void )
bool mysqli::options ( int $option , mixed $value )
bool mysqli::ping ( void )
public int mysqli::poll ( array &$read , array &$error , array &$reject ,
int $sec [, int $usec ] )
mysqli_stmt mysqli::prepare ( string $query )
mixed mysqli::query ( string $query [, int $resultmode =
MYSQLI_STORE_RESULT ] )
bool mysqli::real_connect ([ string $host [, string $username [, string
$passwd [, string $dbname [, int $port [, string $socket [, int $flags
]]]]]]] )
string mysqli::escape_string ( string $escapestr )
bool mysqli::real_query ( string $query )
public mysqli_result mysqli::reap_async_query ( void )
bool mysqli::rollback ( void )
bool mysqli::select_db ( string $dbname )
bool mysqli::set_charset ( string $charset )
void mysqli_set_local_infile_default ( mysqli $link )
bool mysqli::set_local_infile_handler ( mysqli $link , callback $read_func
)
string mysqli_sqlstate ( mysqli $link )
bool mysqli::ssl_set ( string $key , string $cert , string $ca , string
$capath , string $cipher )
string mysqli::stat ( void )
mysqli_stmt mysqli::stmt_init ( void )
mysqli_result mysqli::store_result ( void )
int mysqli_thread_id ( mysqli $link )
bool mysqli_thread_safe ( void )
mysqli_result mysqli::use_result ( void )
int mysqli_warning_count ( mysqli $link )
}
----------------------------------------------------------------------
mysqli::affected_rows
mysqli_affected_rows
(PHP 5)
mysqli::affected_rows -- mysqli_affected_rows - Gets the number of
affected rows in a previous MySQL operation
Description
Object oriented style
int $mysqli->affected_rows;
Procedural style
int mysqli_affected_rows ( mysqli $link )
Returns the number of rows affected by the last INSERT, UPDATE, REPLACE or
DELETE query.
For SELECT statements mysqli_affected_rows() works like mysqli_num_rows().
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
An integer greater than zero indicates the number of rows affected or
retrieved. Zero indicates that no records where updated for an UPDATE
statement, no rows matched the WHERE clause in the query or that no query
has yet been executed. -1 indicates that the query returned an error.
Note:
If the number of affected rows is greater than maximal int value, the
number of affected rows will be returned as a string.
Examples
Example #1 mysqli->affected_rows example
Object oriented style
query("CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", $mysqli->affected_rows);
$mysqli->query("ALTER TABLE Language ADD Status int default 0");
/* update rows */
$mysqli->query("UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", $mysqli->affected_rows);
/* delete rows */
$mysqli->query("DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", $mysqli->affected_rows);
/* select all rows */
$result = $mysqli->query("SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", $mysqli->affected_rows);
$result->close();
/* Delete table Language */
$mysqli->query("DROP TABLE Language");
/* close connection */
$mysqli->close();
?>
Procedural style
50");
printf("Affected rows (UPDATE): %d\n", mysqli_affected_rows($link));
/* delete rows */
mysqli_query($link, "DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", mysqli_affected_rows($link));
/* select all rows */
$result = mysqli_query($link, "SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", mysqli_affected_rows($link));
mysqli_free_result($result);
/* Delete table Language */
mysqli_query($link, "DROP TABLE Language");
/* close connection */
mysqli_close($link);
?>
The above examples will output:
Affected rows (INSERT): 984
Affected rows (UPDATE): 168
Affected rows (DELETE): 815
Affected rows (SELECT): 169
See Also
* mysqli_num_rows() - Gets the number of rows in a result
* mysqli_info() - Retrieves information about the most recently executed
query
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::autocommit
mysqli_autocommit
(PHP 5)
mysqli::autocommit -- mysqli_autocommit - Turns on or off auto-commiting
database modifications
Description
Object oriented style
bool mysqli::autocommit ( bool $mode )
Procedural style
bool mysqli_autocommit ( mysqli $link , bool $mode )
Turns on or off auto-commit mode on queries for the database connection.
To determine the current state of autocommit use the SQL command SELECT
@@autocommit.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
mode
Whether to turn on auto-commit or not.
Return Values
Returns TRUE on success or FALSE on failure.
Notes
Note:
This function doesn't work with non transactional table types (like
MyISAM or ISAM).
Examples
Example #1 mysqli::autocommit() example
Object oriented style
autocommit(TRUE);
if ($result = $mysqli->query("SELECT @@autocommit")) {
$row = $result->fetch_row();
printf("Autocommit is %s\n", $row[0]);
$result->free();
}
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
Autocommit is 1
See Also
* mysqli_commit() - Commits the current transaction
* mysqli_rollback() - Rolls back current transaction
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::change_user
mysqli_change_user
(PHP 5)
mysqli::change_user -- mysqli_change_user - Changes the user of the
specified database connection
Description
Object oriented style
bool mysqli::change_user ( string $user , string $password , string
$database )
Procedural style
bool mysqli_change_user ( mysqli $link , string $user , string $password ,
string $database )
Changes the user of the specified database connection and sets the current
database.
In order to successfully change users a valid username and password
parameters must be provided and that user must have sufficient permissions
to access the desired database. If for any reason authorization fails, the
current user authentication will remain.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
user
The MySQL user name.
password
The MySQL password.
database
The database to change to.
If desired, the NULL value may be passed resulting in only
changing the user and not selecting a database. To select a
database in this case use the mysqli_select_db() function.
Return Values
Returns TRUE on success or FALSE on failure.
Notes
Note:
Using this command will always cause the current database connection to
behave as if was a completely new database connection, regardless of if
the operation was completed successfully. This reset includes performing
a rollback on any active transactions, closing all temporary tables, and
unlocking all locked tables.
Examples
Example #1 mysqli::change_user() example
Object oriented style
query("SET @a:=1");
/* reset all and select a new database */
$mysqli->change_user("my_user", "my_password", "world");
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database: %s\n", $row[0]);
$result->close();
}
if ($result = $mysqli->query("SELECT @a")) {
$row = $result->fetch_row();
if ($row[0] === NULL) {
printf("Value of variable a is NULL\n");
}
$result->close();
}
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
Default database: world
Value of variable a is NULL
See Also
* mysqli_connect() - Alias of mysqli::__construct
* mysqli_select_db() - Selects the default database for database queries
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::character_set_name
mysqli_character_set_name
(PHP 5)
mysqli::character_set_name -- mysqli_character_set_name - Returns the
default character set for the database connection
Description
Object oriented style
string mysqli::character_set_name ( void )
Procedural style
string mysqli_character_set_name ( mysqli $link )
Returns the current character set for the database connection.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
The default character set for the current connection
Examples
Example #1 mysqli::character_set_name() example
Object oriented style
character_set_name();
printf ("Current character set is %s\n", $charset);
$mysqli->close();
?>
Procedural style
The above examples will output:
Current character set is latin1_swedish_ci
See Also
* mysqli_client_encoding() - Alias of mysqli_character_set_name
* mysqli_real_escape_string() - Escapes special characters in a string
for use in an SQL statement, taking into account the current charset
of the connection
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::client_info
mysqli_get_client_info
(PHP 5)
mysqli::client_info -- mysqli_get_client_info - Returns the MySQL client
version as a string
Description
Object oriented style
string $mysqli->client_info;
Procedural style
string mysqli_get_client_info ( mysqli $link )
Returns a string that represents the MySQL client library version.
Return Values
A string that represents the MySQL client library version
Examples
Example #1 mysqli_get_client_info
See Also
* mysqli_get_client_version() - Get MySQL client info
* mysqli_get_server_info() - Returns the version of the MySQL server
* mysqli_get_server_version() - Returns the version of the MySQL server
as an integer
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::client_version
mysqli_get_client_version
(PHP 5)
mysqli::client_version -- mysqli_get_client_version - Get MySQL client
info
Description
Object oriented style
int $mysqli->client_version;
Procedural style
int mysqli_get_client_version ( mysqli $link )
Returns client version number as an integer.
Return Values
A number that represents the MySQL client library version in format:
main_version*10000 + minor_version *100 + sub_version. For example, 4.1.0
is returned as 40100.
This is useful to quickly determine the version of the client library to
know if some capability exits.
Examples
Example #1 mysqli_get_client_version
See Also
* mysqli_get_client_info() - Returns the MySQL client version as a
string
* mysqli_get_server_info() - Returns the version of the MySQL server
* mysqli_get_server_version() - Returns the version of the MySQL server
as an integer
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::close
mysqli_close
(PHP 5)
mysqli::close -- mysqli_close - Closes a previously opened database
connection
Description
Object oriented style
bool mysqli::close ( void )
Procedural style
bool mysqli_close ( mysqli $link )
Closes a previously opened database connection.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
Returns TRUE on success or FALSE on failure.
Examples
See mysqli_connect().
See Also
* mysqli_connect() - Alias of mysqli::__construct
* mysqli_init() - Initializes MySQLi and returns a resource for use with
mysqli_real_connect()
* mysqli_real_connect() - Opens a connection to a mysql server
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::commit
mysqli_commit
(PHP 5)
mysqli::commit -- mysqli_commit - Commits the current transaction
Description
Object oriented style
bool mysqli::commit ( void )
Procedural style
bool mysqli_commit ( mysqli $link )
Commits the current transaction for the database connection.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 mysqli::commit() example
Object oriented style
query("CREATE TABLE Language LIKE CountryLanguage");
/* set autocommit to off */
$mysqli->autocommit(FALSE);
/* Insert some values */
$mysqli->query("INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F', 11.2)");
$mysqli->query("INSERT INTO Language VALUES ('DEU', 'Swabian', 'F', 9.4)");
/* commit transaction */
$mysqli->commit();
/* drop table */
$mysqli->query("DROP TABLE Language");
/* close connection */
$mysqli->close();
?>
Procedural style
See Also
* mysqli_autocommit() - Turns on or off auto-commiting database
modifications
* mysqli_rollback() - Rolls back current transaction
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::connect_errno
mysqli_connect_errno
(PHP 5)
mysqli::connect_errno -- mysqli_connect_errno - Returns the error code
from last connect call
Description
Object oriented style
string $mysqli->connect_errno;
Procedural style
int mysqli_connect_errno ( void )
Returns the last error code number from the last call to mysqli_connect().
Note:
Client error message numbers are listed in the MySQL errmsg.h header
file, server error message numbers are listed in mysqld_error.h. In the
MySQL source distribution you can find a complete list of error messages
and error numbers in the file Docs/mysqld_error.txt.
Return Values
An error code value for the last call to mysqli_connect(), if it failed.
zero means no error occurred.
Examples
Example #1 mysqli->connect_errno example
Object oriented style
connect_errno) {
die('Connect Error: ' . $mysqli->connect_errno);
}
?>
Procedural style
The above examples will output:
Connect Error: 1045
See Also
* mysqli_connect() - Alias of mysqli::__construct
* mysqli_connect_error() - Returns a string description of the last
connect error
* mysqli_errno() - Returns the error code for the most recent function
call
* mysqli_error() - Returns a string description of the last error
* mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL
operation
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::connect_error
mysqli_connect_error
(PHP 5)
mysqli::connect_error -- mysqli_connect_error - Returns a string
description of the last connect error
Description
Object oriented style
string $mysqli->connect_error;
Procedural style
string mysqli_connect_error ( void )
Returns the last error message string from the last call to
mysqli_connect().
Return Values
A string that describes the error. NULL is returned if no error occurred.
Examples
Example #1 mysqli->connect_error example
Object oriented style
connect_error) {
die('Connect Error: ' . $mysqli->connect_error);
}
?>
Procedural style
The above examples will output:
Connect Error: Access denied for user 'fake_user'@'localhost' (using password: YES)
Notes
Warning
The mysqli->connect_error property only works properly as of PHP versions
5.2.9 and 5.3.0. Use the mysqli_connect_error() function if compatibility
with earlier PHP versions is required.
See Also
* mysqli_connect() - Alias of mysqli::__construct
* mysqli_connect_errno() - Returns the error code from last connect call
* mysqli_errno() - Returns the error code for the most recent function
call
* mysqli_error() - Returns a string description of the last error
* mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL
operation
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::__construct
mysqli_connect
(PHP 5)
mysqli::__construct -- mysqli_connect - Open a new connection to the MySQL
server
Description
Object oriented style
mysqli::__construct() ([ string $host = ini_get("mysqli.default_host") [,
string $username = ini_get("mysqli.default_user") [, string $passwd =
ini_get("mysqli.default_pw") [, string $dbname = "" [, int $port =
ini_get("mysqli.default_port") [, string $socket =
ini_get("mysqli.default_socket") ]]]]]] )
Procedural style
mysqli mysqli_connect ([ string $host = ini_get("mysqli.default_host") [,
string $username = ini_get("mysqli.default_user") [, string $passwd =
ini_get("mysqli.default_pw") [, string $dbname = "" [, int $port =
ini_get("mysqli.default_port") [, string $socket =
ini_get("mysqli.default_socket") ]]]]]] )
Opens a connection to the MySQL Server running on.
Parameters
host
Can be either a host name or an IP address. Passing the NULL value
or the string "localhost" to this parameter, the local host is
assumed. When possible, pipes will be used instead of the TCP/IP
protocol.
Prepending host by p: opens a persistent connection.
mysqli_change_user() is automatically called on connections opened
from the connection pool.
username
The MySQL user name.
passwd
If not provided or NULL, the MySQL server will attempt to
authenticate the user against those user records which have no
password only. This allows one username to be used with different
permissions (depending on if a password as provided or not).
dbname
If provided will specify the default database to be used when
performing queries.
port
Specifies the port number to attempt to connect to the MySQL
server.
socket
Specifies the socket or named pipe that should be used.
Note:
Specifying the socket parameter will not explicitly determine
the type of connection to be used when connecting to the MySQL
server. How the connection is made to the MySQL database is
determined by the host parameter.
Return Values
Returns an object which represents the connection to a MySQL Server.
Changelog
Version Description
5.3.0 Added the ability of persistent connections.
Examples
Example #1 mysqli::__construct() example
Object oriented style
connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
/*
* Use this instead of $connect_error if you need to ensure
* compatibility with PHP versions prior to 5.2.9 and 5.3.0.
*/
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . $mysqli->host_info . "\n";
$mysqli->close();
?>
Object oriented style when extending mysqli class
host_info . "\n";
$db->close();
?>
Procedural style
The above examples will output:
Success... MySQL host info: localhost via TCP/IP
Notes
Note:
MySQLnd always assumes the server default charset. This charset is sent
during connection hand-shake/authentication, which mysqlnd will use.
Libmysql uses the default charset set in the my.cnf or by an explicit
call to mysqli_options() prior to calling mysqli_real_connect(), but
after mysqli_init().
Note:
OO syntax only: If a connection fails an object is still returned. To
check if the connection failed then use either the
mysqli_connect_error() function or the mysqli->connect_error property as
in the preceding examples.
Note:
If it is necessary to set options, such as the connection timeout,
mysqli_real_connect() must be used instead.
Note:
Calling the constructor with no parameters is the same as calling
mysqli_init().
Note:
Error "Can't create TCP/IP socket (10106)" usually means that the
variables_order configure directive doesn't contain character E. On
Windows, if the environment is not copied the SYSTEMROOT environment
variable won't be available and PHP will have problems loading Winsock.
See Also
* mysqli_real_connect() - Opens a connection to a mysql server
* mysqli_options() - Set options
* mysqli_connect_errno() - Returns the error code from last connect call
* mysqli_connect_error() - Returns a string description of the last
connect error
* mysqli_close() - Closes a previously opened database connection
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::debug
mysqli_debug
(PHP 5)
mysqli::debug -- mysqli_debug - Performs debugging operations
Description
Object oriented style
bool mysqli::debug ( string $message )
Procedural style
bool mysqli_debug ( string $message )
Performs debugging operations using the Fred Fish debugging library.
Parameters
message
A string representing the debugging operation to perform
Return Values
Returns TRUE.
Notes
Note:
To use the mysqli_debug() function you must compile the MySQL client
library to support debugging.
Examples
Example #1 Generating a Trace File
See Also
* mysqli_dump_debug_info() - Dump debugging information into the log
* mysqli_report() - Enables or disables internal report functions
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::dump_debug_info
mysqli_dump_debug_info
(PHP 5)
mysqli::dump_debug_info -- mysqli_dump_debug_info - Dump debugging
information into the log
Description
Object oriented style
bool mysqli::dump_debug_info ( void )
Procedural style
bool mysqli_dump_debug_info ( mysqli $link )
This function is designed to be executed by an user with the SUPER
privilege and is used to dump debugging information into the log for the
MySQL Server relating to the connection.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* mysqli_debug() - Performs debugging operations
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::errno
mysqli_errno
(PHP 5)
mysqli::errno -- mysqli_errno - Returns the error code for the most recent
function call
Description
Object oriented style
int $mysqli->errno;
Procedural style
int mysqli_errno ( mysqli $link )
Returns the last error code for the most recent MySQLi function call that
can succeed or fail.
Client error message numbers are listed in the MySQL errmsg.h header file,
server error message numbers are listed in mysqld_error.h. In the MySQL
source distribution you can find a complete list of error messages and
error numbers in the file Docs/mysqld_error.txt.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
An error code value for the last call, if it failed. zero means no error
occurred.
Examples
Example #1 mysqli->errno example
Object oriented style
query("SET a=1")) {
printf("Errorcode: %d\n", $mysqli->errno);
}
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
Errorcode: 1193
See Also
* mysqli_connect_errno() - Returns the error code from last connect call
* mysqli_connect_error() - Returns a string description of the last
connect error
* mysqli_error() - Returns a string description of the last error
* mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL
operation
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::error
mysqli_error
(PHP 5)
mysqli::error -- mysqli_error - Returns a string description of the last
error
Description
Object oriented style
string $mysqli->error;
Procedural style
string mysqli_error ( mysqli $link )
Returns the last error message for the most recent MySQLi function call
that can succeed or fail.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
A string that describes the error. An empty string if no error occurred.
Examples
Example #1 mysqli->error example
Object oriented style
query("SET a=1")) {
printf("Errormessage: %s\n", $mysqli->error);
}
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
Errormessage: Unknown system variable 'a'
See Also
* mysqli_connect_errno() - Returns the error code from last connect call
* mysqli_connect_error() - Returns a string description of the last
connect error
* mysqli_errno() - Returns the error code for the most recent function
call
* mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL
operation
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::field_count
mysqli_field_count
(PHP 5)
mysqli::field_count -- mysqli_field_count - Returns the number of columns
for the most recent query
Description
Object oriented style
int $mysqli_result->field_count;
Procedural style
int mysqli_field_count ( mysqli $link )
Returns the number of columns for the most recent query on the connection
represented by the link parameter. This function can be useful when using
the mysqli_store_result() function to determine if the query should have
produced a non-empty result set or not without knowing the nature of the
query.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
An integer representing the number of fields in a result set.
Examples
Example #1 mysqli->field_count example
Object oriented style
query( "DROP TABLE IF EXISTS friends");
$mysqli->query( "CREATE TABLE friends (id int, name varchar(20))");
$mysqli->query( "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");
$mysqli->real_query("SELECT * FROM friends");
if ($mysqli->field_count) {
/* this was a select/show or describe query */
$result = $mysqli->store_result();
/* process resultset */
$row = $result->fetch_row();
/* free resultset */
$result->close();
}
/* close connection */
$mysqli->close();
?>
Procedural style
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::get_charset
mysqli_get_charset
(PHP 5 >= 5.1.0)
mysqli::get_charset -- mysqli_get_charset - Returns a character set object
Description
Object oriented style
object mysqli::get_charset ( void )
Procedural style
object mysqli_get_charset ( mysqli $link )
Returns a character set object providing several properties of the current
active character set.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
The function returns a character set object with the following properties:
charset
Character set name
collation
Collation name
dir
Directory the charset description was fetched from (?) or "" for
built-in character sets
min_length
Minimum character length in bytes
max_length
Maximum character length in bytes
number
Internal character set number
state
Character set status (?)
Examples
Example #1 mysqli::get_charset() example
Object oriented style
real_connect("localhost","root","","test");
var_dump($db->get_charset());
?>
Procedural style
get_charset());
?>
The above examples will output:
object(stdClass)#2 (7) {
["charset"]=>
string(6) "latin1"
["collation"]=>
string(17) "latin1_swedish_ci"
["dir"]=>
string(0) ""
["min_length"]=>
int(1)
["max_length"]=>
int(1)
["number"]=>
int(8)
["state"]=>
int(801)
}
See Also
* mysqli_character_set_name() - Returns the default character set for
the database connection
* mysqli_set_charset() - Sets the default client character set
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::get_client_info
mysqli_get_client_info
(PHP 5)
mysqli::get_client_info -- mysqli_get_client_info - Returns the MySQL
client version as a string
Description
Object oriented style
string mysqli::get_client_info ( void )
Procedural style
string mysqli_get_client_info ( mysqli $link )
Returns a string that represents the MySQL client library version.
Return Values
A string that represents the MySQL client library version
Examples
Example #1 mysqli_get_client_info
See Also
* mysqli_get_client_version() - Get MySQL client info
* mysqli_get_server_info() - Returns the version of the MySQL server
* mysqli_get_server_version() - Returns the version of the MySQL server
as an integer
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_get_client_stats
(PHP 5 >= 5.3.0)
mysqli_get_client_stats - Returns client per-process statistics
Description
array mysqli_get_client_stats ( void )
Returns client per-process statistics. Available only with mysqlnd.
Parameters
Return Values
Returns an array with client stats if success, FALSE otherwise.
Examples
Example #1 A mysqli_get_client_stats() example
The above example will output something similar to:
Array
(
[bytes_sent] => 43
[bytes_received] => 80
[packets_sent] => 1
[packets_received] => 2
[protocol_overhead_in] => 8
[protocol_overhead_out] => 4
[bytes_received_ok_packet] => 11
[bytes_received_eof_packet] => 0
[bytes_received_rset_header_packet] => 0
[bytes_received_rset_field_meta_packet] => 0
[bytes_received_rset_row_packet] => 0
[bytes_received_prepare_response_packet] => 0
[bytes_received_change_user_packet] => 0
[packets_sent_command] => 0
[packets_received_ok] => 1
[packets_received_eof] => 0
[packets_received_rset_header] => 0
[packets_received_rset_field_meta] => 0
[packets_received_rset_row] => 0
[packets_received_prepare_response] => 0
[packets_received_change_user] => 0
[result_set_queries] => 0
[non_result_set_queries] => 0
[no_index_used] => 0
[bad_index_used] => 0
[slow_queries] => 0
[buffered_sets] => 0
[unbuffered_sets] => 0
[ps_buffered_sets] => 0
[ps_unbuffered_sets] => 0
[flushed_normal_sets] => 0
[flushed_ps_sets] => 0
[ps_prepared_never_executed] => 0
[ps_prepared_once_executed] => 0
[rows_fetched_from_server_normal] => 0
[rows_fetched_from_server_ps] => 0
[rows_buffered_from_client_normal] => 0
[rows_buffered_from_client_ps] => 0
[rows_fetched_from_client_normal_buffered] => 0
[rows_fetched_from_client_normal_unbuffered] => 0
[rows_fetched_from_client_ps_buffered] => 0
[rows_fetched_from_client_ps_unbuffered] => 0
[rows_fetched_from_client_ps_cursor] => 0
[rows_skipped_normal] => 0
[rows_skipped_ps] => 0
[copy_on_write_saved] => 0
[copy_on_write_performed] => 0
[command_buffer_too_small] => 0
[connect_success] => 1
[connect_failure] => 0
[connection_reused] => 0
[reconnect] => 0
[pconnect_success] => 0
[active_connections] => 1
[active_persistent_connections] => 0
[explicit_close] => 0
[implicit_close] => 0
[disconnect_close] => 0
[in_middle_of_command_close] => 0
[explicit_free_result] => 0
[implicit_free_result] => 0
[explicit_stmt_close] => 0
[implicit_stmt_close] => 0
[mem_emalloc_count] => 0
[mem_emalloc_ammount] => 0
[mem_ecalloc_count] => 0
[mem_ecalloc_ammount] => 0
[mem_erealloc_count] => 0
[mem_erealloc_ammount] => 0
[mem_efree_count] => 0
[mem_malloc_count] => 0
[mem_malloc_ammount] => 0
[mem_calloc_count] => 0
[mem_calloc_ammount] => 0
[mem_realloc_count] => 0
[mem_realloc_ammount] => 0
[mem_free_count] => 0
[proto_text_fetched_null] => 0
[proto_text_fetched_bit] => 0
[proto_text_fetched_tinyint] => 0
[proto_text_fetched_short] => 0
[proto_text_fetched_int24] => 0
[proto_text_fetched_int] => 0
[proto_text_fetched_bigint] => 0
[proto_text_fetched_decimal] => 0
[proto_text_fetched_float] => 0
[proto_text_fetched_double] => 0
[proto_text_fetched_date] => 0
[proto_text_fetched_year] => 0
[proto_text_fetched_time] => 0
[proto_text_fetched_datetime] => 0
[proto_text_fetched_timestamp] => 0
[proto_text_fetched_string] => 0
[proto_text_fetched_blob] => 0
[proto_text_fetched_enum] => 0
[proto_text_fetched_set] => 0
[proto_text_fetched_geometry] => 0
[proto_text_fetched_other] => 0
[proto_binary_fetched_null] => 0
[proto_binary_fetched_bit] => 0
[proto_binary_fetched_tinyint] => 0
[proto_binary_fetched_short] => 0
[proto_binary_fetched_int24] => 0
[proto_binary_fetched_int] => 0
[proto_binary_fetched_bigint] => 0
[proto_binary_fetched_decimal] => 0
[proto_binary_fetched_float] => 0
[proto_binary_fetched_double] => 0
[proto_binary_fetched_date] => 0
[proto_binary_fetched_year] => 0
[proto_binary_fetched_time] => 0
[proto_binary_fetched_datetime] => 0
[proto_binary_fetched_timestamp] => 0
[proto_binary_fetched_string] => 0
[proto_binary_fetched_blob] => 0
[proto_binary_fetched_enum] => 0
[proto_binary_fetched_set] => 0
[proto_binary_fetched_geometry] => 0
[proto_binary_fetched_other] => 0
)
See Also
* Stats description
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::client_version
mysqli_get_client_version
(PHP 5)
mysqli::client_version -- mysqli_get_client_version - Get MySQL client
info
Description
Object oriented style
int $mysqli->client_version;
Procedural style
int mysqli_get_client_version ( mysqli $link )
Returns client version number as an integer.
Return Values
A number that represents the MySQL client library version in format:
main_version*10000 + minor_version *100 + sub_version. For example, 4.1.0
is returned as 40100.
This is useful to quickly determine the version of the client library to
know if some capability exits.
Examples
Example #1 mysqli_get_client_version
See Also
* mysqli_get_client_info() - Returns the MySQL client version as a
string
* mysqli_get_server_info() - Returns the version of the MySQL server
* mysqli_get_server_version() - Returns the version of the MySQL server
as an integer
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::get_connection_stats
mysqli_get_connection_stats
(PHP 5 >= 5.3.0)
mysqli::get_connection_stats -- mysqli_get_connection_stats - Returns
statistics about the client connection
Description
Object oriented style
bool mysqli::get_connection_stats ( void )
Procedural style
array mysqli_get_connection_stats ( mysqli $link )
Returns statistics about the client connection. Available only with
mysqlnd.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
Returns an array with connection stats if success, FALSE otherwise.
Examples
Example #1 A mysqli_get_connection_stats() example
The above example will output something similar to:
Array
(
[bytes_sent] => 43
[bytes_received] => 80
[packets_sent] => 1
[packets_received] => 2
[protocol_overhead_in] => 8
[protocol_overhead_out] => 4
[bytes_received_ok_packet] => 11
[bytes_received_eof_packet] => 0
[bytes_received_rset_header_packet] => 0
[bytes_received_rset_field_meta_packet] => 0
[bytes_received_rset_row_packet] => 0
[bytes_received_prepare_response_packet] => 0
[bytes_received_change_user_packet] => 0
[packets_sent_command] => 0
[packets_received_ok] => 1
[packets_received_eof] => 0
[packets_received_rset_header] => 0
[packets_received_rset_field_meta] => 0
[packets_received_rset_row] => 0
[packets_received_prepare_response] => 0
[packets_received_change_user] => 0
[result_set_queries] => 0
[non_result_set_queries] => 0
[no_index_used] => 0
[bad_index_used] => 0
[slow_queries] => 0
[buffered_sets] => 0
[unbuffered_sets] => 0
[ps_buffered_sets] => 0
[ps_unbuffered_sets] => 0
[flushed_normal_sets] => 0
[flushed_ps_sets] => 0
[ps_prepared_never_executed] => 0
[ps_prepared_once_executed] => 0
[rows_fetched_from_server_normal] => 0
[rows_fetched_from_server_ps] => 0
[rows_buffered_from_client_normal] => 0
[rows_buffered_from_client_ps] => 0
[rows_fetched_from_client_normal_buffered] => 0
[rows_fetched_from_client_normal_unbuffered] => 0
[rows_fetched_from_client_ps_buffered] => 0
[rows_fetched_from_client_ps_unbuffered] => 0
[rows_fetched_from_client_ps_cursor] => 0
[rows_skipped_normal] => 0
[rows_skipped_ps] => 0
[copy_on_write_saved] => 0
[copy_on_write_performed] => 0
[command_buffer_too_small] => 0
[connect_success] => 1
[connect_failure] => 0
[connection_reused] => 0
[reconnect] => 0
[pconnect_success] => 0
[active_connections] => 1
[active_persistent_connections] => 0
[explicit_close] => 0
[implicit_close] => 0
[disconnect_close] => 0
[in_middle_of_command_close] => 0
[explicit_free_result] => 0
[implicit_free_result] => 0
[explicit_stmt_close] => 0
[implicit_stmt_close] => 0
[mem_emalloc_count] => 0
[mem_emalloc_ammount] => 0
[mem_ecalloc_count] => 0
[mem_ecalloc_ammount] => 0
[mem_erealloc_count] => 0
[mem_erealloc_ammount] => 0
[mem_efree_count] => 0
[mem_malloc_count] => 0
[mem_malloc_ammount] => 0
[mem_calloc_count] => 0
[mem_calloc_ammount] => 0
[mem_realloc_count] => 0
[mem_realloc_ammount] => 0
[mem_free_count] => 0
[proto_text_fetched_null] => 0
[proto_text_fetched_bit] => 0
[proto_text_fetched_tinyint] => 0
[proto_text_fetched_short] => 0
[proto_text_fetched_int24] => 0
[proto_text_fetched_int] => 0
[proto_text_fetched_bigint] => 0
[proto_text_fetched_decimal] => 0
[proto_text_fetched_float] => 0
[proto_text_fetched_double] => 0
[proto_text_fetched_date] => 0
[proto_text_fetched_year] => 0
[proto_text_fetched_time] => 0
[proto_text_fetched_datetime] => 0
[proto_text_fetched_timestamp] => 0
[proto_text_fetched_string] => 0
[proto_text_fetched_blob] => 0
[proto_text_fetched_enum] => 0
[proto_text_fetched_set] => 0
[proto_text_fetched_geometry] => 0
[proto_text_fetched_other] => 0
[proto_binary_fetched_null] => 0
[proto_binary_fetched_bit] => 0
[proto_binary_fetched_tinyint] => 0
[proto_binary_fetched_short] => 0
[proto_binary_fetched_int24] => 0
[proto_binary_fetched_int] => 0
[proto_binary_fetched_bigint] => 0
[proto_binary_fetched_decimal] => 0
[proto_binary_fetched_float] => 0
[proto_binary_fetched_double] => 0
[proto_binary_fetched_date] => 0
[proto_binary_fetched_year] => 0
[proto_binary_fetched_time] => 0
[proto_binary_fetched_datetime] => 0
[proto_binary_fetched_timestamp] => 0
[proto_binary_fetched_string] => 0
[proto_binary_fetched_blob] => 0
[proto_binary_fetched_enum] => 0
[proto_binary_fetched_set] => 0
[proto_binary_fetched_geometry] => 0
[proto_binary_fetched_other] => 0
)
See Also
* Stats description
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::host_info
mysqli_get_host_info
(PHP 5)
mysqli::host_info -- mysqli_get_host_info - Returns a string representing
the type of connection used
Description
Object oriented style
string $mysqli->host_info;
Procedural style
string mysqli_get_host_info ( mysqli $link )
Returns a string describing the connection represented by the link
parameter (including the server host name).
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
A character string representing the server hostname and the connection
type.
Examples
Example #1 mysqli->host_info example
Object oriented style
host_info);
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
Host info: Localhost via UNIX socket
See Also
* mysqli_get_proto_info() - Returns the version of the MySQL protocol
used
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::protocol_version
mysqli_get_proto_info
(PHP 5)
mysqli::protocol_version -- mysqli_get_proto_info - Returns the version of
the MySQL protocol used
Description
Object oriented style
string $mysqli->protocol_version;
Procedural style
int mysqli_get_proto_info ( mysqli $link )
Returns an integer representing the MySQL protocol version used by the
connection represented by the link parameter.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
Returns an integer representing the protocol version.
Examples
Example #1 mysqli->protocol_version example
Object oriented style
protocol_version);
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
Protocol version: 10
See Also
* mysqli_get_host_info() - Returns a string representing the type of
connection used
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::server_info
mysqli_get_server_info
(PHP 5)
mysqli::server_info -- mysqli_get_server_info - Returns the version of the
MySQL server
Description
Object oriented style
string $mysqli->server_info;
Procedural style
string mysqli_get_server_info ( mysqli $link )
Returns a string representing the version of the MySQL server that the
MySQLi extension is connected to.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
A character string representing the server version.
Examples
Example #1 mysqli->server_info example
Object oriented style
server_info);
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
Server version: 4.1.2-alpha-debug
See Also
* mysqli_get_client_info() - Returns the MySQL client version as a
string
* mysqli_get_client_version() - Get MySQL client info
* mysqli_get_server_version() - Returns the version of the MySQL server
as an integer
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::server_version
mysqli_get_server_version
(PHP 5)
mysqli::server_version -- mysqli_get_server_version - Returns the version
of the MySQL server as an integer
Description
Object oriented style
int $mysqli->server_version;
Procedural style
int mysqli_get_server_version ( mysqli $link )
The mysqli_get_server_version() function returns the version of the server
connected to (represented by the link parameter) as an integer.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
An integer representing the server version.
The form of this version number is main_version * 10000 + minor_version *
100 + sub_version (i.e. version 4.1.0 is 40100).
Examples
Example #1 mysqli->server_version example
Object oriented style
server_version);
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
Server version: 40102
See Also
* mysqli_get_client_info() - Returns the MySQL client version as a
string
* mysqli_get_client_version() - Get MySQL client info
* mysqli_get_server_info() - Returns the version of the MySQL server
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::get_warnings
mysqli_get_warnings
(PHP 5 >= 5.1.0)
mysqli::get_warnings -- mysqli_get_warnings - Get result of SHOW WARNINGS
Description
Object oriented style
mysqli_warning mysqli::get_warnings ( void )
Procedural style
mysqli_warning mysqli_get_warnings ( mysqli $link )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::info
mysqli_info
(PHP 5)
mysqli::info -- mysqli_info - Retrieves information about the most
recently executed query
Description
Object oriented style
string $mysqli->info;
Procedural style
string mysqli_info ( mysqli $link )
The mysqli_info() function returns a string providing information about
the last query executed. The nature of this string is provided below:
Possible mysqli_info return values
Query type Example result string
INSERT INTO...SELECT... Records: 100 Duplicates: 0
Warnings: 0
INSERT INTO...VALUES (...),(...),(...) Records: 3 Duplicates: 0 Warnings:
0
LOAD DATA INFILE ... Records: 1 Deleted: 0 Skipped: 0
Warnings: 0
ALTER TABLE ... Records: 3 Duplicates: 0 Warnings:
0
UPDATE ... Rows matched: 40 Changed: 40
Warnings: 0
Note:
Queries which do not fall into one of the preceding formats are not
supported. In these situations, mysqli_info() will return an empty
string.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
A character string representing additional information about the most
recently executed query.
Examples
Example #1 mysqli->info example
Object oriented style
query("CREATE TEMPORARY TABLE t1 LIKE City");
/* INSERT INTO .. SELECT */
$mysqli->query("INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150");
printf("%s\n", $mysqli->info);
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
Records: 150 Duplicates: 0 Warnings: 0
See Also
* mysqli_affected_rows() - Gets the number of affected rows in a
previous MySQL operation
* mysqli_warning_count() - Returns the number of warnings from the last
query for the given link
* mysqli_num_rows() - Gets the number of rows in a result
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::init
mysqli_init
(PHP 5)
mysqli::init -- mysqli_init - Initializes MySQLi and returns a resource
for use with mysqli_real_connect()
Description
Object oriented style
mysqli mysqli::init ( void )
Procedural style
mysqli mysqli_init ( void )
Allocates or initializes a MYSQL object suitable for mysqli_options() and
mysqli_real_connect().
Note:
Any subsequent calls to any mysqli function (except mysqli_options())
will fail until mysqli_real_connect() was called.
Return Values
Returns an object.
Examples
See mysqli_real_connect().
See Also
* mysqli_options() - Set options
* mysqli_close() - Closes a previously opened database connection
* mysqli_real_connect() - Opens a connection to a mysql server
* mysqli_connect() - Alias of mysqli::__construct
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::insert_id
mysqli_insert_id
(PHP 5)
mysqli::insert_id -- mysqli_insert_id - Returns the auto generated id used
in the last query
Description
Object oriented style
mixed $mysqli->insert_id;
Procedural style
mixed mysqli_insert_id ( mysqli $link )
The mysqli_insert_id() function returns the ID generated by a query on a
table with a column having the AUTO_INCREMENT attribute. If the last query
wasn't an INSERT or UPDATE statement or if the modified table does not
have a column with the AUTO_INCREMENT attribute, this function will return
zero.
Note:
Performing an INSERT or UPDATE statement using the LAST_INSERT_ID()
function will also modify the value returned by the mysqli_insert_id()
function.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
The value of the AUTO_INCREMENT field that was updated by the previous
query. Returns zero if there was no previous query on the connection or if
the query did not update an AUTO_INCREMENT value.
Note:
If the number is greater than maximal int value, mysqli_insert_id() will
return a string.
Examples
Example #1 mysqli->insert_id example
Object oriented style
query("CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
/* drop table */
$mysqli->query("DROP TABLE myCity");
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
New Record has id 1.
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::kill
mysqli_kill
(PHP 5)
mysqli::kill -- mysqli_kill - Asks the server to kill a MySQL thread
Description
Object oriented style
bool mysqli::kill ( int $processid )
Procedural style
bool mysqli_kill ( mysqli $link , int $processid )
This function is used to ask the server to kill a MySQL thread specified
by the processid parameter. This value must be retrieved by calling the
mysqli_thread_id() function.
To stop a running query you should use the SQL command KILL QUERY
processid.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 mysqli::kill() example
Object oriented style
thread_id;
/* Kill connection */
$mysqli->kill($thread_id);
/* This should produce an error */
if (!$mysqli->query("CREATE TABLE myCity LIKE City")) {
printf("Error: %s\n", $mysqli->error);
exit;
}
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
Error: MySQL server has gone away
See Also
* mysqli_thread_id() - Returns the thread ID for the current connection
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::more_results
mysqli_more_results
(PHP 5)
mysqli::more_results -- mysqli_more_results - Check if there are any more
query results from a multi query
Description
Object oriented style
bool mysqli::more_results ( void )
Procedural style
bool mysqli_more_results ( mysqli $link )
Indicates if one or more result sets are available from a previous call to
mysqli_multi_query().
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
Returns TRUE on success or FALSE on failure.
Examples
See mysqli_multi_query().
See Also
* mysqli_multi_query() - Performs a query on the database
* mysqli_next_result() - Prepare next result from multi_query
* mysqli_store_result() - Transfers a result set from the last query
* mysqli_use_result() - Initiate a result set retrieval
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::multi_query
mysqli_multi_query
(PHP 5)
mysqli::multi_query -- mysqli_multi_query - Performs a query on the
database
Description
Object oriented style
bool mysqli::multi_query ( string $query )
Procedural style
bool mysqli_multi_query ( mysqli $link , string $query )
Executes one or multiple queries which are concatenated by a semicolon.
To retrieve the resultset from the first query you can use
mysqli_use_result() or mysqli_store_result(). All subsequent query results
can be processed using mysqli_more_results() and mysqli_next_result().
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
query
The query, as a string.
Data inside the query should be properly escaped.
Return Values
Returns FALSE if the first statement failed. To retrieve subsequent errors
from other statements you have to call mysqli_next_result() first.
Examples
Example #1 mysqli::multi_query() example
Object oriented style
multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output something similar to:
my_user@localhost
-----------------
Amersfoort
Maastricht
Dordrecht
Leiden
Haarlemmermeer
See Also
* mysqli_use_result() - Initiate a result set retrieval
* mysqli_store_result() - Transfers a result set from the last query
* mysqli_next_result() - Prepare next result from multi_query
* mysqli_more_results() - Check if there are any more query results from
a multi query
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::next_result
mysqli_next_result
(PHP 5)
mysqli::next_result -- mysqli_next_result - Prepare next result from
multi_query
Description
Object oriented style
bool mysqli::next_result ( void )
Procedural style
bool mysqli_next_result ( mysqli $link )
Prepares next result set from a previous call to mysqli_multi_query()
which can be retrieved by mysqli_store_result() or mysqli_use_result().
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
Returns TRUE on success or FALSE on failure.
Examples
See mysqli_multi_query().
See Also
* mysqli_multi_query() - Performs a query on the database
* mysqli_more_results() - Check if there are any more query results from
a multi query
* mysqli_store_result() - Transfers a result set from the last query
* mysqli_use_result() - Initiate a result set retrieval
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::options
mysqli_options
(PHP 5)
mysqli::options -- mysqli_options - Set options
Description
Object oriented style
bool mysqli::options ( int $option , mixed $value )
Procedural style
bool mysqli_options ( mysqli $link , int $option , mixed $value )
Used to set extra connect options and affect behavior for a connection.
This function may be called multiple times to set several options.
mysqli_options() should be called after mysqli_init() and before
mysqli_real_connect().
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
option
The option that you want to set. It can be one of the following
values:
Valid options
Name Description
connection timeout in seconds
MYSQLI_OPT_CONNECT_TIMEOUT (supported on Windows with TCP/IP since
PHP 5.3.1)
MYSQLI_OPT_LOCAL_INFILE enable/disable use of LOAD LOCAL INFILE
MYSQLI_INIT_COMMAND command to execute after when
connecting to MySQL server
MYSQLI_READ_DEFAULT_FILE Read options from named option file
instead of my.cnf
Read options from the named group from
MYSQLI_READ_DEFAULT_GROUP my.cnf or the file specified with
MYSQL_READ_DEFAULT_FILE.
value
The value for the option.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
See mysqli_real_connect().
Notes
Note:
MySQLnd always assumes the server default charset. This charset is sent
during connection hand-shake/authentication, which mysqlnd will use.
Libmysql uses the default charset set in the my.cnf or by an explicit
call to mysqli_options() prior to calling mysqli_real_connect(), but
after mysqli_init().
See Also
* mysqli_init() - Initializes MySQLi and returns a resource for use with
mysqli_real_connect()
* mysqli_real_connect() - Opens a connection to a mysql server
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::ping
mysqli_ping
(PHP 5)
mysqli::ping -- mysqli_ping - Pings a server connection, or tries to
reconnect if the connection has gone down
Description
Object oriented style
bool mysqli::ping ( void )
Procedural style
bool mysqli_ping ( mysqli $link )
Checks whether the connection to the server is working. If it has gone
down, and global option mysqli.reconnect is enabled an automatic
reconnection is attempted.
This function can be used by clients that remain idle for a long while, to
check whether the server has closed the connection and reconnect if
necessary.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 mysqli::ping() example
Object oriented style
ping()) {
printf ("Our connection is ok!\n");
} else {
printf ("Error: %s\n", $mysqli->error);
}
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
Our connection is ok!
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::poll
mysqli_poll
(PHP 5 >= 5.3.0)
mysqli::poll -- mysqli_poll - Poll connections
Description
Object oriented style
public int mysqli::poll ( array &$read , array &$error , array &$reject ,
int $sec [, int $usec ] )
Procedural style
int mysqli_poll ( array &$read , array &$error , array &$reject , int $sec
[, int $usec ] )
Warning
This function is currently not documented; only its argument list is
available.
Poll connections. Available only with mysqlnd.
Parameters
read
error
reject
sec
Number of seconds to wait, must be non-negative.
usec
Number of microseconds to wait, must be non-negative.
Return Values
Returns number of ready connections in success, FALSE otherwise.
Examples
Example #1 A mysqli_poll() example
query("SELECT 'test'", MYSQLI_ASYNC);
$all_links = array($link1);
$processed = 0;
do {
$links = $errors = $reject = array();
foreach ($all_links as $link) {
$links[] = $errors[] = $reject[] = $link;
}
if (!mysqli_poll($links, $errors, $reject, 1)) {
continue;
}
foreach ($links as $link) {
if ($result = $link->reap_async_query()) {
print_r($result->fetch_row());
mysqli_free_result($result);
$processed++;
}
}
} while ($processed < count($all_links));
?>
The above example will output:
Array
(
[0] => test
)
See Also
* mysqli_query() - Performs a query on the database
* mysqli_reap_async_query() - Get result from async query
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::prepare
mysqli_prepare
(PHP 5)
mysqli::prepare -- mysqli_prepare - Prepare an SQL statement for execution
Description
Object oriented style
mysqli_stmt mysqli::prepare ( string $query )
Procedural style
mysqli_stmt mysqli_prepare ( mysqli $link , string $query )
Prepares the SQL query, and returns a statement handle to be used for
further operations on the statement. The query must consist of a single
SQL statement.
The parameter markers must be bound to application variables using
mysqli_stmt_bind_param() and/or mysqli_stmt_bind_result() before executing
the statement or fetching rows.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
query
The query, as a string.
Note:
You should not add a terminating semicolon or \g to the
statement.
This parameter can include one or more parameter markers in the
SQL statement by embedding question mark (?) characters at the
appropriate positions.
Note:
The markers are legal only in certain places in SQL statements.
For example, they are allowed in the VALUES() list of an INSERT
statement (to specify column values for a row), or in a
comparison with a column in a WHERE clause to specify a
comparison value.
However, they are not allowed for identifiers (such as table or
column names), in the select list that names the columns to be
returned by a SELECT statement, or to specify both operands of a
binary operator such as the = equal sign. The latter restriction
is necessary because it would be impossible to determine the
parameter type. It's not allowed to compare marker with NULL by
? IS NULL too. In general, parameters are legal only in Data
Manipulation Language (DML) statements, and not in Data
Definition Language (DDL) statements.
Return Values
mysqli_prepare() returns a statement object or FALSE if an error occurred.
Examples
Example #1 mysqli::prepare() example
Object oriented style
prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
Amersfoort is in district Utrecht
See Also
* mysqli_stmt_execute() - Executes a prepared Query
* mysqli_stmt_fetch() - Fetch results from a prepared statement into the
bound variables
* mysqli_stmt_bind_param() - Binds variables to a prepared statement as
parameters
* mysqli_stmt_bind_result() - Binds variables to a prepared statement
for result storage
* mysqli_stmt_close() - Closes a prepared statement
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::query
mysqli_query
(PHP 5)
mysqli::query -- mysqli_query - Performs a query on the database
Description
Object oriented style
mixed mysqli::query ( string $query [, int $resultmode =
MYSQLI_STORE_RESULT ] )
Procedural style
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode =
MYSQLI_STORE_RESULT ] )
Performs a query against the database.
Functionally, using this function is identical to calling
mysqli_real_query() followed either by mysqli_use_result() or
mysqli_store_result().
Note:
In the case where you pass a statement to mysqli_query() that is longer
than max_allowed_packet of the server, the returned error codes are
different depending on whether you are using MySQL Native Driver
(mysqlnd) or MySQL Client Library (libmysql). The behavior is as
follows:
* mysqlnd on Linux returns an error code of 1153. The error message
means "got a packet bigger than max_allowed_packet bytes".
* mysqlnd on Windows returns an error code 2006. This error message
means "server has gone away".
* libmysql on all platforms returns an error code 2006. This error
message means "server has gone away".
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
query
The query string.
Data inside the query should be properly escaped.
resultmode
Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT
depending on the desired behavior. By default, MYSQLI_STORE_RESULT
is used.
If you use MYSQLI_USE_RESULT all subsequent calls will return
error Commands out of sync unless you call mysqli_free_result()
With MYSQLI_ASYNC (available with mysqlnd), it is possible to
perform query asynchronously. mysqli_poll() is then used to get
results from such queries.
Return Values
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN
queries mysqli_query() will return a result object. For other successful
queries mysqli_query() will return TRUE.
Changelog
Version Description
5.3.0 Added the ability of async queries.
Examples
Example #1 mysqli::query() example
Object oriented style
connect_errno()) {
printf("Connect failed: %s\n", $mysqli->connect_error());
exit();
}
/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
printf("Table myCity successfully created.\n");
}
/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", $result->num_rows);
/* free result set */
$result->close();
}
/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {
/* Note, that we can't execute any functions which interact with the
server until result set was closed. All calls will return an
'out of sync' error */
if (!$mysqli->query("SET @a:='this will not work'")) {
printf("Error: %s\n", $mysqli->error);
}
$result->close();
}
$mysqli->close();
?>
Procedural style
The above examples will output:
Table myCity successfully created.
Select returned 10 rows.
Error: Commands out of sync; You can't run this command now
See Also
* mysqli_real_query() - Execute an SQL query
* mysqli_multi_query() - Performs a query on the database
* mysqli_free_result() - Frees the memory associated with a result
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::real_connect
mysqli_real_connect
(PHP 5)
mysqli::real_connect -- mysqli_real_connect - Opens a connection to a
mysql server
Description
Object oriented style
bool mysqli::real_connect ([ string $host [, string $username [, string
$passwd [, string $dbname [, int $port [, string $socket [, int $flags
]]]]]]] )
Procedural style
bool mysqli_real_connect ( mysqli $link [, string $host [, string
$username [, string $passwd [, string $dbname [, int $port [, string
$socket [, int $flags ]]]]]]] )
Establish a connection to a MySQL database engine.
This function differs from mysqli_connect():
* mysqli_real_connect() needs a valid object which has to be created by
function mysqli_init().
* With the mysqli_options() function you can set various options for
connection.
* There is a flags parameter.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
host
Can be either a host name or an IP address. Passing the NULL value
or the string "localhost" to this parameter, the local host is
assumed. When possible, pipes will be used instead of the TCP/IP
protocol.
username
The MySQL user name.
passwd
If provided or NULL, the MySQL server will attempt to authenticate
the user against those user records which have no password only.
This allows one username to be used with different permissions
(depending on if a password as provided or not).
dbname
If provided will specify the default database to be used when
performing queries.
port
Specifies the port number to attempt to connect to the MySQL
server.
socket
Specifies the socket or named pipe that should be used.
Note:
Specifying the socket parameter will not explicitly determine
the type of connection to be used when connecting to the MySQL
server. How the connection is made to the MySQL database is
determined by the host parameter.
flags
With the parameter flags you can set different connection options:
Supported flags
Name Description
MYSQLI_CLIENT_COMPRESS Use compression protocol
MYSQLI_CLIENT_FOUND_ROWS return number of matched rows, not the
number of affected rows
Allow spaces after function names.
MYSQLI_CLIENT_IGNORE_SPACE Makes all function names reserved
words.
Allow interactive_timeout seconds
MYSQLI_CLIENT_INTERACTIVE (instead of wait_timeout seconds) of
inactivity before closing the
connection
MYSQLI_CLIENT_SSL Use SSL (encryption)
Note:
For security reasons the MULTI_STATEMENT flag is not supported
in PHP. If you want to execute multiple queries use the
mysqli_multi_query() function.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 mysqli::real_connect() example
Object oriented style
options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
die('Setting MYSQLI_INIT_COMMAND failed');
}
if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}
if (!$mysqli->real_connect('localhost', 'my_user', 'my_password', 'my_db')) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . $mysqli->host_info . "\n";
$mysqli->close();
?>
Object oriented style when extending mysqli class
host_info . "\n";
$db->close();
?>
Procedural style
The above examples will output:
Success... MySQL host info: localhost via TCP/IP
Notes
Note:
MySQLnd always assumes the server default charset. This charset is sent
during connection hand-shake/authentication, which mysqlnd will use.
Libmysql uses the default charset set in the my.cnf or by an explicit
call to mysqli_options() prior to calling mysqli_real_connect(), but
after mysqli_init().
See Also
* mysqli_connect() - Alias of mysqli::__construct
* mysqli_init() - Initializes MySQLi and returns a resource for use with
mysqli_real_connect()
* mysqli_options() - Set options
* mysqli_ssl_set() - Used for establishing secure connections using SSL
* mysqli_close() - Closes a previously opened database connection
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::real_escape_string
mysqli_real_escape_string
(PHP 5)
mysqli::real_escape_string -- mysqli_real_escape_string - Escapes special
characters in a string for use in an SQL statement, taking into account
the current charset of the connection
Description
Object oriented style
string mysqli::escape_string ( string $escapestr )
string mysqli::real_escape_string ( string $escapestr )
Procedural style
string mysqli_real_escape_string ( mysqli $link , string $escapestr )
This function is used to create a legal SQL string that you can use in an
SQL statement. The given string is encoded to an escaped SQL string,
taking into account the current character set of the connection.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
escapestr
The string to be escaped.
Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and
Control-Z.
Return Values
Returns an escaped string.
Examples
Example #1 mysqli::real_escape_string() example
Object oriented style
query("CREATE TEMPORARY TABLE myCity LIKE City");
$city = "'s Hertogenbosch";
/* this query will fail, cause we didn't escape $city */
if (!$mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
printf("Error: %s\n", $mysqli->sqlstate);
}
$city = $mysqli->real_escape_string($city);
/* this query with escaped $city will work */
if ($mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
printf("%d Row inserted.\n", $mysqli->affected_rows);
}
$mysqli->close();
?>
Procedural style
The above examples will output:
Error: 42000
1 Row inserted.
See Also
* mysqli_character_set_name() - Returns the default character set for
the database connection
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::real_query
mysqli_real_query
(PHP 5)
mysqli::real_query -- mysqli_real_query - Execute an SQL query
Description
Object oriented style
bool mysqli::real_query ( string $query )
Procedural style
bool mysqli_real_query ( mysqli $link , string $query )
Executes a single query against the database whose result can then be
retrieved or stored using the mysqli_store_result() or mysqli_use_result()
functions.
In order to determine if a given query should return a result set or not,
see mysqli_field_count().
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
query
The query, as a string.
Data inside the query should be properly escaped.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* mysqli_query() - Performs a query on the database
* mysqli_store_result() - Transfers a result set from the last query
* mysqli_use_result() - Initiate a result set retrieval
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::reap_async_query
mysqli_reap_async_query
(PHP 5 >= 5.3.0)
mysqli::reap_async_query -- mysqli_reap_async_query - Get result from
async query
Description
Object oriented style
public mysqli_result mysqli::reap_async_query ( void )
Procedural style
mysqli_result mysqli_reap_async_query ( mysql $link )
Warning
This function is currently not documented; only its argument list is
available.
Get result from async query. Available only with mysqlnd.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
Returns mysqli_result in success, FALSE otherwise.
See Also
* mysqli_poll() - Poll connections
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::rollback
mysqli_rollback
(PHP 5)
mysqli::rollback -- mysqli_rollback - Rolls back current transaction
Description
Object oriented style
bool mysqli::rollback ( void )
Procedural style
bool mysqli_rollback ( mysqli $link )
Rollbacks the current transaction for the database.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 mysqli::rollback() example
Object oriented style
autocommit(FALSE);
$mysqli->query("CREATE TABLE myCity LIKE City");
$mysqli->query("ALTER TABLE myCity Type=InnoDB");
$mysqli->query("INSERT INTO myCity SELECT * FROM City LIMIT 50");
/* commit insert */
$mysqli->commit();
/* delete all rows */
$mysqli->query("DELETE FROM myCity");
if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) {
$row = $result->fetch_row();
printf("%d rows in table myCity.\n", $row[0]);
/* Free result */
$result->close();
}
/* Rollback */
$mysqli->rollback();
if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) {
$row = $result->fetch_row();
printf("%d rows in table myCity (after rollback).\n", $row[0]);
/* Free result */
$result->close();
}
/* Drop table myCity */
$mysqli->query("DROP TABLE myCity");
$mysqli->close();
?>
Procedural style
The above examples will output:
0 rows in table myCity.
50 rows in table myCity (after rollback).
See Also
* mysqli_commit() - Commits the current transaction
* mysqli_autocommit() - Turns on or off auto-commiting database
modifications
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::select_db
mysqli_select_db
(PHP 5)
mysqli::select_db -- mysqli_select_db - Selects the default database for
database queries
Description
Object oriented style
bool mysqli::select_db ( string $dbname )
Procedural style
bool mysqli_select_db ( mysqli $link , string $dbname )
Selects the default database to be used when performing queries against
the database connection.
Note:
This function should only be used to change the default database for the
connection. You can select the default database with 4th parameter in
mysqli_connect().
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
dbname
The database name.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 mysqli::select_db() example
Object oriented style
query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
/* change db to world db */
$mysqli->select_db("world");
/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
$mysqli->close();
?>
Procedural style
The above examples will output:
Default database is test.
Default database is world.
See Also
* mysqli_connect() - Alias of mysqli::__construct
* mysqli_real_connect() - Opens a connection to a mysql server
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::set_charset
mysqli_set_charset
(PHP 5 >= 5.0.5)
mysqli::set_charset -- mysqli_set_charset - Sets the default client
character set
Description
Object oriented style
bool mysqli::set_charset ( string $charset )
Procedural style
bool mysqli_set_charset ( mysqli $link , string $charset )
Sets the default character set to be used when sending data from and to
the database server.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
charset
The charset to be set as default.
Return Values
Returns TRUE on success or FALSE on failure.
Notes
Note:
To use this function on a Windows platform you need MySQL client library
version 4.1.11 or above (for MySQL 5.0 you need 5.0.6 or above).
Note:
This is the preferred way to change the charset. Using mysqli::query()
to execute SET NAMES .. is not recommended.
Examples
Example #1 mysqli::set_charset() example
Object oriented style
set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
} else {
printf("Current character set: %s\n", $mysqli->character_set_name());
}
$mysqli->close();
?>
Procedural style
The above examples will output:
Current character set: utf8
See Also
* mysqli_character_set_name() - Returns the default character set for
the database connection
* mysqli_real_escape_string() - Escapes special characters in a string
for use in an SQL statement, taking into account the current charset
of the connection
* >> List of character sets that MySQL supports
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::set_local_infile_default
mysqli_set_local_infile_default
(PHP 5)
mysqli::set_local_infile_default -- mysqli_set_local_infile_default -
Unsets user defined handler for load local infile command
Description
void mysqli_set_local_infile_default ( mysqli $link )
Deactivates a LOAD DATA INFILE LOCAL handler previously set with
mysqli_set_local_infile_handler().
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
No value is returned.
Examples
See mysqli_set_local_infile_handler() examples
See Also
* mysqli_set_local_infile_handler() - Set callback function for LOAD
DATA LOCAL INFILE command
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::set_local_infile_handler
mysqli_set_local_infile_handler
(PHP 5)
mysqli::set_local_infile_handler -- mysqli_set_local_infile_handler - Set
callback function for LOAD DATA LOCAL INFILE command
Description
Object oriented style
bool mysqli::set_local_infile_handler ( mysqli $link , callback $read_func
)
Procedural style
bool mysqli_set_local_infile_handler ( mysqli $link , callback $read_func
)
Set callback function for LOAD DATA LOCAL INFILE command
The callbacks task is to read input from the file specified in the LOAD
DATA LOCAL INFILE and to reformat it into the format understood by LOAD
DATA INFILE.
The returned data needs to match the format specified in the LOAD DATA
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
read_func
A callback function or object method taking the following
parameters:
stream
A PHP stream associated with the SQL commands INFILE
&buffer
A string buffer to store the rewritten input into
buflen
The maximum number of characters to be stored in the
buffer
&errormsg
If an error occurs you can store an error message in
here
The callback function should return the number of characters stored in the
buffer or a negative value if an error occurred.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 mysqli::set_local_infile_handler() example
Object oriented style
real_connect("localhost","root","","test");
function callme($stream, &$buffer, $buflen, &$errmsg)
{
$buffer = fgets($stream);
echo $buffer;
// convert to upper case and replace "," delimiter with [TAB]
$buffer = strtoupper(str_replace(",", "\t", $buffer));
return strlen($buffer);
}
echo "Input:\n";
$db->set_local_infile_handler("callme");
$db->query("LOAD DATA LOCAL INFILE 'input.txt' INTO TABLE t1");
$db->set_local_infile_default();
$res = $db->query("SELECT * FROM t1");
echo "\nResult:\n";
while ($row = $res->fetch_assoc()) {
echo join(",", $row)."\n";
}
?>
Procedural style
The above examples will output:
Input:
23,foo
42,bar
Output:
23,FOO
42,BAR
See Also
* mysqli_set_local_infile_default() - Unsets user defined handler for
load local infile command
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::sqlstate
mysqli_sqlstate
(PHP 5)
mysqli::sqlstate -- mysqli_sqlstate - Returns the SQLSTATE error from
previous MySQL operation
Description
Object oriented style
string $mysqli->sqlstate;
Procedural style
string mysqli_sqlstate ( mysqli $link )
Returns a string containing the SQLSTATE error code for the last error.
The error code consists of five characters. '00000' means no error. The
values are specified by ANSI SQL and ODBC. For a list of possible values,
see >> http://dev.mysql.com/doc/mysql/en/error-handling.html.
Note:
Note that not all MySQL errors are yet mapped to SQLSTATE's. The value
HY000 (general error) is used for unmapped errors.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
Returns a string containing the SQLSTATE error code for the last error.
The error code consists of five characters. '00000' means no error.
Examples
Example #1 mysqli->sqlstate example
Object oriented style
query("CREATE TABLE City (ID INT, Name VARCHAR(30))")) {
printf("Error - SQLSTATE %s.\n", $mysqli->sqlstate);
}
$mysqli->close();
?>
Procedural style
The above examples will output:
Error - SQLSTATE 42S01.
See Also
* mysqli_errno() - Returns the error code for the most recent function
call
* mysqli_error() - Returns a string description of the last error
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::ssl_set
mysqli_ssl_set
(PHP 5)
mysqli::ssl_set -- mysqli_ssl_set - Used for establishing secure
connections using SSL
Description
Object oriented style
bool mysqli::ssl_set ( string $key , string $cert , string $ca , string
$capath , string $cipher )
Procedural style
bool mysqli_ssl_set ( mysqli $link , string $key , string $cert , string
$ca , string $capath , string $cipher )
Used for establishing secure connections using SSL. It must be called
before mysqli_real_connect(). This function does nothing unless OpenSSL
support is enabled.
Note that MySQL Native Driver does not support SSL before PHP 5.3.3, so
calling this function when using MySQL Native Driver will result in an
error. MySQL Native Driver is enabled by default on Microsoft Windows from
PHP version 5.3 onwards.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
key
The path name to the key file.
cert
The path name to the certificate file.
ca
The path name to the certificate authority file.
capath
The pathname to a directory that contains trusted SSL CA
certificates in PEM format.
cipher
A list of allowable ciphers to use for SSL encryption.
Any unused SSL parameters may be given as NULL
Return Values
This function always returns TRUE value. If SSL setup is incorrect
mysqli_real_connect() will return an error when you attempt to connect.
See Also
* mysqli_options() - Set options
* mysqli_real_connect() - Opens a connection to a mysql server
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::stat
mysqli_stat
(PHP 5)
mysqli::stat -- mysqli_stat - Gets the current system status
Description
Object oriented style
string mysqli::stat ( void )
Procedural style
string mysqli_stat ( mysqli $link )
mysqli_stat() returns a string containing information similar to that
provided by the 'mysqladmin status' command. This includes uptime in
seconds and the number of running threads, questions, reloads, and open
tables.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
A string describing the server status. FALSE if an error occurred.
Examples
Example #1 mysqli::stat() example
Object oriented style
stat());
$mysqli->close();
?>
Procedural style
The above examples will output:
System status: Uptime: 272 Threads: 1 Questions: 5340 Slow queries: 0
Opens: 13 Flush tables: 1 Open tables: 0 Queries per second avg: 19.632
Memory in use: 8496K Max memory used: 8560K
See Also
* mysqli_get_server_info() - Returns the version of the MySQL server
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::stmt_init
mysqli_stmt_init
(PHP 5)
mysqli::stmt_init -- mysqli_stmt_init - Initializes a statement and
returns an object for use with mysqli_stmt_prepare
Description
Object oriented style
mysqli_stmt mysqli::stmt_init ( void )
Procedural style
mysqli_stmt mysqli_stmt_init ( mysqli $link )
Allocates and initializes a statement object suitable for
mysqli_stmt_prepare().
Note:
Any subsequent calls to any mysqli_stmt function will fail until
mysqli_stmt_prepare() was called.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
Returns an object.
See Also
* mysqli_stmt_prepare() - Prepare an SQL statement for execution
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::store_result
mysqli_store_result
(PHP 5)
mysqli::store_result -- mysqli_store_result - Transfers a result set from
the last query
Description
Object oriented style
mysqli_result mysqli::store_result ( void )
Procedural style
mysqli_result mysqli_store_result ( mysqli $link )
Transfers the result set from the last query on the database connection
represented by the link parameter to be used with the mysqli_data_seek()
function.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
Returns a buffered result object or FALSE if an error occurred.
Note:
mysqli_store_result() returns FALSE in case the query didn't return a
result set (if the query was, for example an INSERT statement). This
function also returns FALSE if the reading of the result set failed. You
can check if you have got an error by checking if mysqli_error() doesn't
return an empty string, if mysqli_errno() returns a non zero value, or
if mysqli_field_count() returns a non zero value. Also possible reason
for this function returning FALSE after successful call to
mysqli_query() can be too large result set (memory for it cannot be
allocated). If mysqli_field_count() returns a non-zero value, the
statement should have produced a non-empty result set.
Notes
Note:
Although it is always good practice to free the memory used by the
result of a query using the mysqli_free_result() function, when
transferring large result sets using the mysqli_store_result() this
becomes particularly important.
Examples
See mysqli_multi_query().
See Also
* mysqli_real_query() - Execute an SQL query
* mysqli_use_result() - Initiate a result set retrieval
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::thread_id
mysqli_thread_id
(PHP 5)
mysqli::thread_id -- mysqli_thread_id - Returns the thread ID for the
current connection
Description
Object oriented style
int $mysqli->thread_id;
Procedural style
int mysqli_thread_id ( mysqli $link )
The mysqli_thread_id() function returns the thread ID for the current
connection which can then be killed using the mysqli_kill() function. If
the connection is lost and you reconnect with mysqli_ping(), the thread ID
will be other. Therefore you should get the thread ID only when you need
it.
Note:
The thread ID is assigned on a connection-by-connection basis. Hence, if
the connection is broken and then re-established a new thread ID will be
assigned.
To kill a running query you can use the SQL command KILL QUERY
processid.
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
Returns the Thread ID for the current connection.
Examples
Example #1 mysqli->thread_id example
Object oriented style
thread_id;
/* Kill connection */
$mysqli->kill($thread_id);
/* This should produce an error */
if (!$mysqli->query("CREATE TABLE myCity LIKE City")) {
printf("Error: %s\n", $mysqli->error);
exit;
}
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
Error: MySQL server has gone away
See Also
* mysqli_kill() - Asks the server to kill a MySQL thread
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::thread_safe
mysqli_thread_safe
(PHP 5)
mysqli::thread_safe -- mysqli_thread_safe - Returns whether thread safety
is given or not
Description
Procedural style
bool mysqli_thread_safe ( void )
Tells whether the client library is compiled as thread-safe.
Return Values
TRUE if the client library is thread-safe, otherwise FALSE.
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::use_result
mysqli_use_result
(PHP 5)
mysqli::use_result -- mysqli_use_result - Initiate a result set retrieval
Description
Object oriented style
mysqli_result mysqli::use_result ( void )
Procedural style
mysqli_result mysqli_use_result ( mysqli $link )
Used to initiate the retrieval of a result set from the last query
executed using the mysqli_real_query() function on the database
connection.
Either this or the mysqli_store_result() function must be called before
the results of a query can be retrieved, and one or the other must be
called to prevent the next query on that database connection from failing.
Note:
The mysqli_use_result() function does not transfer the entire result set
from the database and hence cannot be used functions such as
mysqli_data_seek() to move to a particular row within the set. To use
this functionality, the result set must be stored using
mysqli_store_result(). One should not use mysqli_use_result() if a lot
of processing on the client side is performed, since this will tie up
the server and prevent other threads from updating any tables from which
the data is being fetched.
Return Values
Returns an unbuffered result object or FALSE if an error occurred.
Examples
Example #1 mysqli::use_result() example
Object oriented style
multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->use_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->close();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
my_user@localhost
-----------------
Amersfoort
Maastricht
Dordrecht
Leiden
Haarlemmermeer
See Also
* mysqli_real_query() - Execute an SQL query
* mysqli_store_result() - Transfers a result set from the last query
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli::warning_count
mysqli_warning_count
(PHP 5)
mysqli::warning_count -- mysqli_warning_count - Returns the number of
warnings from the last query for the given link
Description
Object oriented style
int $mysqli->warning_count;
Procedural style
int mysqli_warning_count ( mysqli $link )
Returns the number of warnings from the last query in the connection.
Note:
For retrieving warning messages you can use the SQL command SHOW
WARNINGS [limit row_count].
Parameters
link
Procedural style only: A link identifier returned by
mysqli_connect() or mysqli_init()
Return Values
Number of warnings or zero if there are no warnings.
Examples
Example #1 mysqli->warning_count example
Object oriented style
query("CREATE TABLE myCity LIKE City");
/* a remarkable city in Wales */
$query = "INSERT INTO myCity (CountryCode, Name) VALUES('GBR',
'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";
$mysqli->query($query);
if ($mysqli->warning_count) {
if ($result = $mysqli->query("SHOW WARNINGS")) {
$row = $result->fetch_row();
printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
$result->close();
}
}
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
Warning (1264): Data truncated for column 'Name' at row 1
See Also
* mysqli_errno() - Returns the error code for the most recent function
call
* mysqli_error() - Returns a string description of the last error
* mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL
operation
----------------------------------------------------------------------
Table of Contents
* mysqli::affected_rows - Gets the number of affected rows in a previous
MySQL operation
* mysqli::autocommit - Turns on or off auto-commiting database
modifications
* mysqli::change_user - Changes the user of the specified database
connection
* mysqli::character_set_name - Returns the default character set for the
database connection
* mysqli::client_info - Returns the MySQL client version as a string
* mysqli::client_version - Get MySQL client info
* mysqli::close - Closes a previously opened database connection
* mysqli::commit - Commits the current transaction
* mysqli::connect_errno - Returns the error code from last connect call
* mysqli::connect_error - Returns a string description of the last
connect error
* mysqli::__construct - Open a new connection to the MySQL server
* mysqli::debug - Performs debugging operations
* mysqli::dump_debug_info - Dump debugging information into the log
* mysqli::errno - Returns the error code for the most recent function
call
* mysqli::error - Returns a string description of the last error
* mysqli::field_count - Returns the number of columns for the most
recent query
* mysqli::get_charset - Returns a character set object
* mysqli::get_client_info - Returns the MySQL client version as a string
* mysqli_get_client_stats - Returns client per-process statistics
* mysqli::client_version - Get MySQL client info
* mysqli::get_connection_stats - Returns statistics about the client
connection
* mysqli::host_info - Returns a string representing the type of
connection used
* mysqli::protocol_version - Returns the version of the MySQL protocol
used
* mysqli::server_info - Returns the version of the MySQL server
* mysqli::server_version - Returns the version of the MySQL server as an
integer
* mysqli::get_warnings - Get result of SHOW WARNINGS
* mysqli::info - Retrieves information about the most recently executed
query
* mysqli::init - Initializes MySQLi and returns a resource for use with
mysqli_real_connect()
* mysqli::insert_id - Returns the auto generated id used in the last
query
* mysqli::kill - Asks the server to kill a MySQL thread
* mysqli::more_results - Check if there are any more query results from
a multi query
* mysqli::multi_query - Performs a query on the database
* mysqli::next_result - Prepare next result from multi_query
* mysqli::options - Set options
* mysqli::ping - Pings a server connection, or tries to reconnect if the
connection has gone down
* mysqli::poll - Poll connections
* mysqli::prepare - Prepare an SQL statement for execution
* mysqli::query - Performs a query on the database
* mysqli::real_connect - Opens a connection to a mysql server
* mysqli::real_escape_string - Escapes special characters in a string
for use in an SQL statement, taking into account the current charset
of the connection
* mysqli::real_query - Execute an SQL query
* mysqli::reap_async_query - Get result from async query
* mysqli::rollback - Rolls back current transaction
* mysqli::select_db - Selects the default database for database queries
* mysqli::set_charset - Sets the default client character set
* mysqli::set_local_infile_default - Unsets user defined handler for
load local infile command
* mysqli::set_local_infile_handler - Set callback function for LOAD DATA
LOCAL INFILE command
* mysqli::sqlstate - Returns the SQLSTATE error from previous MySQL
operation
* mysqli::ssl_set - Used for establishing secure connections using SSL
* mysqli::stat - Gets the current system status
* mysqli::stmt_init - Initializes a statement and returns an object for
use with mysqli_stmt_prepare
* mysqli::store_result - Transfers a result set from the last query
* mysqli::thread_id - Returns the thread ID for the current connection
* mysqli::thread_safe - Returns whether thread safety is given or not
* mysqli::use_result - Initiate a result set retrieval
* mysqli::warning_count - Returns the number of warnings from the last
query for the given link
----------------------------------------------------------------------
----------------------------------------------------------------------
The MySQLi_STMT class
Introduction
Represents a prepared statement.
Class synopsis
MySQLi_STMT {
/* Properties */
int $MySQLi_STMT->affected_rows;
int $errno;
string $error;
int $field_count;
int $insert_id;
int $num_rows;
int $param_count;
string $sqlstate;
/* Methods */
int mysqli_stmt_affected_rows ( mysqli_stmt $stmt )
int mysqli_stmt::attr_get ( int $attr )
bool mysqli_stmt::attr_set ( int $attr , int $mode )
bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$...
] )
bool mysqli_stmt::bind_result ( mixed &$var1 [, mixed &$... ] )
bool mysqli_stmt::close ( void )
void mysqli_stmt::data_seek ( int $offset )
int mysqli_stmt_errno ( mysqli_stmt $stmt )
string mysqli_stmt_error ( mysqli_stmt $stmt )
bool mysqli_stmt::execute ( void )
bool mysqli_stmt::fetch ( void )
int mysqli_stmt_field_count ( mysqli_stmt $stmt )
void mysqli_stmt::free_result ( void )
mysqli_result mysqli_stmt::get_result ( void )
object mysqli_stmt::get_warnings ( mysqli_stmt $stmt )
mixed mysqli_stmt_insert_id ( mysqli_stmt $stmt )
int mysqli_stmt_num_rows ( mysqli_stmt $stmt )
int mysqli_stmt_param_count ( mysqli_stmt $stmt )
mixed mysqli_stmt::prepare ( string $query )
bool mysqli_stmt::reset ( void )
mysqli_result mysqli_stmt::result_metadata ( void )
bool mysqli_stmt::send_long_data ( int $param_nr , string $data )
string mysqli_stmt_sqlstate ( mysqli_stmt $stmt )
bool mysqli_stmt::store_result ( void )
}
----------------------------------------------------------------------
mysqli_stmt::affected_rows
mysqli_stmt_affected_rows
(PHP 5)
mysqli_stmt::affected_rows -- mysqli_stmt_affected_rows - Returns the
total number of rows changed, deleted, or inserted by the last executed
statement
Description
Object oriented style
int $mysqli_stmt->affected_rows;
Procedural style
int mysqli_stmt_affected_rows ( mysqli_stmt $stmt )
Returns the number of rows affected by INSERT, UPDATE, or DELETE query.
This function only works with queries which update a table. In order to
get the number of rows from a SELECT query, use mysqli_stmt_num_rows()
instead.
Parameters
stmt
Procedural style only: A statement identifier returned by
mysqli_stmt_init().
Return Values
An integer greater than zero indicates the number of rows affected or
retrieved. Zero indicates that no records where updated for an
UPDATE/DELETE statement, no rows matched the WHERE clause in the query or
that no query has yet been executed. -1 indicates that the query has
returned an error. NULL indicates an invalid argument was supplied to the
function.
Note:
If the number of affected rows is greater than maximal PHP int value,
the number of affected rows will be returned as a string value.
Examples
Example #1 Object oriented style
query("CREATE TEMPORARY TABLE myCountry LIKE Country");
$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";
/* prepare statement */
if ($stmt = $mysqli->prepare($query)) {
/* Bind variable for placeholder */
$code = 'A%';
$stmt->bind_param("s", $code);
/* execute statement */
$stmt->execute();
printf("rows inserted: %d\n", $stmt->affected_rows);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Example #2 Procedural style
The above examples will output:
rows inserted: 17
See Also
* mysqli_stmt_num_rows() - Return the number of rows in statements
result set
* mysqli_prepare() - Prepare an SQL statement for execution
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::attr_get
mysqli_stmt_attr_get
(PHP 5)
mysqli_stmt::attr_get -- mysqli_stmt_attr_get - Used to get the current
value of a statement attribute
Description
Object oriented style
int mysqli_stmt::attr_get ( int $attr )
Procedural style
int mysqli_stmt_attr_get ( mysqli_stmt $stmt , int $attr )
Gets the current value of a statement attribute.
Parameters
stmt
Procedural style only: A statement identifier returned by
mysqli_stmt_init().
attr
The attribute that you want to get.
Return Values
Returns FALSE if the attribute is not found, otherwise returns the value
of the attribute.
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::attr_set
mysqli_stmt_attr_set
(PHP 5)
mysqli_stmt::attr_set -- mysqli_stmt_attr_set - Used to modify the
behavior of a prepared statement
Description
Object oriented style
bool mysqli_stmt::attr_set ( int $attr , int $mode )
Procedural style
bool mysqli_stmt_attr_set ( mysqli_stmt $stmt , int $attr , int $mode )
Used to modify the behavior of a prepared statement. This function may be
called multiple times to set several attributes.
Parameters
stmt
Procedural style only: A statement identifier returned by
mysqli_stmt_init().
attr
The attribute that you want to set. It can have one of the
following values:
Attribute values
Character Description
If set to 1, causes
MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH mysqli_stmt_store_result() to
update the metadata
MYSQL_FIELD->max_length value.
Type of cursor to open for
statement when
mysqli_stmt_execute() is
MYSQLI_STMT_ATTR_CURSOR_TYPE invoked. mode can be
MYSQLI_CURSOR_TYPE_NO_CURSOR
(the default) or
MYSQLI_CURSOR_TYPE_READ_ONLY.
Number of rows to fetch from
server at a time when using a
MYSQLI_STMT_ATTR_PREFETCH_ROWS cursor. mode can be in the
range from 1 to the maximum
value of unsigned long. The
default is 1.
If you use the MYSQLI_STMT_ATTR_CURSOR_TYPE option with
MYSQLI_CURSOR_TYPE_READ_ONLY, a cursor is opened for the statement
when you invoke mysqli_stmt_execute(). If there is already an open
cursor from a previous mysqli_stmt_execute() call, it closes the
cursor before opening a new one. mysqli_stmt_reset() also closes
any open cursor before preparing the statement for re-execution.
mysqli_stmt_free_result() closes any open cursor.
If you open a cursor for a prepared statement,
mysqli_stmt_store_result() is unnecessary.
mode
The value to assign to the attribute.
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::bind_param
mysqli_stmt_bind_param
(PHP 5)
mysqli_stmt::bind_param -- mysqli_stmt_bind_param - Binds variables to a
prepared statement as parameters
Description
Object oriented style
bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$...
] )
Procedural style
bool mysqli_stmt_bind_param ( mysqli_stmt $stmt , string $types , mixed
&$var1 [, mixed &$... ] )
Bind variables for the parameter markers in the SQL statement that was
passed to mysqli_prepare().
Note:
If data size of a variable exceeds max. allowed packet size
(max_allowed_packet), you have to specify b in types and use
mysqli_stmt_send_long_data() to send the data in packets.
Note:
Care must be taken when using mysqli_stmt_bind_param() in conjunction
with call_user_func_array(). Note that mysqli_stmt_bind_param() requires
parameters to be passed by reference, whereas call_user_func_array() can
accept as a parameter a list of variables that can represent references
or values.
Parameters
stmt
Procedural style only: A statement identifier returned by
mysqli_stmt_init().
types
A string that contains one or more characters which specify the
types for the corresponding bind variables:
Type specification chars
Character Description
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in
packets
var1
The number of variables and length of string types must match the
parameters in the statement.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Object oriented style
prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);
$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
/* Clean up table CountryLanguage */
$mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d Row deleted.\n", $mysqli->affected_rows);
/* close connection */
$mysqli->close();
?>
Example #2 Procedural style
The above examples will output:
1 Row inserted.
1 Row deleted.
See Also
* mysqli_stmt_bind_result() - Binds variables to a prepared statement
for result storage
* mysqli_stmt_execute() - Executes a prepared Query
* mysqli_stmt_fetch() - Fetch results from a prepared statement into the
bound variables
* mysqli_prepare() - Prepare an SQL statement for execution
* mysqli_stmt_send_long_data() - Send data in blocks
* mysqli_stmt_errno() - Returns the error code for the most recent
statement call
* mysqli_stmt_error() - Returns a string description for last statement
error
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::bind_result
mysqli_stmt_bind_result
(PHP 5)
mysqli_stmt::bind_result -- mysqli_stmt_bind_result - Binds variables to a
prepared statement for result storage
Description
Object oriented style
bool mysqli_stmt::bind_result ( mixed &$var1 [, mixed &$... ] )
Procedural style
bool mysqli_stmt_bind_result ( mysqli_stmt $stmt , mixed &$var1 [, mixed
&$... ] )
Binds columns in the result set to variables.
When mysqli_stmt_fetch() is called to fetch data, the MySQL client/server
protocol places the data for the bound columns into the specified
variables var1, ....
Note:
Note that all columns must be bound after mysqli_stmt_execute() and
prior to calling mysqli_stmt_fetch(). Depending on column types bound
variables can silently change to the corresponding PHP type.
A column can be bound or rebound at any time, even after a result set
has been partially retrieved. The new binding takes effect the next time
mysqli_stmt_fetch() is called.
Parameters
stmt
Procedural style only: A statement identifier returned by
mysqli_stmt_init().
var1
The variable to be bound.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Object oriented style
prepare("SELECT Code, Name FROM Country ORDER BY Name LIMIT 5")) {
$stmt->execute();
/* bind variables to prepared statement */
$stmt->bind_result($col1, $col2);
/* fetch values */
while ($stmt->fetch()) {
printf("%s %s\n", $col1, $col2);
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Example #2 Procedural style
The above examples will output:
AFG Afghanistan
ALB Albania
DZA Algeria
ASM American Samoa
AND Andorra
See Also
* mysqli_stmt_bind_param() - Binds variables to a prepared statement as
parameters
* mysqli_stmt_execute() - Executes a prepared Query
* mysqli_stmt_fetch() - Fetch results from a prepared statement into the
bound variables
* mysqli_prepare() - Prepare an SQL statement for execution
* mysqli_stmt_prepare() - Prepare an SQL statement for execution
* mysqli_stmt_init() - Initializes a statement and returns an object for
use with mysqli_stmt_prepare
* mysqli_stmt_errno() - Returns the error code for the most recent
statement call
* mysqli_stmt_error() - Returns a string description for last statement
error
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::close
mysqli_stmt_close
(PHP 5)
mysqli_stmt::close -- mysqli_stmt_close - Closes a prepared statement
Description
Object oriented style
bool mysqli_stmt::close ( void )
Procedural style
bool mysqli_stmt_close ( mysqli_stmt $stmt )
Closes a prepared statement. mysqli_stmt_close() also deallocates the
statement handle. If the current statement has pending or unread results,
this function cancels them so that the next query can be executed.
Parameters
stmt
Procedural style only: A statement identifier returned by
mysqli_stmt_init().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* mysqli_prepare() - Prepare an SQL statement for execution
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::data_seek
mysqli_stmt_data_seek
(PHP 5)
mysqli_stmt::data_seek -- mysqli_stmt_data_seek - Seeks to an arbitrary
row in statement result set
Description
Object oriented style
void mysqli_stmt::data_seek ( int $offset )
Procedural style
void mysqli_stmt_data_seek ( mysqli_stmt $stmt , int $offset )
Seeks to an arbitrary result pointer in the statement result set.
mysqli_stmt_store_result() must be called prior to
mysqli_stmt_data_seek().
Parameters
stmt
Procedural style only: A statement identifier returned by
mysqli_stmt_init().
offset
Must be between zero and the total number of rows minus one (0..
mysqli_stmt_num_rows() - 1).
Return Values
No value is returned.
Examples
Example #1 Object oriented style
prepare($query)) {
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($name, $code);
/* store result */
$stmt->store_result();
/* seek to row no. 400 */
$stmt->data_seek(399);
/* fetch values */
$stmt->fetch();
printf ("City: %s Countrycode: %s\n", $name, $code);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Example #2 Procedural style
The above examples will output:
City: Benin City Countrycode: NGA
See Also
* mysqli_prepare() - Prepare an SQL statement for execution
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::errno
mysqli_stmt_errno
(PHP 5)
mysqli_stmt::errno -- mysqli_stmt_errno - Returns the error code for the
most recent statement call
Description
Object oriented style
int $mysqli_stmt->errno;
Procedural style
int mysqli_stmt_errno ( mysqli_stmt $stmt )
Returns the error code for the most recently invoked statement function
that can succeed or fail.
Client error message numbers are listed in the MySQL errmsg.h header file,
server error message numbers are listed in mysqld_error.h. In the MySQL
source distribution you can find a complete list of error messages and
error numbers in the file Docs/mysqld_error.txt.
Parameters
stmt
Procedural style only: A statement identifier returned by
mysqli_stmt_init().
Return Values
An error code value. Zero means no error occurred.
Examples
Example #1 Object oriented style
query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");
$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {
/* drop table */
$mysqli->query("DROP TABLE myCountry");
/* execute query */
$stmt->execute();
printf("Error: %d.\n", $stmt->errno);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Example #2 Procedural style
The above examples will output:
Error: 1146.
See Also
* mysqli_stmt_error() - Returns a string description for last statement
error
* mysqli_stmt_sqlstate() - Returns SQLSTATE error from previous
statement operation
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::error
mysqli_stmt_error
(PHP 5)
mysqli_stmt::error -- mysqli_stmt_error - Returns a string description for
last statement error
Description
Object oriented style
string $mysqli_stmt->error;
Procedural style
string mysqli_stmt_error ( mysqli_stmt $stmt )
Returns a containing the error message for the most recently invoked
statement function that can succeed or fail.
Parameters
stmt
Procedural style only: A statement identifier returned by
mysqli_stmt_init().
Return Values
A string that describes the error. An empty string if no error occurred.
Examples
Example #1 Object oriented style
query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");
$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {
/* drop table */
$mysqli->query("DROP TABLE myCountry");
/* execute query */
$stmt->execute();
printf("Error: %s.\n", $stmt->error);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Example #2 Procedural style
The above examples will output:
Error: Table 'world.myCountry' doesn't exist.
See Also
* mysqli_stmt_errno() - Returns the error code for the most recent
statement call
* mysqli_stmt_sqlstate() - Returns SQLSTATE error from previous
statement operation
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::execute
mysqli_stmt_execute
(PHP 5)
mysqli_stmt::execute -- mysqli_stmt_execute - Executes a prepared Query
Description
Object oriented style
bool mysqli_stmt::execute ( void )
Procedural style
bool mysqli_stmt_execute ( mysqli_stmt $stmt )
Executes a query that has been previously prepared using the
mysqli_prepare() function. When executed any parameter markers which exist
will automatically be replaced with the appropriate data.
If the statement is UPDATE, DELETE, or INSERT, the total number of
affected rows can be determined by using the mysqli_stmt_affected_rows()
function. Likewise, if the query yields a result set the
mysqli_stmt_fetch() function is used.
Note:
When using mysqli_stmt_execute(), the mysqli_stmt_fetch() function must
be used to fetch the data prior to performing any additional queries.
Parameters
stmt
Procedural style only: A statement identifier returned by
mysqli_stmt_init().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Object oriented style
query("CREATE TABLE myCity LIKE City");
/* Prepare an insert statement */
$query = "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sss", $val1, $val2, $val3);
$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';
/* Execute the statement */
$stmt->execute();
$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';
/* Execute the statement */
$stmt->execute();
/* close statement */
$stmt->close();
/* retrieve all rows from myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_row()) {
printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
}
/* free result set */
$result->close();
}
/* remove table */
$mysqli->query("DROP TABLE myCity");
/* close connection */
$mysqli->close();
?>
Example #2 Procedural style
The above examples will output:
Stuttgart (DEU,Baden-Wuerttemberg)
Bordeaux (FRA,Aquitaine)
See Also
* mysqli_prepare() - Prepare an SQL statement for execution
* mysqli_stmt_bind_param() - Binds variables to a prepared statement as
parameters
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::fetch
mysqli_stmt_fetch
(PHP 5)
mysqli_stmt::fetch -- mysqli_stmt_fetch - Fetch results from a prepared
statement into the bound variables
Description
Object oriented style
bool mysqli_stmt::fetch ( void )
Procedural style
bool mysqli_stmt_fetch ( mysqli_stmt $stmt )
Fetch the result from a prepared statement into the variables bound by
mysqli_stmt_bind_result().
Note:
Note that all columns must be bound by the application before calling
mysqli_stmt_fetch().
Note:
Data are transferred unbuffered without calling
mysqli_stmt_store_result() which can decrease performance (but reduces
memory cost).
Parameters
stmt
Procedural style only: A statement identifier returned by
mysqli_stmt_init().
Return Values
Return Values
Value Description
TRUE Success. Data has been fetched
FALSE Error occurred
NULL No more rows/data exists or data truncation occurred
Examples
Example #1 Object oriented style
prepare($query)) {
/* execute statement */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($name, $code);
/* fetch values */
while ($stmt->fetch()) {
printf ("%s (%s)\n", $name, $code);
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Example #2 Procedural style
The above examples will output:
Rockford (USA)
Tallahassee (USA)
Salinas (USA)
Santa Clarita (USA)
Springfield (USA)
See Also
* mysqli_prepare() - Prepare an SQL statement for execution
* mysqli_stmt_errno() - Returns the error code for the most recent
statement call
* mysqli_stmt_error() - Returns a string description for last statement
error
* mysqli_stmt_bind_result() - Binds variables to a prepared statement
for result storage
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::field_count
mysqli_stmt_field_count
(PHP 5)
mysqli_stmt::field_count -- mysqli_stmt_field_count - Returns the number
of field in the given statement
Description
Object oriented style
int $mysqli_stmt->field_count;
Procedural style
int mysqli_stmt_field_count ( mysqli_stmt $stmt )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::free_result
mysqli_stmt_free_result
(PHP 5)
mysqli_stmt::free_result -- mysqli_stmt_free_result - Frees stored result
memory for the given statement handle
Description
Object oriented style
void mysqli_stmt::free_result ( void )
Procedural style
void mysqli_stmt_free_result ( mysqli_stmt $stmt )
Frees the result memory associated with the statement, which was allocated
by mysqli_stmt_store_result().
Parameters
stmt
Procedural style only: A statement identifier returned by
mysqli_stmt_init().
Return Values
No value is returned.
See Also
* mysqli_stmt_store_result() - Transfers a result set from a prepared
statement
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::get_result
mysqli_stmt_get_result
(No version information available, might only be in SVN)
mysqli_stmt::get_result -- mysqli_stmt_get_result - Gets a result set from
a prepared statement
Description
Object oriented style
mysqli_result mysqli_stmt::get_result ( void )
Procedural style
mysqli_result mysqli_stmt_get_result ( mysqli_stmt $stmt )
Call to return a result set from a prepared statement query.
Parameters
stmt
Procedural style only: A statement identifier returned by
mysqli_stmt_init().
Return Values
Returns a resultset or FALSE on failure.
Examples
Object oriented style
connect_error)
{
die("$mysqli->connect_errno: $myslqi->connect_error");
}
$query = "SELECT Name, Population, Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1";
$stmt = $mysqli->stmt_init();
if(!$stmt->prepare($query))
{
print "Failed to prepare statement\n";
}
else
{
$stmt->bind_param("s", $continent);
$continent_array = array('Europe','Africa','Asia','North America');
foreach($continent_array as $continent)
{
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM))
{
foreach ($row as $r)
{
print "$r ";
}
print "\n";
}
}
}
$stmt->close();
$mysqli->close();
?>
Procedural style
The above examples will output:
Albania 3401200 Europe
Algeria 31471000 Africa
Afghanistan 22720000 Asia
Anguilla 8000 North America
See Also
* mysqli_prepare() - Prepare an SQL statement for execution
* mysqli_stmt_result_metadata() - Returns result set metadata from a
prepared statement
* mysqli_stmt_fetch() - Fetch results from a prepared statement into the
bound variables
* mysqli_fetch_array() - Fetch a result row as an associative, a numeric
array, or both
* mysqli_stmt_store_result() - Transfers a result set from a prepared
statement
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::get_warnings
mysqli_stmt_get_warnings
(PHP 5 >= 5.1.0)
mysqli_stmt::get_warnings -- mysqli_stmt_get_warnings - Get result of SHOW
WARNINGS
Description
Object oriented style
object mysqli_stmt::get_warnings ( mysqli_stmt $stmt )
Procedural style
object mysqli_stmt_get_warnings ( mysqli_stmt $stmt )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::insert_id
mysqli_stmt_insert_id
(PHP 5)
mysqli_stmt::insert_id -- mysqli_stmt_insert_id - Get the ID generated
from the previous INSERT operation
Description
Object oriented style
int $mysqli_stmt->insert_id;
Procedural style
mixed mysqli_stmt_insert_id ( mysqli_stmt $stmt )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::num_rows
mysqli_stmt_num_rows
(PHP 5)
mysqli_stmt::num_rows -- mysqli_stmt_num_rows - Return the number of rows
in statements result set
Description
Object oriented style
int $mysqli_stmt->num_rows;
Procedural style
int mysqli_stmt_num_rows ( mysqli_stmt $stmt )
Returns the number of rows in the result set. The use of
mysqli_stmt_num_rows() depends on whether or not you used
mysqli_stmt_store_result() to buffer the entire result set in the
statement handle.
If you use mysqli_stmt_store_result(), mysqli_stmt_num_rows() may be
called immediately.
Parameters
stmt
Procedural style only: A statement identifier returned by
mysqli_stmt_init().
Return Values
An integer representing the number of rows in result set.
Examples
Example #1 Object oriented style
prepare($query)) {
/* execute query */
$stmt->execute();
/* store result */
$stmt->store_result();
printf("Number of rows: %d.\n", $stmt->num_rows);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Example #2 Procedural style
The above examples will output:
Number of rows: 20.
See Also
* mysqli_stmt_affected_rows() - Returns the total number of rows
changed, deleted, or inserted by the last executed statement
* mysqli_prepare() - Prepare an SQL statement for execution
* mysqli_stmt_store_result() - Transfers a result set from a prepared
statement
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::param_count
mysqli_stmt_param_count
(PHP 5)
mysqli_stmt::param_count -- mysqli_stmt_param_count - Returns the number
of parameter for the given statement
Description
Object oriented style
int $mysqli_stmt->param_count;
Procedural style
int mysqli_stmt_param_count ( mysqli_stmt $stmt )
Returns the number of parameter markers present in the prepared statement.
Parameters
stmt
Procedural style only: A statement identifier returned by
mysqli_stmt_init().
Return Values
Returns an integer representing the number of parameters.
Examples
Example #1 Object oriented style
prepare("SELECT Name FROM Country WHERE Name=? OR Code=?")) {
$marker = $stmt->param_count;
printf("Statement has %d markers.\n", $marker);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Example #2 Procedural style
The above examples will output:
Statement has 2 markers.
See Also
* mysqli_prepare() - Prepare an SQL statement for execution
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::prepare
mysqli_stmt_prepare
(PHP 5)
mysqli_stmt::prepare -- mysqli_stmt_prepare - Prepare an SQL statement for
execution
Description
Object oriented style
mixed mysqli_stmt::prepare ( string $query )
Procedural style
bool mysqli_stmt_prepare ( mysqli_stmt $stmt , string $query )
Prepares the SQL query pointed to by the null-terminated string query.
The parameter markers must be bound to application variables using
mysqli_stmt_bind_param() and/or mysqli_stmt_bind_result() before executing
the statement or fetching rows.
Note:
In the case where you pass a statement to mysqli_stmt_prepare() that is
longer than max_allowed_packet of the server, the returned error codes
are different depending on whether you are using MySQL Native Driver
(mysqlnd) or MySQL Client Library (libmysql). The behavior is as
follows:
* mysqlnd on Linux returns an error code of 1153. The error message
means "got a packet bigger than max_allowed_packet bytes".
* mysqlnd on Windows returns an error code 2006. This error message
means "server has gone away".
* libmysql on all platforms returns an error code 2006. This error
message means "server has gone away".
Parameters
stmt
Procedural style only: A statement identifier returned by
mysqli_stmt_init().
query
The query, as a string. It must consist of a single SQL statement.
You can include one or more parameter markers in the SQL statement
by embedding question mark (?) characters at the appropriate
positions.
Note:
You should not add a terminating semicolon or \g to the
statement.
Note:
The markers are legal only in certain places in SQL statements.
For example, they are allowed in the VALUES() list of an INSERT
statement (to specify column values for a row), or in a
comparison with a column in a WHERE clause to specify a
comparison value.
However, they are not allowed for identifiers (such as table or
column names), in the select list that names the columns to be
returned by a SELECT statement), or to specify both operands of
a binary operator such as the = equal sign. The latter
restriction is necessary because it would be impossible to
determine the parameter type. In general, parameters are legal
only in Data Manipulation Language (DML) statements, and not in
Data Definition Language (DDL) statements.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Object oriented style
stmt_init();
if ($stmt->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Example #2 Procedural style
The above examples will output:
Amersfoort is in district Utrecht
See Also
* mysqli_stmt_init() - Initializes a statement and returns an object for
use with mysqli_stmt_prepare
* mysqli_stmt_execute() - Executes a prepared Query
* mysqli_stmt_fetch() - Fetch results from a prepared statement into the
bound variables
* mysqli_stmt_bind_param() - Binds variables to a prepared statement as
parameters
* mysqli_stmt_bind_result() - Binds variables to a prepared statement
for result storage
* mysqli_stmt_close() - Closes a prepared statement
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::reset
mysqli_stmt_reset
(PHP 5)
mysqli_stmt::reset -- mysqli_stmt_reset - Resets a prepared statement
Description
Object oriented style
bool mysqli_stmt::reset ( void )
Procedural style
bool mysqli_stmt_reset ( mysqli_stmt $stmt )
Resets a prepared statement on client and server to state after prepare.
It resets the statement on the server, data sent using
mysqli_stmt_send_long_data(), unbuffered result sets and current errors.
It does not clear bindings or stored result sets. Stored result sets will
be cleared when executing the prepared statement (or closing it).
To prepare a statement with another query use function
mysqli_stmt_prepare().
Parameters
stmt
Procedural style only: A statement identifier returned by
mysqli_stmt_init().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* mysqli_prepare() - Prepare an SQL statement for execution
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::result_metadata
mysqli_stmt_result_metadata
(PHP 5)
mysqli_stmt::result_metadata -- mysqli_stmt_result_metadata - Returns
result set metadata from a prepared statement
Description
Object oriented style
mysqli_result mysqli_stmt::result_metadata ( void )
Procedural style
mysqli_result mysqli_stmt_result_metadata ( mysqli_stmt $stmt )
If a statement passed to mysqli_prepare() is one that produces a result
set, mysqli_stmt_result_metadata() returns the result object that can be
used to process the meta information such as total number of fields and
individual field information.
Note:
This result set pointer can be passed as an argument to any of the
field-based functions that process result set metadata, such as:
* mysqli_num_fields()
* mysqli_fetch_field()
* mysqli_fetch_field_direct()
* mysqli_fetch_fields()
* mysqli_field_count()
* mysqli_field_seek()
* mysqli_field_tell()
* mysqli_free_result()
The result set structure should be freed when you are done with it, which
you can do by passing it to mysqli_free_result()
Note:
The result set returned by mysqli_stmt_result_metadata() contains only
metadata. It does not contain any row results. The rows are obtained by
using the statement handle with mysqli_stmt_fetch().
Parameters
stmt
Procedural style only: A statement identifier returned by
mysqli_stmt_init().
Return Values
Returns a result object or FALSE if an error occurred.
Examples
Example #1 Object oriented style
query("DROP TABLE IF EXISTS friends");
$mysqli->query("CREATE TABLE friends (id int, name varchar(20))");
$mysqli->query("INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");
$stmt = $mysqli->prepare("SELECT id, name FROM friends");
$stmt->execute();
/* get resultset for metadata */
$result = $stmt->result_metadata();
/* retrieve field information from metadata result set */
$field = $result->fetch_field();
printf("Fieldname: %s\n", $field->name);
/* close resultset */
$result->close();
/* close connection */
$mysqli->close();
?>
Example #2 Procedural style
name);
/* close resultset */
mysqli_free_result($result);
/* close connection */
mysqli_close($link);
?>
See Also
* mysqli_prepare() - Prepare an SQL statement for execution
* mysqli_free_result() - Frees the memory associated with a result
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::send_long_data
mysqli_stmt_send_long_data
(PHP 5)
mysqli_stmt::send_long_data -- mysqli_stmt_send_long_data - Send data in
blocks
Description
Object oriented style
bool mysqli_stmt::send_long_data ( int $param_nr , string $data )
Procedural style
bool mysqli_stmt_send_long_data ( mysqli_stmt $stmt , int $param_nr ,
string $data )
Allows to send parameter data to the server in pieces (or chunks), e.g. if
the size of a blob exceeds the size of max_allowed_packet. This function
can be called multiple times to send the parts of a character or binary
data value for a column, which must be one of the TEXT or BLOB datatypes.
Parameters
stmt
Procedural style only: A statement identifier returned by
mysqli_stmt_init().
param_nr
Indicates which parameter to associate the data with. Parameters
are numbered beginning with 0.
data
A string containing data to be sent.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Object oriented style
prepare("INSERT INTO messages (message) VALUES (?)");
$null = NULL;
$stmt->bind_param("b", $null);
$fp = fopen("messages.txt", "r");
while (!feof($fp)) {
$stmt->send_long_data(0, fread($fp, 8192));
}
fclose($fp);
$stmt->execute();
?>
See Also
* mysqli_prepare() - Prepare an SQL statement for execution
* mysqli_stmt_bind_param() - Binds variables to a prepared statement as
parameters
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::sqlstate
mysqli_stmt_sqlstate
(PHP 5)
mysqli_stmt::sqlstate -- mysqli_stmt_sqlstate - Returns SQLSTATE error
from previous statement operation
Description
Object oriented style
string $mysqli_stmt->sqlstate;
Procedural style
string mysqli_stmt_sqlstate ( mysqli_stmt $stmt )
Returns a string containing the SQLSTATE error code for the most recently
invoked prepared statement function that can succeed or fail. The error
code consists of five characters. '00000' means no error. The values are
specified by ANSI SQL and ODBC. For a list of possible values, see
>> http://dev.mysql.com/doc/mysql/en/error-handling.html.
Parameters
stmt
Procedural style only: A statement identifier returned by
mysqli_stmt_init().
Return Values
Returns a string containing the SQLSTATE error code for the last error.
The error code consists of five characters. '00000' means no error.
Notes
Note:
Note that not all MySQL errors are yet mapped to SQLSTATE's. The value
HY000 (general error) is used for unmapped errors.
Examples
Object oriented style
query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");
$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {
/* drop table */
$mysqli->query("DROP TABLE myCountry");
/* execute query */
$stmt->execute();
printf("Error: %s.\n", $stmt->sqlstate);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
Error: 42S02.
See Also
* mysqli_stmt_errno() - Returns the error code for the most recent
statement call
* mysqli_stmt_error() - Returns a string description for last statement
error
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_stmt::store_result
mysqli_stmt_store_result
(PHP 5)
mysqli_stmt::store_result -- mysqli_stmt_store_result - Transfers a result
set from a prepared statement
Description
Object oriented style
bool mysqli_stmt::store_result ( void )
Procedural style
bool mysqli_stmt_store_result ( mysqli_stmt $stmt )
You must call mysqli_stmt_store_result() for every query that successfully
produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN), and only if you
want to buffer the complete result set by the client, so that the
subsequent mysqli_stmt_fetch() call returns buffered data.
Note:
It is unnecessary to call mysqli_stmt_store_result() for other queries,
but if you do, it will not harm or cause any notable performance in all
cases. You can detect whether the query produced a result set by
checking if mysqli_stmt_result_metadata() returns NULL.
Parameters
stmt
Procedural style only: A statement identifier returned by
mysqli_stmt_init().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Object oriented style
prepare($query)) {
/* execute query */
$stmt->execute();
/* store result */
$stmt->store_result();
printf("Number of rows: %d.\n", $stmt->num_rows);
/* free result */
$stmt->free_result();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
Number of rows: 20.
See Also
* mysqli_prepare() - Prepare an SQL statement for execution
* mysqli_stmt_result_metadata() - Returns result set metadata from a
prepared statement
* mysqli_stmt_fetch() - Fetch results from a prepared statement into the
bound variables
----------------------------------------------------------------------
Table of Contents
* mysqli_stmt::affected_rows - Returns the total number of rows changed,
deleted, or inserted by the last executed statement
* mysqli_stmt::attr_get - Used to get the current value of a statement
attribute
* mysqli_stmt::attr_set - Used to modify the behavior of a prepared
statement
* mysqli_stmt::bind_param - Binds variables to a prepared statement as
parameters
* mysqli_stmt::bind_result - Binds variables to a prepared statement for
result storage
* mysqli_stmt::close - Closes a prepared statement
* mysqli_stmt::data_seek - Seeks to an arbitrary row in statement result
set
* mysqli_stmt::errno - Returns the error code for the most recent
statement call
* mysqli_stmt::error - Returns a string description for last statement
error
* mysqli_stmt::execute - Executes a prepared Query
* mysqli_stmt::fetch - Fetch results from a prepared statement into the
bound variables
* mysqli_stmt::field_count - Returns the number of field in the given
statement
* mysqli_stmt::free_result - Frees stored result memory for the given
statement handle
* mysqli_stmt::get_result - Gets a result set from a prepared statement
* mysqli_stmt::get_warnings - Get result of SHOW WARNINGS
* mysqli_stmt::insert_id - Get the ID generated from the previous INSERT
operation
* mysqli_stmt::num_rows - Return the number of rows in statements result
set
* mysqli_stmt::param_count - Returns the number of parameter for the
given statement
* mysqli_stmt::prepare - Prepare an SQL statement for execution
* mysqli_stmt::reset - Resets a prepared statement
* mysqli_stmt::result_metadata - Returns result set metadata from a
prepared statement
* mysqli_stmt::send_long_data - Send data in blocks
* mysqli_stmt::sqlstate - Returns SQLSTATE error from previous statement
operation
* mysqli_stmt::store_result - Transfers a result set from a prepared
statement
----------------------------------------------------------------------
----------------------------------------------------------------------
The MySQLi_Result class
Introduction
Represents the result set obtained from a query against the database.
Class synopsis
MySQLi_Result {
/* Properties */
int $MySQLi_Result->current_field ;
int $field_count;
array $lengths;
int $num_rows;
/* Methods */
int mysqli_field_tell ( mysqli_result $result )
bool mysqli_result::data_seek ( int $offset )
mixed mysqli_result::fetch_all ([ int $resulttype = MYSQLI_NUM ] )
mixed mysqli_result::fetch_array ([ int $resulttype = MYSQLI_BOTH ] )
array mysqli_result::fetch_assoc ( void )
object mysqli_result::fetch_field_direct ( int $fieldnr )
object mysqli_result::fetch_field ( void )
array mysqli_result::fetch_fields ( void )
object mysqli_result::fetch_object ([ string $class_name [, array $params
]] )
mixed mysqli_result::fetch_row ( void )
int mysqli_num_fields ( mysqli_result $result )
bool mysqli_result::field_seek ( int $fieldnr )
void mysqli_result::free ( void )
array mysqli_fetch_lengths ( mysqli_result $result )
int mysqli_num_rows ( mysqli_result $result )
}
----------------------------------------------------------------------
mysqli_result::current_field
mysqli_field_tell
(PHP 5)
mysqli_result::current_field -- mysqli_field_tell - Get current field
offset of a result pointer
Description
Object oriented style
int $mysqli_result->current_field ;
Procedural style
int mysqli_field_tell ( mysqli_result $result )
Returns the position of the field cursor used for the last
mysqli_fetch_field() call. This value can be used as an argument to
mysqli_field_seek().
Parameters
result
Procedural style only: A result set identifier returned by
mysqli_query(), mysqli_store_result() or mysqli_use_result().
Return Values
Returns current offset of field cursor.
Examples
Object oriented style
query($query)) {
/* Get field information for all columns */
while ($finfo = $result->fetch_field()) {
/* get fieldpointer offset */
$currentfield = $result->current_field;
printf("Column %d:\n", $currentfield);
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
$result->close();
}
/* close connection */
$mysqli->close();
?>
Procedural style
name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>
The above examples will output:
Column 1:
Name: Name
Table: Country
max. Len: 11
Flags: 1
Type: 254
Column 2:
Name: SurfaceArea
Table: Country
max. Len: 10
Flags: 32769
Type: 4
See Also
* mysqli_fetch_field() - Returns the next field in the result set
* mysqli_field_seek() - Set result pointer to a specified field offset
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_result::data_seek
mysqli_data_seek
(PHP 5)
mysqli_result::data_seek -- mysqli_data_seek - Adjusts the result pointer
to an arbitary row in the result
Description
Object oriented style
bool mysqli_result::data_seek ( int $offset )
Procedural style
bool mysqli_data_seek ( mysqli_result $result , int $offset )
The mysqli_data_seek() function seeks to an arbitrary result pointer
specified by the offset in the result set.
Parameters
result
Procedural style only: A result set identifier returned by
mysqli_query(), mysqli_store_result() or mysqli_use_result().
offset
The field offset. Must be between zero and the total number of
rows minus one (0..mysqli_num_rows() - 1).
Return Values
Returns TRUE on success or FALSE on failure.
Notes
Note:
This function can only be used with buffered results attained from the
use of the mysqli_store_result() or mysqli_query() functions.
Examples
Object oriented style
query( $query)) {
/* seek to row no. 400 */
$result->data_seek(399);
/* fetch row */
$row = $result->fetch_row();
printf ("City: %s Countrycode: %s\n", $row[0], $row[1]);
/* free result set*/
$result->close();
}
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
City: Benin City Countrycode: NGA
See Also
* mysqli_store_result() - Transfers a result set from the last query
* mysqli_fetch_row() - Get a result row as an enumerated array
* mysqli_fetch_array() - Fetch a result row as an associative, a numeric
array, or both
* mysqli_fetch_assoc() - Fetch a result row as an associative array
* mysqli_fetch_object() - Returns the current row of a result set as an
object
* mysqli_query() - Performs a query on the database
* mysqli_num_rows() - Gets the number of rows in a result
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_result::fetch_all
mysqli_fetch_all
(PHP 5 >= 5.3.0)
mysqli_result::fetch_all -- mysqli_fetch_all - Fetches all result rows as
an associative array, a numeric array, or both
Description
Object oriented style
mixed mysqli_result::fetch_all ([ int $resulttype = MYSQLI_NUM ] )
Procedural style
mixed mysqli_fetch_all ( mysqli_result $result [, int $resulttype =
MYSQLI_NUM ] )
mysqli_fetch_all() fetches all result rows and returns the result set as
an associative array, a numeric array, or both.
Parameters
result
Procedural style only: A result set identifier returned by
mysqli_query(), mysqli_store_result() or mysqli_use_result().
resulttype
This optional parameter is a constant indicating what type of
array should be produced from the current row data. The possible
values for this parameter are the constants MYSQLI_ASSOC,
MYSQLI_NUM, or MYSQLI_BOTH.
Return Values
Returns an array of associative or numeric arrays holding result rows.
MySQL Native Driver Only
Available only with mysqlnd.
As mysqli_fetch_all() returns all the rows as an array in a single step,
it may consume more memory than some similar functions such as
mysqli_fetch_array(), which only returns one row at a time from the result
set. Further, if you need to iterate over the result set, you will need a
looping construct that will further impact performance. For these reasons
mysqli_fetch_all() should only be used in those situations where the
fetched result set will be sent to another layer for processing.
See Also
* mysqli_fetch_array() - Fetch a result row as an associative, a numeric
array, or both
* mysqli_query() - Performs a query on the database
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_result::fetch_array
mysqli_fetch_array
(PHP 5)
mysqli_result::fetch_array -- mysqli_fetch_array - Fetch a result row as
an associative, a numeric array, or both
Description
Object oriented style
mixed mysqli_result::fetch_array ([ int $resulttype = MYSQLI_BOTH ] )
Procedural style
mixed mysqli_fetch_array ( mysqli_result $result [, int $resulttype =
MYSQLI_BOTH ] )
Returns an array that corresponds to the fetched row or NULL if there are
no more rows for the resultset represented by the result parameter.
mysqli_fetch_array() is an extended version of the mysqli_fetch_row()
function. In addition to storing the data in the numeric indices of the
result array, the mysqli_fetch_array() function can also store the data in
associative indices, using the field names of the result set as keys.
Note: Field names returned by this function are case-sensitive.
Note: This function sets NULL fields to the PHP NULL value.
If two or more columns of the result have the same field names, the last
column will take precedence and overwrite the earlier data. In order to
access multiple columns with the same name, the numerically indexed
version of the row must be used.
Parameters
result
Procedural style only: A result set identifier returned by
mysqli_query(), mysqli_store_result() or mysqli_use_result().
resulttype
This optional parameter is a constant indicating what type of
array should be produced from the current row data. The possible
values for this parameter are the constants MYSQLI_ASSOC,
MYSQLI_NUM, or MYSQLI_BOTH.
By using the MYSQLI_ASSOC constant this function will behave
identically to the mysqli_fetch_assoc(), while MYSQLI_NUM will
behave identically to the mysqli_fetch_row() function. The final
option MYSQLI_BOTH will create a single array with the attributes
of both.
Return Values
Returns an array of strings that corresponds to the fetched row or NULL if
there are no more rows in resultset.
Examples
Object oriented style
query($query);
/* numeric array */
$row = $result->fetch_array(MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);
/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
/* associative and numeric array */
$row = $result->fetch_array(MYSQLI_BOTH);
printf ("%s (%s)\n", $row[0], $row["CountryCode"]);
/* free result set */
$result->close();
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
Kabul (AFG)
Qandahar (AFG)
Herat (AFG)
See Also
* mysqli_fetch_assoc() - Fetch a result row as an associative array
* mysqli_fetch_row() - Get a result row as an enumerated array
* mysqli_fetch_object() - Returns the current row of a result set as an
object
* mysqli_query() - Performs a query on the database
* mysqli_data_seek() - Adjusts the result pointer to an arbitary row in
the result
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_result::fetch_assoc
mysqli_fetch_assoc
(PHP 5)
mysqli_result::fetch_assoc -- mysqli_fetch_assoc - Fetch a result row as
an associative array
Description
Object oriented style
array mysqli_result::fetch_assoc ( void )
Procedural style
array mysqli_fetch_assoc ( mysqli_result $result )
Returns an associative array that corresponds to the fetched row or NULL
if there are no more rows.
Note: Field names returned by this function are case-sensitive.
Note: This function sets NULL fields to the PHP NULL value.
Parameters
result
Procedural style only: A result set identifier returned by
mysqli_query(), mysqli_store_result() or mysqli_use_result().
Return Values
Returns an associative array of strings representing the fetched row in
the result set, where each key in the array represents the name of one of
the result set's columns or NULL if there are no more rows in resultset.
If two or more columns of the result have the same field names, the last
column will take precedence. To access the other column(s) of the same
name, you either need to access the result with numeric indices by using
mysqli_fetch_row() or add alias names.
Examples
Object oriented style
query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)
See Also
* mysqli_fetch_array() - Fetch a result row as an associative, a numeric
array, or both
* mysqli_fetch_row() - Get a result row as an enumerated array
* mysqli_fetch_object() - Returns the current row of a result set as an
object
* mysqli_query() - Performs a query on the database
* mysqli_data_seek() - Adjusts the result pointer to an arbitary row in
the result
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_result::fetch_field_direct
mysqli_fetch_field_direct
(PHP 5)
mysqli_result::fetch_field_direct -- mysqli_fetch_field_direct - Fetch
meta-data for a single field
Description
Object oriented style
object mysqli_result::fetch_field_direct ( int $fieldnr )
Procedural style
object mysqli_fetch_field_direct ( mysqli_result $result , int $fieldnr )
Returns an object which contains field definition information from the
specified result set.
Parameters
result
Procedural style only: A result set identifier returned by
mysqli_query(), mysqli_store_result() or mysqli_use_result().
fieldnr
The field number. This value must be in the range from 0 to number
of fields - 1.
Return Values
Returns an object which contains field definition information or FALSE if
no field information for specified fieldnr is available.
Object attributes
Attribute Description
name The name of the column
orgname Original column name if an alias was specified
table The name of the table this field belongs to (if not calculated)
orgtable Original table name if an alias was specified
def The default value for this field, represented as a string
max_length The maximum width of the field for the result set.
length The width of the field, as specified in the table definition.
charsetnr The character set number for the field.
flags An integer representing the bit-flags for the field.
type The data type used for this field
decimals The number of decimals used (for integer fields)
Examples
Object oriented style
query($query)) {
/* Get field information for column 'SurfaceArea' */
$finfo = $result->fetch_field_direct(1);
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n", $finfo->type);
$result->close();
}
/* close connection */
$mysqli->close();
?>
Procedural style
name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n", $finfo->type);
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>
The above examples will output:
Name: SurfaceArea
Table: Country
max. Len: 10
Flags: 32769
Type: 4
See Also
* mysqli_num_fields() - Get the number of fields in a result
* mysqli_fetch_field() - Returns the next field in the result set
* mysqli_fetch_fields() - Returns an array of objects representing the
fields in a result set
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_result::fetch_field
mysqli_fetch_field
(PHP 5)
mysqli_result::fetch_field -- mysqli_fetch_field - Returns the next field
in the result set
Description
Object oriented style
object mysqli_result::fetch_field ( void )
Procedural style
object mysqli_fetch_field ( mysqli_result $result )
Returns the definition of one column of a result set as an object. Call
this function repeatedly to retrieve information about all columns in the
result set.
Parameters
result
Procedural style only: A result set identifier returned by
mysqli_query(), mysqli_store_result() or mysqli_use_result().
Return Values
Returns an object which contains field definition information or FALSE if
no field information is available.
Object properties
Property Description
name The name of the column
orgname Original column name if an alias was specified
table The name of the table this field belongs to (if not calculated)
orgtable Original table name if an alias was specified
def Reserved for default value, currently always ""
db Database (since PHP 5.3.6)
catalog The catalog name, always "def" (since PHP 5.3.6)
max_length The maximum width of the field for the result set.
length The width of the field, as specified in the table definition.
charsetnr The character set number for the field.
flags An integer representing the bit-flags for the field.
type The data type used for this field
decimals The number of decimals used (for integer fields)
Examples
Object oriented style
query($query)) {
/* Get field information for all columns */
while ($finfo = $result->fetch_field()) {
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
$result->close();
}
/* close connection */
$mysqli->close();
?>
Procedural style
name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>
The above examples will output:
Name: Name
Table: Country
max. Len: 11
Flags: 1
Type: 254
Name: SurfaceArea
Table: Country
max. Len: 10
Flags: 32769
Type: 4
See Also
* mysqli_num_fields() - Get the number of fields in a result
* mysqli_fetch_field_direct() - Fetch meta-data for a single field
* mysqli_fetch_fields() - Returns an array of objects representing the
fields in a result set
* mysqli_field_seek() - Set result pointer to a specified field offset
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_result::fetch_fields
mysqli_fetch_fields
(PHP 5)
mysqli_result::fetch_fields -- mysqli_fetch_fields - Returns an array of
objects representing the fields in a result set
Description
Object oriented style
array mysqli_result::fetch_fields ( void )
Procedural style
array mysqli_fetch_fields ( mysqli_result $result )
This function serves an identical purpose to the mysqli_fetch_field()
function with the single difference that, instead of returning one object
at a time for each field, the columns are returned as an array of objects.
Parameters
result
Procedural style only: A result set identifier returned by
mysqli_query(), mysqli_store_result() or mysqli_use_result().
Return Values
Returns an array of objects which contains field definition information or
FALSE if no field information is available.
Object properties
Property Description
name The name of the column
orgname Original column name if an alias was specified
table The name of the table this field belongs to (if not calculated)
orgtable Original table name if an alias was specified
max_length The maximum width of the field for the result set.
length The width of the field, as specified in the table definition.
charsetnr The character set number for the field.
flags An integer representing the bit-flags for the field.
type The data type used for this field
decimals The number of decimals used (for integer fields)
Examples
Object oriented style
query($query)) {
/* Get field information for all columns */
$finfo = $result->fetch_fields();
foreach ($finfo as $val) {
printf("Name: %s\n", $val->name);
printf("Table: %s\n", $val->table);
printf("max. Len: %d\n", $val->max_length);
printf("Flags: %d\n", $val->flags);
printf("Type: %d\n\n", $val->type);
}
$result->close();
}
/* close connection */
$mysqli->close();
?>
Procedural style
name);
printf("Table: %s\n", $val->table);
printf("max. Len: %d\n", $val->max_length);
printf("Flags: %d\n", $val->flags);
printf("Type: %d\n\n", $val->type);
}
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>
The above examples will output:
Name: Name
Table: Country
max. Len: 11
Flags: 1
Type: 254
Name: SurfaceArea
Table: Country
max. Len: 10
Flags: 32769
Type: 4
See Also
* mysqli_num_fields() - Get the number of fields in a result
* mysqli_fetch_field_direct() - Fetch meta-data for a single field
* mysqli_fetch_field() - Returns the next field in the result set
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_result::fetch_object
mysqli_fetch_object
(PHP 5)
mysqli_result::fetch_object -- mysqli_fetch_object - Returns the current
row of a result set as an object
Description
Object oriented style
object mysqli_result::fetch_object ([ string $class_name [, array $params
]] )
Procedural style
object mysqli_fetch_object ( mysqli_result $result [, string $class_name
[, array $params ]] )
The mysqli_fetch_object() will return the current row result set as an
object where the attributes of the object represent the names of the
fields found within the result set.
Note that mysqli_fetch_object() sets the properties of the object before
calling the object constructor.
Parameters
result
Procedural style only: A result set identifier returned by
mysqli_query(), mysqli_store_result() or mysqli_use_result().
class_name
The name of the class to instantiate, set the properties of and
return. If not specified, a stdClass object is returned.
params
An optional array of parameters to pass to the constructor for
class_name objects.
Return Values
Returns an object with string properties that corresponds to the fetched
row or NULL if there are no more rows in resultset.
Note: Field names returned by this function are case-sensitive.
Note: This function sets NULL fields to the PHP NULL value.
Changelog
Version Description
5.0.0 Added the ability to return as a different object.
Examples
Object oriented style
query($query)) {
/* fetch object array */
while ($obj = $result->fetch_object()) {
printf ("%s (%s)\n", $obj->Name, $obj->CountryCode);
}
/* free result set */
$result->close();
}
/* close connection */
$mysqli->close();
?>
Procedural style
Name, $obj->CountryCode);
}
/* free result set */
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>
The above examples will output:
Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)
See Also
* mysqli_fetch_array() - Fetch a result row as an associative, a numeric
array, or both
* mysqli_fetch_assoc() - Fetch a result row as an associative array
* mysqli_fetch_row() - Get a result row as an enumerated array
* mysqli_query() - Performs a query on the database
* mysqli_data_seek() - Adjusts the result pointer to an arbitary row in
the result
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_result::fetch_row
mysqli_fetch_row
(PHP 5)
mysqli_result::fetch_row -- mysqli_fetch_row - Get a result row as an
enumerated array
Description
Object oriented style
mixed mysqli_result::fetch_row ( void )
Procedural style
mixed mysqli_fetch_row ( mysqli_result $result )
Fetches one row of data from the result set and returns it as an
enumerated array, where each column is stored in an array offset starting
from 0 (zero). Each subsequent call to this function will return the next
row within the result set, or NULL if there are no more rows.
Parameters
result
Procedural style only: A result set identifier returned by
mysqli_query(), mysqli_store_result() or mysqli_use_result().
Return Values
mysqli_fetch_row() returns an array of strings that corresponds to the
fetched row or NULL if there are no more rows in result set.
Note: This function sets NULL fields to the PHP NULL value.
Examples
Object oriented style
query($query)) {
/* fetch object array */
while ($row = $result->fetch_row()) {
printf ("%s (%s)\n", $row[0], $row[1]);
}
/* free result set */
$result->close();
}
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)
See Also
* mysqli_fetch_array() - Fetch a result row as an associative, a numeric
array, or both
* mysqli_fetch_assoc() - Fetch a result row as an associative array
* mysqli_fetch_object() - Returns the current row of a result set as an
object
* mysqli_query() - Performs a query on the database
* mysqli_data_seek() - Adjusts the result pointer to an arbitary row in
the result
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_result::field_count
mysqli_num_fields
(PHP 5)
mysqli_result::field_count -- mysqli_num_fields - Get the number of fields
in a result
Description
Object oriented style
int $mysqli_result->field_count;
Procedural style
int mysqli_num_fields ( mysqli_result $result )
Returns the number of fields from specified result set.
Parameters
result
Procedural style only: A result set identifier returned by
mysqli_query(), mysqli_store_result() or mysqli_use_result().
Return Values
The number of fields from a result set.
Examples
Object oriented style
query("SELECT * FROM City ORDER BY ID LIMIT 1")) {
/* determine number of fields in result set */
$field_cnt = $result->field_count;
printf("Result set has %d fields.\n", $field_cnt);
/* close result set */
$result->close();
}
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
Result set has 5 fields.
See Also
* mysqli_fetch_field() - Returns the next field in the result set
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_result::field_seek
mysqli_field_seek
(PHP 5)
mysqli_result::field_seek -- mysqli_field_seek - Set result pointer to a
specified field offset
Description
Object oriented style
bool mysqli_result::field_seek ( int $fieldnr )
Procedural style
bool mysqli_field_seek ( mysqli_result $result , int $fieldnr )
Sets the field cursor to the given offset. The next call to
mysqli_fetch_field() will retrieve the field definition of the column
associated with that offset.
Note:
To seek to the beginning of a row, pass an offset value of zero.
Parameters
result
Procedural style only: A result set identifier returned by
mysqli_query(), mysqli_store_result() or mysqli_use_result().
fieldnr
The field number. This value must be in the range from 0 to number
of fields - 1.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Object oriented style
query($query)) {
/* Get field information for 2nd column */
$result->field_seek(1);
$finfo = $result->fetch_field();
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
$result->close();
}
/* close connection */
$mysqli->close();
?>
Procedural style
name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>
The above examples will output:
Name: SurfaceArea
Table: Country
max. Len: 10
Flags: 32769
Type: 4
See Also
* mysqli_fetch_field() - Returns the next field in the result set
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_result::free
mysqli_free_result
(PHP 5)
mysqli_result::free -- mysqli_free_result - Frees the memory associated
with a result
Description
Object oriented style
void mysqli_result::free ( void )
void mysqli_result::close ( void )
void mysqli_result::free_result ( void )
Procedural style
void mysqli_free_result ( mysqli_result $result )
Frees the memory associated with the result.
Note:
You should always free your result with mysqli_free_result(), when your
result object is not needed anymore.
Parameters
result
Procedural style only: A result set identifier returned by
mysqli_query(), mysqli_store_result() or mysqli_use_result().
Return Values
No value is returned.
See Also
* mysqli_query() - Performs a query on the database
* mysqli_stmt_store_result() - Transfers a result set from a prepared
statement
* mysqli_store_result() - Transfers a result set from the last query
* mysqli_use_result() - Initiate a result set retrieval
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_result::lengths
mysqli_fetch_lengths
(PHP 5)
mysqli_result::lengths -- mysqli_fetch_lengths - Returns the lengths of
the columns of the current row in the result set
Description
Object oriented style
array $mysqli_result->lengths;
Procedural style
array mysqli_fetch_lengths ( mysqli_result $result )
The mysqli_fetch_lengths() function returns an array containing the
lengths of every column of the current row within the result set.
Parameters
result
Procedural style only: A result set identifier returned by
mysqli_query(), mysqli_store_result() or mysqli_use_result().
Return Values
An array of integers representing the size of each column (not including
any terminating null characters). FALSE if an error occurred.
mysqli_fetch_lengths() is valid only for the current row of the result
set. It returns FALSE if you call it before calling
mysqli_fetch_row/array/object or after retrieving all rows in the result.
Examples
Object oriented style
query($query)) {
$row = $result->fetch_row();
/* display column lengths */
foreach ($result->lengths as $i => $val) {
printf("Field %2d has Length %2d\n", $i+1, $val);
}
$result->close();
}
/* close connection */
$mysqli->close();
?>
Procedural style
$val) {
printf("Field %2d has Length %2d\n", $i+1, $val);
}
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>
The above examples will output:
Field 1 has Length 3
Field 2 has Length 5
Field 3 has Length 13
Field 4 has Length 9
Field 5 has Length 6
Field 6 has Length 1
Field 7 has Length 6
Field 8 has Length 4
Field 9 has Length 6
Field 10 has Length 6
Field 11 has Length 5
Field 12 has Length 44
Field 13 has Length 7
Field 14 has Length 3
Field 15 has Length 2
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_result::num_rows
mysqli_num_rows
(PHP 5)
mysqli_result::num_rows -- mysqli_num_rows - Gets the number of rows in a
result
Description
Object oriented style
int $mysqli_result->num_rows;
Procedural style
int mysqli_num_rows ( mysqli_result $result )
Returns the number of rows in the result set.
The use of mysqli_num_rows() depends on whether you use buffered or
unbuffered result sets. In case you use unbuffered resultsets
mysqli_num_rows() will not return the correct number of rows until all the
rows in the result have been retrieved.
Parameters
result
Procedural style only: A result set identifier returned by
mysqli_query(), mysqli_store_result() or mysqli_use_result().
Return Values
Returns number of rows in the result set.
Note:
If the number of rows is greater than maximal int value, the number will
be returned as a string.
Examples
Object oriented style
query("SELECT Code, Name FROM Country ORDER BY Name")) {
/* determine number of rows result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
/* close result set */
$result->close();
}
/* close connection */
$mysqli->close();
?>
Procedural style
The above examples will output:
Result set has 239 rows.
See Also
* mysqli_affected_rows() - Gets the number of affected rows in a
previous MySQL operation
* mysqli_store_result() - Transfers a result set from the last query
* mysqli_use_result() - Initiate a result set retrieval
* mysqli_query() - Performs a query on the database
----------------------------------------------------------------------
Table of Contents
* mysqli_result::current_field - Get current field offset of a result
pointer
* mysqli_result::data_seek - Adjusts the result pointer to an arbitary
row in the result
* mysqli_result::fetch_all - Fetches all result rows as an associative
array, a numeric array, or both
* mysqli_result::fetch_array - Fetch a result row as an associative, a
numeric array, or both
* mysqli_result::fetch_assoc - Fetch a result row as an associative
array
* mysqli_result::fetch_field_direct - Fetch meta-data for a single field
* mysqli_result::fetch_field - Returns the next field in the result set
* mysqli_result::fetch_fields - Returns an array of objects representing
the fields in a result set
* mysqli_result::fetch_object - Returns the current row of a result set
as an object
* mysqli_result::fetch_row - Get a result row as an enumerated array
* mysqli_result::field_count - Get the number of fields in a result
* mysqli_result::field_seek - Set result pointer to a specified field
offset
* mysqli_result::free - Frees the memory associated with a result
* mysqli_result::lengths - Returns the lengths of the columns of the
current row in the result set
* mysqli_result::num_rows - Gets the number of rows in a result
----------------------------------------------------------------------
----------------------------------------------------------------------
The MySQLi_Driver class
Introduction
MySQLi Driver.
Class synopsis
MySQLi_Driver {
/* Properties */
public readonly string $MySQLi_Driver->client_info ;
public readonly string $client_version ;
public readonly string $driver_version ;
public readonly string $embedded ;
public bool $reconnect ;
public int $report_mode ;
/* Methods */
void mysqli_driver::embedded_server_end ( void )
bool mysqli_driver::embedded_server_start ( bool $start , array $arguments
, array $groups )
}
Properties
client_info
The Client API header version
client_version
The Client version
driver_version
The MySQLi Driver version
embedded
Whether MySQLi Embedded support is enabled
reconnect
Allow or prevent reconnect (see the mysqli.reconnect INI
directive)
report_mode
Set to MYSQLI_REPORT_OFF, MYSQLI_REPORT_ALL or any combination of
MYSQLI_REPORT_STRICT (throw Exceptions for errors),
MYSQLI_REPORT_ERROR (report errors) and MYSQLI_REPORT_INDEX
(errors regarding indexes). See also mysqli_report().
----------------------------------------------------------------------
mysqli_driver::embedded_server_end
mysqli_embedded_server_end
(PHP 5)
mysqli_driver::embedded_server_end -- mysqli_embedded_server_end - Stop
embedded server
Description
Object oriented style
void mysqli_driver::embedded_server_end ( void )
Procedural style
void mysqli_embedded_server_end ( void )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_driver::embedded_server_start
mysqli_embedded_server_start
(PHP 5)
mysqli_driver::embedded_server_start -- mysqli_embedded_server_start -
Initialize and start embedded server
Description
Object oriented style
bool mysqli_driver::embedded_server_start ( bool $start , array $arguments
, array $groups )
Procedural style
bool mysqli_embedded_server_start ( bool $start , array $arguments , array
$groups )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
Table of Contents
* mysqli_driver::embedded_server_end - Stop embedded server
* mysqli_driver::embedded_server_start - Initialize and start embedded
server
----------------------------------------------------------------------
----------------------------------------------------------------------
The MySQLi_Warning class
Introduction
Represents a MySQL warning.
Class synopsis
mysqli_warning {
/* Properties */
public $mysqli_warning->message ;
public $sqlstate ;
public $errno ;
/* Methods */
mysqli_warning::__construct ( void )
public void mysqli_warning::next ( void )
}
Properties
message
Message string
sqlstate
SQL state
errno
Error number
----------------------------------------------------------------------
mysqli_warning::__construct
(No version information available, might only be in SVN)
mysqli_warning::__construct - The __construct purpose
Description
mysqli_warning::__construct ( void )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
This function has no parameters.
Return Values
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_warning::next
(No version information available, might only be in SVN)
mysqli_warning::next - The next purpose
Description
public void mysqli_warning::next ( void )
Warning
This function is currently not documented; only its argument list is
available.
Parameters
This function has no parameters.
Return Values
----------------------------------------------------------------------
Table of Contents
* mysqli_warning::__construct - The __construct purpose
* mysqli_warning::next - The next purpose
----------------------------------------------------------------------
----------------------------------------------------------------------
Aliases and deprecated Mysqli Functions
----------------------------------------------------------------------
mysqli_bind_param
(PHP 5)
mysqli_bind_param - Alias for mysqli_stmt_bind_param()
Description
This function is an alias of mysqli_stmt_bind_param().
Notes
Note:
mysqli_bind_param() is deprecated and will be removed.
See Also
* mysqli_stmt_bind_param() - Binds variables to a prepared statement as
parameters
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_bind_result
(PHP 5)
mysqli_bind_result - Alias for mysqli_stmt_bind_result()
Description
This function is an alias of mysqli_stmt_bind_result().
Notes
Note:
mysqli_bind_result() is deprecated and will be removed.
See Also
* mysqli_stmt_bind_result() - Binds variables to a prepared statement
for result storage
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_client_encoding
(PHP 5)
mysqli_client_encoding - Alias of mysqli_character_set_name()
Description
This function is an alias of mysqli_character_set_name().
See Also
* mysqli_real_escape_string() - Escapes special characters in a string
for use in an SQL statement, taking into account the current charset
of the connection
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_connect
(PHP 5)
mysqli_connect - Alias of mysqli::__construct()
Description
This function is an alias of: mysqli::__construct()
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_disable_reads_from_master
mysqli::disable_reads_from_master
(PHP 5)
mysqli_disable_reads_from_master -- mysqli::disable_reads_from_master -
Disable reads from master
Description
Object oriented style
void mysqli::disable_reads_from_master ( void )
Procedural style
bool mysqli_disable_reads_from_master ( mysqli $link )
Warning
This function is currently not documented; only its argument list is
available.
Warning
This function has been DEPRECATED and REMOVED as of PHP 5.3.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_disable_rpl_parse
(PHP 5)
mysqli_disable_rpl_parse - Disable RPL parse
Description
bool mysqli_disable_rpl_parse ( mysqli $link )
Warning
This function is currently not documented; only its argument list is
available.
Warning
This function has been DEPRECATED and REMOVED as of PHP 5.3.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_enable_reads_from_master
(PHP 5)
mysqli_enable_reads_from_master - Enable reads from master
Description
bool mysqli_enable_reads_from_master ( mysqli $link )
Warning
This function is currently not documented; only its argument list is
available.
Warning
This function has been DEPRECATED and REMOVED as of PHP 5.3.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_enable_rpl_parse
(PHP 5)
mysqli_enable_rpl_parse - Enable RPL parse
Description
bool mysqli_enable_rpl_parse ( mysqli $link )
Warning
This function is currently not documented; only its argument list is
available.
Warning
This function has been DEPRECATED and REMOVED as of PHP 5.3.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_escape_string
(PHP 5)
mysqli_escape_string - Alias of mysqli_real_escape_string()
Description
This function is an alias of: mysqli_real_escape_string().
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_execute
(PHP 5)
mysqli_execute - Alias for mysqli_stmt_execute()
Description
This function is an alias of mysqli_stmt_execute().
Notes
Note:
mysqli_execute() is deprecated and will be removed.
See Also
* mysqli_stmt_execute() - Executes a prepared Query
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_fetch
(PHP 5)
mysqli_fetch - Alias for mysqli_stmt_fetch()
Description
This function is an alias of mysqli_stmt_fetch().
Notes
Note:
mysqli_fetch() is deprecated and will be removed.
See Also
* mysqli_stmt_fetch() - Fetch results from a prepared statement into the
bound variables
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_get_cache_stats
(PHP 5 >= 5.3.0)
mysqli_get_cache_stats - Returns client Zval cache statistics
Description
array mysqli_get_cache_stats ( void )
Warning
This function is currently not documented; only its argument list is
available.
Returns client Zval cache statistics. Available only with mysqlnd.
Parameters
Return Values
Returns an array with client Zval cache stats if success, FALSE otherwise.
Examples
Example #1 A mysqli_get_cache_stats() example
The above example will output something similar to:
Array
(
[bytes_sent] => 43
[bytes_received] => 80
[packets_sent] => 1
[packets_received] => 2
[protocol_overhead_in] => 8
[protocol_overhead_out] => 4
[bytes_received_ok_packet] => 11
[bytes_received_eof_packet] => 0
[bytes_received_rset_header_packet] => 0
[bytes_received_rset_field_meta_packet] => 0
[bytes_received_rset_row_packet] => 0
[bytes_received_prepare_response_packet] => 0
[bytes_received_change_user_packet] => 0
[packets_sent_command] => 0
[packets_received_ok] => 1
[packets_received_eof] => 0
[packets_received_rset_header] => 0
[packets_received_rset_field_meta] => 0
[packets_received_rset_row] => 0
[packets_received_prepare_response] => 0
[packets_received_change_user] => 0
[result_set_queries] => 0
[non_result_set_queries] => 0
[no_index_used] => 0
[bad_index_used] => 0
[slow_queries] => 0
[buffered_sets] => 0
[unbuffered_sets] => 0
[ps_buffered_sets] => 0
[ps_unbuffered_sets] => 0
[flushed_normal_sets] => 0
[flushed_ps_sets] => 0
[ps_prepared_never_executed] => 0
[ps_prepared_once_executed] => 0
[rows_fetched_from_server_normal] => 0
[rows_fetched_from_server_ps] => 0
[rows_buffered_from_client_normal] => 0
[rows_buffered_from_client_ps] => 0
[rows_fetched_from_client_normal_buffered] => 0
[rows_fetched_from_client_normal_unbuffered] => 0
[rows_fetched_from_client_ps_buffered] => 0
[rows_fetched_from_client_ps_unbuffered] => 0
[rows_fetched_from_client_ps_cursor] => 0
[rows_skipped_normal] => 0
[rows_skipped_ps] => 0
[copy_on_write_saved] => 0
[copy_on_write_performed] => 0
[command_buffer_too_small] => 0
[connect_success] => 1
[connect_failure] => 0
[connection_reused] => 0
[reconnect] => 0
[pconnect_success] => 0
[active_connections] => 1
[active_persistent_connections] => 0
[explicit_close] => 0
[implicit_close] => 0
[disconnect_close] => 0
[in_middle_of_command_close] => 0
[explicit_free_result] => 0
[implicit_free_result] => 0
[explicit_stmt_close] => 0
[implicit_stmt_close] => 0
[mem_emalloc_count] => 0
[mem_emalloc_ammount] => 0
[mem_ecalloc_count] => 0
[mem_ecalloc_ammount] => 0
[mem_erealloc_count] => 0
[mem_erealloc_ammount] => 0
[mem_efree_count] => 0
[mem_malloc_count] => 0
[mem_malloc_ammount] => 0
[mem_calloc_count] => 0
[mem_calloc_ammount] => 0
[mem_realloc_count] => 0
[mem_realloc_ammount] => 0
[mem_free_count] => 0
[proto_text_fetched_null] => 0
[proto_text_fetched_bit] => 0
[proto_text_fetched_tinyint] => 0
[proto_text_fetched_short] => 0
[proto_text_fetched_int24] => 0
[proto_text_fetched_int] => 0
[proto_text_fetched_bigint] => 0
[proto_text_fetched_decimal] => 0
[proto_text_fetched_float] => 0
[proto_text_fetched_double] => 0
[proto_text_fetched_date] => 0
[proto_text_fetched_year] => 0
[proto_text_fetched_time] => 0
[proto_text_fetched_datetime] => 0
[proto_text_fetched_timestamp] => 0
[proto_text_fetched_string] => 0
[proto_text_fetched_blob] => 0
[proto_text_fetched_enum] => 0
[proto_text_fetched_set] => 0
[proto_text_fetched_geometry] => 0
[proto_text_fetched_other] => 0
[proto_binary_fetched_null] => 0
[proto_binary_fetched_bit] => 0
[proto_binary_fetched_tinyint] => 0
[proto_binary_fetched_short] => 0
[proto_binary_fetched_int24] => 0
[proto_binary_fetched_int] => 0
[proto_binary_fetched_bigint] => 0
[proto_binary_fetched_decimal] => 0
[proto_binary_fetched_float] => 0
[proto_binary_fetched_double] => 0
[proto_binary_fetched_date] => 0
[proto_binary_fetched_year] => 0
[proto_binary_fetched_time] => 0
[proto_binary_fetched_datetime] => 0
[proto_binary_fetched_timestamp] => 0
[proto_binary_fetched_string] => 0
[proto_binary_fetched_blob] => 0
[proto_binary_fetched_enum] => 0
[proto_binary_fetched_set] => 0
[proto_binary_fetched_geometry] => 0
[proto_binary_fetched_other] => 0
)
See Also
* Stats description
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_get_metadata
(PHP 5)
mysqli_get_metadata - Alias for mysqli_stmt_result_metadata()
Description
This function is an alias of mysqli_stmt_result_metadata().
Notes
Note:
mysqli_get_metadata() is deprecated and will be removed.
See Also
* mysqli_stmt_result_metadata() - Returns result set metadata from a
prepared statement
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_master_query
(PHP 5)
mysqli_master_query - Enforce execution of a query on the master in a
master/slave setup
Description
bool mysqli_master_query ( mysqli $link , string $query )
Warning
This function is currently not documented; only its argument list is
available.
Warning
This function has been DEPRECATED and REMOVED as of PHP 5.3.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_param_count
(PHP 5)
mysqli_param_count - Alias for mysqli_stmt_param_count()
Description
This function is an alias of mysqli_stmt_param_count().
Notes
Note:
mysqli_param_count() is deprecated and will be removed.
See Also
* mysqli_stmt_param_count() - Returns the number of parameter for the
given statement
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_report
(PHP 5)
mysqli_report - Enables or disables internal report functions
Description
bool mysqli_report ( int $flags )
mysqli_report() is a powerful function to improve your queries and code
during development and testing phase. Depending on the flags it reports
errors from mysqli function calls or queries which don't use an index (or
use a bad index).
Parameters
flags
Supported flags
Name Description
MYSQLI_REPORT_OFF Turns reporting off
MYSQLI_REPORT_ERROR Report errors from mysqli function calls
MYSQLI_REPORT_STRICT Throw mysqli_sql_exception for errors instead
of warnings
MYSQLI_REPORT_INDEX Report if no index or bad index was used in a
query
MYSQLI_REPORT_ALL Set all options (report all)
Return Values
Returns TRUE on success or FALSE on failure.
Changelog
Version Description
5.2.15 & 5.3.4 Changing the reporting mode is now be per-request, rather
than per-process.
Examples
Object oriented style
query("SELECT Name FROM Nonexistingtable WHERE population > 50000");
/* this query should report a bad index */
$result = $mysqli->query("SELECT Name FROM City WHERE population > 50000");
$result->close();
$mysqli->close();
?>
See Also
* MySQLi_Driver::$report_mode
* mysqli_debug() - Performs debugging operations
* mysqli_dump_debug_info() - Dump debugging information into the log
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_rpl_parse_enabled
(PHP 5)
mysqli_rpl_parse_enabled - Check if RPL parse is enabled
Description
int mysqli_rpl_parse_enabled ( mysqli $link )
Warning
This function is currently not documented; only its argument list is
available.
Warning
This function has been DEPRECATED and REMOVED as of PHP 5.3.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_rpl_probe
(PHP 5)
mysqli_rpl_probe - RPL probe
Description
bool mysqli_rpl_probe ( mysqli $link )
Warning
This function is currently not documented; only its argument list is
available.
Warning
This function has been DEPRECATED and REMOVED as of PHP 5.3.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_rpl_query_type
mysqli::rpl_query_type
(PHP 5)
mysqli_rpl_query_type -- mysqli::rpl_query_type - Returns RPL query type
Description
Object oriented style
int mysqli::rpl_query_type ( string $query )
Procedural style
int mysqli_rpl_query_type ( mysqli $link , string $query )
Returns MYSQLI_RPL_MASTER, MYSQLI_RPL_SLAVE or MYSQLI_RPL_ADMIN depending
on a query type. INSERT, UPDATE and similar are master queries, SELECT is
slave, and FLUSH, REPAIR and similar are admin.
Warning
This function is currently not documented; only its argument list is
available.
Warning
This function has been DEPRECATED and REMOVED as of PHP 5.3.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_send_long_data
(PHP 5)
mysqli_send_long_data - Alias for mysqli_stmt_send_long_data()
Description
This function is an alias of mysqli_stmt_send_long_data().
Notes
Note:
mysqli_send_long_data() is deprecated and will be removed.
See Also
* mysqli_stmt_send_long_data() - Send data in blocks
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_send_query
mysqli::send_query
(PHP 5)
mysqli_send_query -- mysqli::send_query - Send the query and return
Description
Object oriented style
bool mysqli::send_query ( string $query )
Procedural style
bool mysqli_send_query ( mysqli $link , string $query )
Warning
This function is currently not documented; only its argument list is
available.
Warning
This function has been DEPRECATED and REMOVED as of PHP 5.3.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_set_opt
(PHP 5)
mysqli_set_opt - Alias of mysqli_options()
Description
This function is an alias of mysqli_options().
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqli_slave_query
(PHP 5)
mysqli_slave_query - Force execution of a query on a slave in a
master/slave setup
Description
bool mysqli_slave_query ( mysqli $link , string $query )
Warning
This function is currently not documented; only its argument list is
available.
Warning
This function has been DEPRECATED and REMOVED as of PHP 5.3.0.
----------------------------------------------------------------------
Table of Contents
* mysqli_bind_param - Alias for mysqli_stmt_bind_param
* mysqli_bind_result - Alias for mysqli_stmt_bind_result
* mysqli_client_encoding - Alias of mysqli_character_set_name
* mysqli_connect - Alias of mysqli::__construct
* mysqli_disable_reads_from_master - Disable reads from master
* mysqli_disable_rpl_parse - Disable RPL parse
* mysqli_enable_reads_from_master - Enable reads from master
* mysqli_enable_rpl_parse - Enable RPL parse
* mysqli_escape_string - Alias of mysqli_real_escape_string
* mysqli_execute - Alias for mysqli_stmt_execute
* mysqli_fetch - Alias for mysqli_stmt_fetch
* mysqli_get_cache_stats - Returns client Zval cache statistics
* mysqli_get_metadata - Alias for mysqli_stmt_result_metadata
* mysqli_master_query - Enforce execution of a query on the master in a
master/slave setup
* mysqli_param_count - Alias for mysqli_stmt_param_count
* mysqli_report - Enables or disables internal report functions
* mysqli_rpl_parse_enabled - Check if RPL parse is enabled
* mysqli_rpl_probe - RPL probe
* mysqli_rpl_query_type - Returns RPL query type
* mysqli_send_long_data - Alias for mysqli_stmt_send_long_data
* mysqli_send_query - Send the query and return
* mysqli_set_opt - Alias of mysqli_options
* mysqli_slave_query - Force execution of a query on a slave in a
master/slave setup
----------------------------------------------------------------------
* Introduction
* Overview
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* The mysqli Extension and Persistent Connections
* Predefined Constants
* Notes
* The MySQLi Extension Function Summary
* MySQLi - The MySQLi class
* mysqli::affected_rows - Gets the number of affected rows in a
previous MySQL operation
* mysqli::autocommit - Turns on or off auto-commiting database
modifications
* mysqli::change_user - Changes the user of the specified database
connection
* mysqli::character_set_name - Returns the default character set
for the database connection
* mysqli::client_info - Returns the MySQL client version as a
string
* mysqli::client_version - Get MySQL client info
* mysqli::close - Closes a previously opened database connection
* mysqli::commit - Commits the current transaction
* mysqli::connect_errno - Returns the error code from last connect
call
* mysqli::connect_error - Returns a string description of the last
connect error
* mysqli::__construct - Open a new connection to the MySQL server
* mysqli::debug - Performs debugging operations
* mysqli::dump_debug_info - Dump debugging information into the log
* mysqli::errno - Returns the error code for the most recent
function call
* mysqli::error - Returns a string description of the last error
* mysqli::field_count - Returns the number of columns for the most
recent query
* mysqli::get_charset - Returns a character set object
* mysqli::get_client_info - Returns the MySQL client version as a
string
* mysqli_get_client_stats - Returns client per-process statistics
* mysqli::client_version - Get MySQL client info
* mysqli::get_connection_stats - Returns statistics about the
client connection
* mysqli::host_info - Returns a string representing the type of
connection used
* mysqli::protocol_version - Returns the version of the MySQL
protocol used
* mysqli::server_info - Returns the version of the MySQL server
* mysqli::server_version - Returns the version of the MySQL server
as an integer
* mysqli::get_warnings - Get result of SHOW WARNINGS
* mysqli::info - Retrieves information about the most recently
executed query
* mysqli::init - Initializes MySQLi and returns a resource for use
with mysqli_real_connect()
* mysqli::insert_id - Returns the auto generated id used in the
last query
* mysqli::kill - Asks the server to kill a MySQL thread
* mysqli::more_results - Check if there are any more query results
from a multi query
* mysqli::multi_query - Performs a query on the database
* mysqli::next_result - Prepare next result from multi_query
* mysqli::options - Set options
* mysqli::ping - Pings a server connection, or tries to reconnect
if the connection has gone down
* mysqli::poll - Poll connections
* mysqli::prepare - Prepare an SQL statement for execution
* mysqli::query - Performs a query on the database
* mysqli::real_connect - Opens a connection to a mysql server
* mysqli::real_escape_string - Escapes special characters in a
string for use in an SQL statement, taking into account the
current charset of the connection
* mysqli::real_query - Execute an SQL query
* mysqli::reap_async_query - Get result from async query
* mysqli::rollback - Rolls back current transaction
* mysqli::select_db - Selects the default database for database
queries
* mysqli::set_charset - Sets the default client character set
* mysqli::set_local_infile_default - Unsets user defined handler
for load local infile command
* mysqli::set_local_infile_handler - Set callback function for LOAD
DATA LOCAL INFILE command
* mysqli::sqlstate - Returns the SQLSTATE error from previous MySQL
operation
* mysqli::ssl_set - Used for establishing secure connections using
SSL
* mysqli::stat - Gets the current system status
* mysqli::stmt_init - Initializes a statement and returns an object
for use with mysqli_stmt_prepare
* mysqli::store_result - Transfers a result set from the last query
* mysqli::thread_id - Returns the thread ID for the current
connection
* mysqli::thread_safe - Returns whether thread safety is given or
not
* mysqli::use_result - Initiate a result set retrieval
* mysqli::warning_count - Returns the number of warnings from the
last query for the given link
* MySQLi_STMT - The MySQLi_STMT class
* mysqli_stmt::affected_rows - Returns the total number of rows
changed, deleted, or inserted by the last executed statement
* mysqli_stmt::attr_get - Used to get the current value of a
statement attribute
* mysqli_stmt::attr_set - Used to modify the behavior of a prepared
statement
* mysqli_stmt::bind_param - Binds variables to a prepared statement
as parameters
* mysqli_stmt::bind_result - Binds variables to a prepared
statement for result storage
* mysqli_stmt::close - Closes a prepared statement
* mysqli_stmt::data_seek - Seeks to an arbitrary row in statement
result set
* mysqli_stmt::errno - Returns the error code for the most recent
statement call
* mysqli_stmt::error - Returns a string description for last
statement error
* mysqli_stmt::execute - Executes a prepared Query
* mysqli_stmt::fetch - Fetch results from a prepared statement into
the bound variables
* mysqli_stmt::field_count - Returns the number of field in the
given statement
* mysqli_stmt::free_result - Frees stored result memory for the
given statement handle
* mysqli_stmt::get_result - Gets a result set from a prepared
statement
* mysqli_stmt::get_warnings - Get result of SHOW WARNINGS
* mysqli_stmt::insert_id - Get the ID generated from the previous
INSERT operation
* mysqli_stmt::num_rows - Return the number of rows in statements
result set
* mysqli_stmt::param_count - Returns the number of parameter for
the given statement
* mysqli_stmt::prepare - Prepare an SQL statement for execution
* mysqli_stmt::reset - Resets a prepared statement
* mysqli_stmt::result_metadata - Returns result set metadata from a
prepared statement
* mysqli_stmt::send_long_data - Send data in blocks
* mysqli_stmt::sqlstate - Returns SQLSTATE error from previous
statement operation
* mysqli_stmt::store_result - Transfers a result set from a
prepared statement
* MySQLi_Result - The MySQLi_Result class
* mysqli_result::current_field - Get current field offset of a
result pointer
* mysqli_result::data_seek - Adjusts the result pointer to an
arbitary row in the result
* mysqli_result::fetch_all - Fetches all result rows as an
associative array, a numeric array, or both
* mysqli_result::fetch_array - Fetch a result row as an
associative, a numeric array, or both
* mysqli_result::fetch_assoc - Fetch a result row as an associative
array
* mysqli_result::fetch_field_direct - Fetch meta-data for a single
field
* mysqli_result::fetch_field - Returns the next field in the result
set
* mysqli_result::fetch_fields - Returns an array of objects
representing the fields in a result set
* mysqli_result::fetch_object - Returns the current row of a result
set as an object
* mysqli_result::fetch_row - Get a result row as an enumerated
array
* mysqli_result::field_count - Get the number of fields in a result
* mysqli_result::field_seek - Set result pointer to a specified
field offset
* mysqli_result::free - Frees the memory associated with a result
* mysqli_result::lengths - Returns the lengths of the columns of
the current row in the result set
* mysqli_result::num_rows - Gets the number of rows in a result
* MySQLi_Driver - The MySQLi_Driver class
* mysqli_driver::embedded_server_end - Stop embedded server
* mysqli_driver::embedded_server_start - Initialize and start
embedded server
* MySQLi_Warning - The MySQLi_Warning class
* mysqli_warning::__construct - The __construct purpose
* mysqli_warning::next - The next purpose
* Aliases and deprecated Mysqli Functions
* mysqli_bind_param - Alias for mysqli_stmt_bind_param
* mysqli_bind_result - Alias for mysqli_stmt_bind_result
* mysqli_client_encoding - Alias of mysqli_character_set_name
* mysqli_connect - Alias of mysqli::__construct
* mysqli_disable_reads_from_master - Disable reads from master
* mysqli_disable_rpl_parse - Disable RPL parse
* mysqli_enable_reads_from_master - Enable reads from master
* mysqli_enable_rpl_parse - Enable RPL parse
* mysqli_escape_string - Alias of mysqli_real_escape_string
* mysqli_execute - Alias for mysqli_stmt_execute
* mysqli_fetch - Alias for mysqli_stmt_fetch
* mysqli_get_cache_stats - Returns client Zval cache statistics
* mysqli_get_metadata - Alias for mysqli_stmt_result_metadata
* mysqli_master_query - Enforce execution of a query on the master
in a master/slave setup
* mysqli_param_count - Alias for mysqli_stmt_param_count
* mysqli_report - Enables or disables internal report functions
* mysqli_rpl_parse_enabled - Check if RPL parse is enabled
* mysqli_rpl_probe - RPL probe
* mysqli_rpl_query_type - Returns RPL query type
* mysqli_send_long_data - Alias for mysqli_stmt_send_long_data
* mysqli_send_query - Send the query and return
* mysqli_set_opt - Alias of mysqli_options
* mysqli_slave_query - Force execution of a query on a slave in a
master/slave setup
----------------------------------------------------------------------
----------------------------------------------------------------------
MySQL Native Driver
----------------------------------------------------------------------
Introduction
This section of the manual provides an overview of the MySQL Native
Driver.
----------------------------------------------------------------------
----------------------------------------------------------------------
Overview
MySQL Native Driver is a replacement for the MySQL Client Library
(libmysql). MySQL Native Driver is part of the official PHP sources as of
PHP 5.3.0.
The MySQL database extensions MySQL extension, mysqli and PDO MYSQL all
communicate with the MySQL server. In the past, this was done by the
extension using the services provided by the MySQL Client Library. The
extensions were compiled against the MySQL Client Library in order to use
its client-server protocol.
With MySQL Native Driver there is now an alternative, as the MySQL
database extensions can be compiled to use MySQL Native Driver instead of
the MySQL Client Library.
MySQL Native Driver is written in C as a PHP extension.
What it is not
Although MySQL Native Driver is written as a PHP extension, it is
important to note that it does not provide a new API to the PHP
programmer. The programmer APIs for MySQL database connectivity are
provided by the MySQL extension, mysqli and PDO MYSQL. These extensions
can now use the services of MySQL Native Driver to communicate with the
MySQL Server. Therefore, you should not think of MySQL Native Driver as an
API.
Why use it?
Using the MySQL Native Driver offers a number of advantages over using the
MySQL Client Library.
The older MySQL Client Library was written by MySQL AB (now Oracle
Corporation) and so was released under the MySQL license. This ultimately
led to MySQL support being disabled by default in PHP. However, the MySQL
Native Driver has been developed as part of the PHP project, and is
therefore released under the PHP license. This removes licensing issues
that have been problematic in the past.
Also, in the past, you needed to build the MySQL database extensions
against a copy of the MySQL Client Library. This typically meant you
needed to have MySQL installed on a machine where you were building the
PHP source code. Also, when your PHP application was running, the MySQL
database extensions would call down to the MySQL Client library file at
run time, so the file needed to be installed on your system. With MySQL
Native Driver that is no longer the case as it is included as part of the
standard distribution. So you do not need MySQL installed in order to
build PHP or run PHP database applications.
Because MySQL Native Driver is written as a PHP extension, it is tightly
coupled to the workings of PHP. This leads to gains in efficiency,
especially when it comes to memory usage, as the driver uses the PHP
memory management system. It also supports the PHP memory limit. Using
MySQL Native Driver leads to comparable or better performance than using
MySQL Client Library, it always ensures the most efficient use of memory.
One example of the memory efficiency is the fact that when using the MySQL
Client Library, each row is stored in memory twice, whereas with the MySQL
Native Driver each row is only stored once in memory.
Special features
MySQL Native Driver also provides some special features not available when
the MySQL database extensions use MySQL Client Library. These special
features are listed below:
* Improved persistent connections
* The special function mysqli_fetch_all()
* Performance statistics calls: mysqli_get_cache_stats(),
mysqli_get_client_stats(), mysqli_get_connection_stats()
The performance statistics facility can prove to be very useful in
identifying performance bottlenecks.
MySQL Native Driver also allows for persistent connections when used with
the mysqli extension.
SSL Support
MySQL Native Driver has supported SSL since PHP version 5.3.3
Compressed Protocol Support
As of PHP 5.3.2 MySQL Native Driver supports the compressed client server
protocol. MySQL Native Driver did not support this in 5.3.0 and 5.3.1.
Extensions such as ext/mysql, ext/mysqli, that are configured to use MySQL
Native Driver, can also take advantage of this feature. Note that
PDO_MYSQL does NOT support compression when used together with mysqlnd.
Named Pipes Support
Named pipes support for Windows was added in PHP version 5.4.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
Installation on Unix
By default the MySQL database extensions are configured to use MySQL
Client Library. In order to use the MySQL Native Driver, PHP needs to be
built specifying that the MySQL database extensions are compiled with
MySQL Native Driver support. This is done through configuration options
prior to building the PHP source code.
For example, to build the MySQL extension, mysqli and PDO MYSQL using the
MySQL Native Driver, the following command would be given:
./configure --with-mysql=mysqlnd \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd \
[other options]
Installation on Windows
In the official PHP distributions from 5.3 onwards, MySQL Native Driver is
enabled by default, so no additional configuration is required to use it.
All MySQL database extensions will use MySQL Native Driver in this case.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
MySQL Native Driver Configuration Options
Name Default Changeable Changelog
Available
mysqlnd.collect_statistics "1" PHP_INI_SYSTEM since PHP
5.3.0.
Available
mysqlnd.collect_memory_statistics "0" PHP_INI_SYSTEM since PHP
5.3.0.
Available
mysqlnd.debug "0" PHP_INI_SYSTEM since PHP
5.3.0.
Available
mysqlnd.net_read_timeout "31536000" PHP_INI_SYSTEM since PHP
5.3.0.
5.3.0 - Available
mysqlnd.net_cmd_buffer_size "2048", 5.3.1 PHP_INI_SYSTEM since PHP
- "4096" 5.3.0.
Available
mysqlnd.net_read_buffer_size "32768" PHP_INI_SYSTEM since PHP
5.3.0.
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
mysqlnd.collect_statistics boolean
Enables the collection of various client statistics which can be
accessed through mysqli_get_client_stats(),
mysqli_get_connection_stats(), mysqli_get_cache_stats() and are
shown in mysqlnd section of the output of the phpinfo() function
as well.
This configuration setting enables all MySQL Native Driver
statistics except those relating to memory management.
mysqlnd.collect_memory_statistics boolean
Enable the collection of various memory statistics which can be
accessed through mysqli_get_client_stats(),
mysqli_get_connection_stats(), mysqli_get_cache_stats() and are
shown in mysqlnd section of the output of the phpinfo() function
as well.
This configuration setting enables the memory management
statistics within the overall set of MySQL Native Driver
statistics.
mysqlnd.debug string
Records communication from all extensions using mysqlnd to the
specified log file.
The format of the directive is mysqlnd.debug =
"option1[,parameter_option1][:option2[,parameter_option2]]".
The options for the format string are as follows:
* A[,file] - Appends trace output to specified file. Also
ensures that data is written after each write. This is done
by closing and reopening the trace file (this is slow). It
helps ensure a complete log file should the application
crash.
* a[,file] - Appends trace output to the specified file.
* d - Enables output from DBUG_ macros for the current
state. May be followed by a list of keywords which selects
output only for the DBUG macros with that keyword. An empty
list of keywords implies output for all macros.
* f[,functions] - Limits debugger actions to the specified list
of functions. An empty list of functions implies that all
functions are selected.
* F - Marks each debugger output line with the name of the
source file containing the macro causing the output.
* i - Marks each debugger output line with the PID of the
current process.
* L - Marks each debugger output line with the name of the
source file line number of the macro causing the output.
* n - Marks each debugger output line with the current function
nesting depth
* o[,file] - Similar to a[,file] but overwrites old file, and
does not append.
* O[,file] - Similar to A[,file] but overwrites old file, and
does not append.
* t[,N] - Enables function control flow tracing. The maximum
nesting depth is specified by N, and defaults to 200.
* x - This option activates profiling.
Example:
d:t:x:O,/tmp/mysqlnd.trace
Note:
This feature is only available with a debug build of PHP. Works
on Microsoft Windows if using a debug build of PHP and PHP was
built using Microsoft Visual C version 9 and above.
mysqlnd.net_read_timeout integer
mysqlnd and the MySQL Client Library, libmysql use different
networking APIs. mysqlnd uses PHP streams, whereas libmysql uses
its own wrapper around the operating level network calls. PHP, by
default, sets a read timeout of 60s for streams. This is set via
php.ini, default_socket_timeout. This default applies to all
streams that set no other timeout value. mysqlnd does not set any
other value and therefore connections of long running queries can
be disconnected after default_socket_timeout seconds resulting in
an error message "2006 - MySQL Server has gone away". The MySQL
Client Library sets a default timeout of 365 * 24 * 3600 seconds
(1 year) and waits for other timeouts to occur, such as TCP/IP
timeouts. mysqlnd now uses the same very long timeout. The value
is configurable through a new php.ini setting:
mysqlnd.net_read_timeout. mysqlnd.net_read_timeout gets used by
any extension (ext/mysql, ext/mysqli, PDO_MySQL) that uses
mysqlnd. mysqlnd tells PHP Streams to use
mysqlnd.net_read_timeout. Please note that there may be subtle
differences between MYSQL_OPT_READ_TIMEOUT from the MySQL Client
Library and PHP Streams, for example MYSQL_OPT_READ_TIMEOUT is
documented to work only for TCP/IP connections and, prior to MySQL
5.1.2, only for Windows. PHP streams may not have this limitation.
Please check the streams documentation, if in doubt.
mysqlnd.net_cmd_buffer_size long
mysqlnd allocates an internal command/network buffer of
mysqlnd.net_cmd_buffer_size (in php.ini) bytes for every
connection. If a MySQL Client Server protocol command, for
example, COM_QUERY ("normal" query), does not fit into the buffer,
mysqlnd will grow the buffer to the size required for sending the
command. Whenever the buffer gets extended for one connection,
command_buffer_too_small will be incremented by one.
If mysqlnd has to grow the buffer beyond its initial size of
mysqlnd.net_cmd_buffer_size bytes for almost every connection, you
should consider increasing the default size to avoid
re-allocations.
The default buffer size is 2048 bytes in PHP 5.3.0. In later
versions the default is 4096 bytes. The default can changed either
through the php.ini setting mysqlnd.net_cmd_buffer_size or using
mysqli_options(MYSQLI_OPT_NET_CMD_BUFFER_SIZE, int size).
It is recommended that the buffer size be set to no less than 4096
bytes because mysqlnd also uses it when reading certain
communication packet from MySQL. In PHP 5.3.0, mysqlnd will not
grow the buffer if MySQL sends a packet that is larger than the
current size of the buffer. As a consequence, mysqlnd is unable to
decode the packet and the client application will get an error.
There are only two situations when the packet can be larger than
the 2048 bytes default of mysqlnd.net_cmd_buffer_size in PHP
5.3.0: the packet transports a very long error message, or the
packet holds column meta data from COM_LIST_FIELD
(mysql_list_fields() and the meta data come from a string column
with a very long default value (>1900 bytes).
As of PHP 5.3.2 mysqlnd does not allow setting buffers smaller
than 4096 bytes.
The value can also be set using mysqli_option(link,
MYSQLI_OPT_NET_CMD_BUFFER_SIZE, size).
mysqlnd.net_read_buffer_size long
Maximum read chunk size in bytes when reading the body of a MySQL
command packet. The MySQL client server protocol encapsulates all
its commands in packets. The packets consist of a small header and
a body with the actual payload. The size of the body is encoded in
the header. mysqlnd reads the body in chunks of MIN(header.size,
mysqlnd.net_read_buffer_size) bytes. If a packet body is larger
than mysqlnd.net_read_buffer_size bytes, mysqlnd has to call
read() multiple times.
The value can also be set using mysqli_optionS(link,
MYSQLI_OPT_NET_READ_BUFFER_SIZE, size).
----------------------------------------------------------------------
----------------------------------------------------------------------
Persistent Connections
Using Persistent Connections
If mysqli is used with mysqlnd, when a persistent connection is created it
generates a COM_CHANGE_USER (mysql_change_user()) call on the server. This
ensures that re-authentication of the connection takes place.
As there is some overhead associated with the COM_CHANGE_USER call, it is
possible to switch this off at compile time. Reusing a persistent
connection will then generate a COM_PING (mysql_ping) call to simply test
the connection is reusable.
Generation of COM_CHANGE_USER can be switched off with the compile flag
MYSQLI_NO_CHANGE_USER_ON_PCONNECT. For example:
shell# CFLAGS="-DMYSQLI_NO_CHANGE_USER_ON_PCONNECT" ./configure --with-mysql=/usr/local/mysql/ --with-mysqli=/usr/local/mysql/bin/mysql_config --with-pdo-mysql=/usr/local/mysql/bin/mysql_config --enable-debug && make clean && make -j6
Or alternatively:
shell# export CFLAGS="-DMYSQLI_NO_CHANGE_USER_ON_PCONNECT"
shell# configure --whatever-option
shell# make clean
shell# make
Note that only mysqli on mysqlnd uses COM_CHANGE_USER. Other
extension-driver combinations use COM_PING on initial use of a persistent
connection.
----------------------------------------------------------------------
----------------------------------------------------------------------
Statistics
Using Statistical Data
MySQL Native Driver contains support for gathering statistics on the
communication between the client and the server. The statistics gathered
are of three main types:
* Client statistics
* Connection statistics
* Zval cache statistics
If you are using the mysqli extension, these statistics can be obtained
through three API calls:
* mysqli_get_client_stats()
* mysqli_get_connection_stats()
* mysqli_get_cache_stats()
Note:
Statistics are aggregated among all extensions that use MySQL Native
Driver. For example, when compiling both ext/mysql and ext/mysqli
against MySQL Native Driver, both function calls of ext/mysql and
ext/mysqli will change the statistics. There is no way to find out how
much a certain API call of any extension that has been compiled against
MySQL Native Driver has impacted a certain statistic. You can configure
the PDO MySQL Driver, ext/mysql and ext/mysqli to optionally use the
MySQL Native Driver. When doing so, all three extensions will change the
statistics.
Accessing Client Statistics
To access client statistics, you need to call mysqli_get_client_stats().
The function call does not require any parameters.
The function returns an associative array that contains the name of the
statistic as the key and the statistical data as the value.
Client statistics can also be accessed by calling the phpinfo() function.
Accessing Connection Statistics
To access connection statistics call mysqli_get_connection_stats(). This
takes the database connection handle as the parameter.
The function returns an associative array that contains the name of the
statistic as the key and the statistical data as the value.
Accessing Zval Cache Statistics
The MySQL Native Driver also collects statistics from its internal Zval
cache. These statistics can be accessed by calling
mysqli_get_cache_stats().
The Zval cache statistics obtained may lead to a tweaking of php.ini
settings related to the Zval cache, resulting in better performance.
Buffered and Unbuffered Result Sets
Result sets can be buffered or unbuffered. Using default settings,
ext/mysql and ext/mysqli work with buffered result sets for normal (non
prepared statement) queries. Buffered result sets are cached on the
client. After the query execution all results are fetched from the MySQL
Server and stored in a cache on the client. The big advantage of buffered
result sets is that they allow the server to free all resources allocated
to a result set, once the results have been fetched by the client.
Unbuffered result sets on the other hand are kept much longer on the
server. If you want to reduce memory consumption on the client, but
increase load on the server, use unbuffered results. If you experience a
high server load and the figures for unbuffered result sets are high, you
should consider moving the load to the clients. Clients typically scale
better than servers. "Load" does not only refer to memory buffers - the
server also needs to keep other resources open, for example file handles
and threads, before a result set can be freed.
Prepared Statements use unbuffered result sets by default. However, you
can use mysqli_stmt_store_result() to enable buffered result sets.
Statistics returned by MySQL Native Driver
The following tables show a list of statistics returned by the
mysqli_get_client_stats(), mysqli_get_connection_stats() and
mysqli_get_cache_stats() functions.
Network
Statistic Scope Description Notes
bytes_sent Connection Number of bytes sent from PHP to the Can be used to check the efficiency of
MySQL server the compression protocol
bytes_received Connection Number of bytes received from MySQL Can be used to check the efficiency of
server the compression protocol
packets_sent Connection Number of MySQL Client Server protocol Used for debugging Client Server
packets sent protocol implementation
packets_received Connection Number of MySQL Client Server protocol Used for debugging Client Server
packets received protocol implementation
MySQL Client Server protocol overhead
in bytes for incoming traffic.
protocol_overhead_in Connection Currently only the Packet Header (4 Used for debugging Client Server
bytes) is considered as overhead. protocol implementation
protocol_overhead_in =
packets_received * 4
MySQL Client Server protocol overhead
in bytes for outgoing traffic.
protocol_overhead_out Connection Currently only the Packet Header (4 Used for debugging Client Server
bytes) is considered as overhead. protocol implementation
protocol_overhead_out = packets_sent *
4
Total size of bytes of MySQL Client Used for debugging CS protocol
Server protocol OK packets received. implementation. Note that the total
bytes_received_ok_packet Connection OK packets can contain a status size in bytes includes the size of the
message. The length of the status header packet (4 bytes, see protocol
message can vary and thus the size of overhead).
an OK packet is not fixed.
Used for debugging CS protocol
Number of MySQL Client Server protocol implementation. Note that the total
packets_received_ok Connection OK packets received. size in bytes includes the size of the
header packet (4 bytes, see protocol
overhead).
Total size in bytes of MySQL Client Used for debugging CS protocol
Server protocol EOF packets received. implementation. Note that the total
bytes_received_eof_packet Connection EOF can vary in size depending on the size in bytes includes the size of the
server version. Also, EOF can header packet (4 bytes, see protocol
transport an error message. overhead).
Number of MySQL Client Server protocol Used for debugging CS protocol
EOF packets. Like with other packet implementation. Note that the total
packets_received_eof Connection statistics the number of packets will size in bytes includes the size of the
be increased even if PHP does not header packet (4 bytes, see protocol
receive the expected packet but, for overhead).
example, an error message.
Total size in bytes of MySQL Client Used for debugging CS protocol
Server protocol result set header implementation. Note that the total
bytes_received_rset_header_packet Connection packets. The size of the packets size in bytes includes the size of the
varies depending on the payload (LOAD header packet (4 bytes, see protocol
LOCAL INFILE, INSERT, UPDATE, SELECT, overhead).
error message).
Used for debugging CS protocol
Number of MySQL Client Server protocol implementation. Note that the total
packets_received_rset_header Connection result set header packets. size in bytes includes the size of the
header packet (4 bytes, see protocol
overhead).
Total size in bytes of MySQL Client
Server protocol result set meta data Only useful for debugging CS protocol
(field information) packets. Of course implementation. Note that the total
bytes_received_rset_field_meta_packet Connection the size varies with the fields in the size in bytes includes the size of the
result set. The packet may also header packet (4 bytes, see protocol
transport an error or an EOF packet in overhead).
case of COM_LIST_FIELDS.
Only useful for debugging CS protocol
Number of MySQL Client Server protocol implementation. Note that the total
packets_received_rset_field_meta Connection result set meta data (field size in bytes includes the size of the
information) packets. header packet (4 bytes, see protocol
overhead).
Total size in bytes of MySQL Client
Server protocol result set row data
packets. The packet may also transport Only useful for debugging CS protocol
an error or an EOF packet. You can implementation. Note that the total
bytes_received_rset_row_packet Connection reverse engineer the number of error size in bytes includes the size of the
and EOF packets by substracting header packet (4 bytes, see protocol
rows_fetched_from_server_normal and overhead).
rows_fetched_from_server_ps from
bytes_received_rset_row_packet.
Only useful for debugging CS protocol
Number of MySQL Client Server protocol implementation. Note that the total
packets_received_rset_row Connection result set row data packets and their size in bytes includes the size of the
total size in bytes. header packet (4 bytes, see protocol
overhead).
Total size in bytes of MySQL Client
Server protocol OK for Prepared
Statement Initialization packets
(prepared statement init packets). The
packet may also transport an error.
The packet size depends on the MySQL
version: 9 bytes with MySQL 4.1 and 12 Only useful for debugging CS protocol
bytes from MySQL 5.0 on. There is no implementation. Note that the total
bytes_received_prepare_response_packet Connection safe way to know how many errors size in bytes includes the size of the
happened. You may be able to guess header packet (4 bytes, see protocol
that an error has occurred if, for overhead).
example, you always connect to MySQL
5.0 or newer and,
bytes_received_prepare_response_packet
!= packets_received_prepare_response *
12. See also
ps_prepared_never_executed,
ps_prepared_once_executed.
Number of MySQL Client Server protocol Only useful for debugging CS protocol
OK for Prepared Statement implementation. Note that the total
packets_received_prepare_response Connection Initialization packets (prepared size in bytes includes the size of the
statement init packets). header packet (4 bytes, see protocol
overhead).
Total size in bytes of MySQL Client Only useful for debugging CS protocol
Server protocol COM_CHANGE_USER implementation. Note that the total
bytes_received_change_user_packet Connection packets. The packet may also transport size in bytes includes the size of the
an error or EOF. header packet (4 bytes, see protocol
overhead).
Only useful for debugging CS protocol
Number of MySQL Client Server protocol implementation. Note that the total
packets_received_change_user Connection COM_CHANGE_USER packets size in bytes includes the size of the
header packet (4 bytes, see protocol
overhead).
Number of MySQL Client Server protocol
commands sent from PHP to MySQL. There
is no way to know which specific
commands and how many of them have
been sent. At its best you can use it
to check if PHP has sent any commands
packets_sent_command Connection to MySQL to know if you can consider Only useful for debugging CS protocol
to disable MySQL support in your PHP implementation.
binary. There is also no way to
reverse engineer the number of errors
that may have occurred while sending
data to MySQL. The only error recoded
is command_buffer_too_small (see
below).
This is the size of the actual data
contained in result sets that do not
originate from prepared statements and
which have been fetched by the PHP
client. Note that although a full
result set may have been pulled from
MySQL by mysqlnd, this statistic only
counts actual data pulled from mysqlnd
by the PHP client. An example of a
code sequence that will increase the
value is as follows:
$mysqli = new mysqli();
$res = $mysqli->query("SELECT 'abc'");
Number of bytes of payload fetched by $res->fetch_assoc();
bytes_received_real_data_normal Connection the PHP client from mysqlnd using the $res->close();
text protocol.
Every fetch operation will increase
the value.
The statistic will not be increased if
the result set is only buffered on the
client, but not fetched, such as in
the following example:
$mysqli = new mysqli();
$res = $mysqli->query("SELECT 'abc'");
$res->close();
This statistic is available as of PHP
version 5.3.4.
This is the size of the actual data
contained in result sets that
originate from prepared statements and
which has been fetched by the PHP
client. The value will not be
increased if the result set is not
Number of bytes of the payload fetched subsequently read by the PHP client.
bytes_received_real_data_ps Connection by the PHP client from mysqlnd using Note that although a full result set
the prepared statement protocol. may have been pulled from MySQL by
mysqlnd, this statistic only counts
actual data pulled from mysqlnd by the
PHP client. See also
bytes_received_real_data_normal. This
statistic is available as of PHP
version 5.3.4.
Result Set
Statistic Scope Description Notes
Number of queries that have
generated a result set. Examples You may use it as an indirect
of queries that generate a result measure for the number of queries
result_set_queries Connection set: SELECT, SHOW. The statistic PHP has sent to MySQL, for
will not be incremented if there example, to identify a client that
is an error reading the result set causes a high database load.
header packet from the line.
Number of queries that did not
generate a result set. Examples of You may use it as an indirect
queries that do not generate a measure for the number of queries
non_result_set_queries Connection result set: INSERT, UPDATE, LOAD PHP has sent to MySQL, for
DATA, SHOW. The statistic will not example, to identify a client that
be incremented if there is an causes a high database load.
error reading the result set
header packet from the line.
Number of queries that have
generated a result set but did not
use an index (see also mysqld
start option
-log-queries-not-using-indexes).
If you want these queries to be
no_index_used Connection reported you can use
mysqli_report(MYSQLI_REPORT_INDEX)
to make ext/mysqli throw an
exception. If you prefer a warning
instead of an exception use
mysqli_report(MYSQLI_REPORT_INDEX
^ MYSQLI_REPORT_STRICT).
If you want these queries to be
reported you can use
Number of queries that have mysqli_report(MYSQLI_REPORT_INDEX)
bad_index_used Connection generated a result set and did not to make ext/mysqli throw an
use a good index (see also mysqld exception. If you prefer a warning
start option -log-slow-queries). instead of an exception use
mysqli_report(MYSQLI_REPORT_INDEX
^ MYSQLI_REPORT_STRICT)
SQL statements that took more than
long_query_time seconds to execute Not reported through
slow_queries Connection and required at least mysqli_report()
min_examined_row_limit rows to be
examined.
Examples of API calls that will
buffer result sets on the client:
mysql_query(), mysqli_query(),
mysqli_store_result(),
mysqli_stmt_get_result().
Buffering result sets on the
client ensures that server
resources are freed as soon as
possible and it makes result set
scrolling easier. The downside is
the additional memory consumption
on the client for buffering data.
Number of buffered result sets Note that mysqlnd (unlike the
returned by "normal" queries. MySQL Client Library) respects the
buffered_sets Connection "Normal" means "not prepared PHP memory limit because it uses
statement" in the following notes. PHP internal memory management
functions to allocate memory. This
is also the reason why
memory_get_usage() reports a higer
memory consumption when using
mysqlnd instead of the MySQL
Client Library. memory_get_usage()
does not measure the memory
consumption of the MySQL Client
Library at all because the MySQL
Client Library does not use PHP
internal memory management
functions monitored by the
function!
Number of unbuffered result sets Examples of API calls that will
unbuffered_sets Connection returned by normal (non prepared not buffer result sets on the
statement) queries. client: mysqli_use_result()
Number of buffered result sets Examples of API calls that will
ps_buffered_sets Connection returned by prepared statements. not buffer result sets on the
By default prepared statements are client: mysqli_stmt_store_result
unbuffered.
ps_unbuffered_sets Connection Number of unbuffered result sets By default prepared statements are
returned by prepared statements. unbuffered.
Unbuffered result sets must be
fetched completely before a new
query can be run on the connection
otherwise MySQL will throw an
error. If the application does not
fetch all rows from an unbuffered
result set, mysqlnd does
implicitly fetch the result set to
Number of result sets from normal clear the line. See also
(non prepared statement) queries rows_skipped_normal,
flushed_normal_sets Connection with unread data which have been rows_skipped_ps. Some possible
flushed silently for you. Flushing causes for an implicit flush:
happens only with unbuffered * Faulty client application
result sets.
* Client stopped reading after
it found what it was looking
for but has made MySQL
calculate more records than
needed
* Client application has stopped
unexpectedly
Unbuffered result sets must be
fetched completely before a new
query can be run on the connection
otherwise MySQL will throw an
error. If the application does not
fetch all rows from an unbuffered
result set, mysqlnd does
implicitly fetch the result set to
Number of result sets from clear the line. See also
prepared statements with unread rows_skipped_normal,
flushed_ps_sets Connection data which have been flushed rows_skipped_ps. Some possible
silently for you. Flushing happens causes for an implicit flush:
only with unbuffered result sets. * Faulty client application
* Client stopped reading after
it found what it was looking
for but has made MySQL
calculate more records than
needed
* Client application has stopped
unexpectedly
Prepared statements occupy server
ps_prepared_never_executed Connection Number of statements prepared but resources. You should not prepare
never executed. a statement if you do not plan to
execute it.
One of the ideas behind prepared
statements is that the same query
gets executed over and over again
(with different parameters) and
some parsing and other preparation
work can be saved, if statement
execution is split up in separate
prepare and execute stages. The
idea is to prepare once and
"cache" results, for example, the
ps_prepared_once_executed Connection Number of prepared statements parse tree to be reused during
executed only one. multiple statement executions. If
you execute a prepared statement
only once the two stage processing
can be inefficient compared to
"normal" queries because all the
caching means extra work and it
takes (limited) server resources
to hold the cached information.
Consequently, prepared statements
that are executed only once may
cause performance hurts.
Total number of result set rows
successfully fetched from MySQL
regardless if the client
rows_fetched_from_server_normal, Connection application has consumed them or See also packets_received_rset_row
rows_fetched_from_server_ps not. Some of the rows may not have
been fetched by the client
application but have been flushed
implicitly.
Total number of succesfully
buffered rows originating from a
"normal" query or a prepared
statement. This is the number of
rows that have been fetched from
MySQL and buffered on client. Note
that there are two distinct
statistics on rows that have been
buffered (MySQL to mysqlnd
rows_buffered_from_client_normal, internal buffer) and buffered rows Examples of queries that will
rows_buffered_from_client_ps Connection that have been fetched by the buffer results: mysqli_query(),
client application (mysqlnd mysqli_store_result()
internal buffer to client
application). If the number of
buffered rows is higher than the
number of fetched buffered rows it
can mean that the client
application runs queries that
cause larger result sets than
needed resulting in rows not read
by the client.
Total number of rows fetched by
rows_fetched_from_client_normal_buffered, Connection the client from a buffered result
rows_fetched_from_client_ps_buffered set created by a normal query or a
prepared statement.
Total number of rows fetched by
rows_fetched_from_client_normal_unbuffered, Connection the client from a unbuffered
rows_fetched_from_client_ps_unbuffered result set created by a "normal"
query or a prepared statement.
Total number of rows fetch by the
rows_fetched_from_client_ps_cursor Connection client from a cursor created by a
prepared statement.
rows_skipped_normal, rows_skipped_ps Connection Reserved for future use (currently
not supported)
With mysqlnd, variables returned
by the extensions point into
mysqlnd internal network result
buffers. If you do not change the
variables, fetched data will be
kept only once in memory. If you
change the variables, mysqlnd has
to perform a copy-on-write to
protect the internal network
copy_on_write_saved, Process result buffers from being changed.
copy_on_write_performed With the MySQL Client Library you
always hold fetched data twice in
memory. Once in the internal MySQL
Client Library buffers and once in
the variables returned by the
extensions. In theory mysqlnd can
save up to 40% memory. However,
note that the memory saving cannot
be measured using
memory_get_usage().
Connection, The free is always considered
Process explicit but for result sets
(only created by an init command, for
explicit_free_result, implicit_free_result during Total number of freed result sets. example,
prepared mysqli_options(MYSQLI_INIT_COMMAND
statement , ...)
cleanup)
Mapping from C API / MySQL meta
data type to statistics name:
* MYSQL_TYPE_NULL -
proto_text_fetched_null
* MYSQL_TYPE_BIT -
proto_text_fetched_bit
* MYSQL_TYPE_TINY -
proto_text_fetched_tinyint
* MYSQL_TYPE_SHORT -
proto_text_fetched_short
* MYSQL_TYPE_INT24 -
proto_text_fetched_int24
* MYSQL_TYPE_LONG -
proto_text_fetched_int
* MYSQL_TYPE_LONGLONG -
proto_text_fetched_bigint
* MYSQL_TYPE_DECIMAL,
MYSQL_TYPE_NEWDECIMAL -
proto_text_fetched_decimal
* MYSQL_TYPE_FLOAT -
proto_text_fetched_null, proto_text_fetched_float
proto_text_fetched_bit,
proto_text_fetched_tinyint * MYSQL_TYPE_DOUBLE -
proto_text_fetched_short, proto_text_fetched_double
proto_text_fetched_int24,
proto_text_fetched_int * MYSQL_TYPE_DATE,
proto_text_fetched_bigint, MYSQL_TYPE_NEWDATE -
proto_text_fetched_decimal, proto_text_fetched_date
proto_text_fetched_float
proto_text_fetched_double, Total number of columns of a * MYSQL_TYPE_YEAR -
proto_text_fetched_date, Connection certain type fetched from a normal proto_text_fetched_year
proto_text_fetched_year query (MySQL text protocol).
proto_text_fetched_time, * MYSQL_TYPE_TIME -
proto_text_fetched_datetime, proto_text_fetched_time
proto_text_fetched_timestamp
proto_text_fetched_string, * MYSQL_TYPE_DATETIME -
proto_text_fetched_blob, proto_text_fetched_datetime
proto_text_fetched_enum
proto_text_fetched_set, * MYSQL_TYPE_TIMESTAMP -
proto_text_fetched_geometry, proto_text_fetched_timestamp
proto_text_fetched_other
* MYSQL_TYPE_STRING,
MYSQL_TYPE_VARSTRING,
MYSQL_TYPE_VARCHAR -
proto_text_fetched_string
* MYSQL_TYPE_TINY_BLOB,
MYSQL_TYPE_MEDIUM_BLOB,
MYSQL_TYPE_LONG_BLOB,
MYSQL_TYPE_BLOB -
proto_text_fetched_blob
* MYSQL_TYPE_ENUM -
proto_text_fetched_enum
* MYSQL_TYPE_SET -
proto_text_fetched_set
* MYSQL_TYPE_GEOMETRY -
proto_text_fetched_geometry
* Any MYSQL_TYPE_* not listed
before (there should be none)
- proto_text_fetched_other
Note that the MYSQL_*-type
constants may not be associated
with the very same SQL column
types in every version of MySQL.
proto_binary_fetched_null,
proto_binary_fetched_bit,
proto_binary_fetched_tinyint
proto_binary_fetched_short,
proto_binary_fetched_int24,
proto_binary_fetched_int,
proto_binary_fetched_bigint,
proto_binary_fetched_decimal,
proto_binary_fetched_float, Total number of columns of a
proto_binary_fetched_double, certain type fetched from a For type mapping see proto_text_*
proto_binary_fetched_date, Connection prepared statement (MySQL binary described in the preceding text.
proto_binary_fetched_year, protocol).
proto_binary_fetched_time,
proto_binary_fetched_datetime,
proto_binary_fetched_timestamp,
proto_binary_fetched_string,
proto_binary_fetched_blob,
proto_binary_fetched_enum,
proto_binary_fetched_set,
proto_binary_fetched_geometry,
proto_binary_fetched_other
Connection
Statistic Scope Description Notes
connect_success, Connection Total number of successful / Reused connections and all other kinds of
connect_failure failed connection attempt. connections are included.
The code sequence $link = new mysqli(...);
$link->real_connect(...) will cause a
Total number of (real_)connect reconnect. But $link = new mysqli(...);
reconnect Process attempts made on an already opened $link->connect(...) will not because
connection handle. $link->connect(...) will explicitly close
the existing connection before a new
connection is established.
Note that connect_success holds the sum of
successful persistent and non-persistent
pconnect_success Connection Total number of successful connection attempts. The number of
persistent connection attempts. successful non-persistent connection
attempts is connect_success -
pconnect_success.
active_connections Connection Total number of active persistent
and non-persistent connections.
Total number of active persistent The total number of active non-persistent
active_persistent_connections Connection connections. connections is active_connections -
active_persistent_connections.
Examples of code snippets that cause an
Total number of explicitly closed explicit close :
explicit_close Connection connections (ext/mysqli only).
$link = new mysqli(...); $link->close(...)
$link = new mysqli(...); $link->connect(...)
Examples of code snippets that cause an
implicit close :
* $link = new mysqli(...);
$link->real_connect(...)
* unset($link)
* Persistent connection: pooled connection
has been created with real_connect and
implicit_close Connection Total number of implicitly closed there may be unknown options set - close
connections (ext/mysqli only). implicitly to avoid returning a
connection with unknown options
* Persistent connection: ping/change_user
fails and ext/mysqli closes the
connection
* end of script execution: close
connections that have not been closed by
the user
Connection failures indicated by It is called disconnect_close because the
disconnect_close Connection the C API call connection handle passed to the C API call
mysql_real_connect() during an will be closed.
attempt to establish a connection.
A connection has been closed in
the middle of a command execution Unless you use asynchronous queries this
(outstanding result sets not should only happen if your script stops
in_middle_of_command_close Process fetched, after sending a query and unexpectedly and PHP shuts down the
before retrieving an answer, while connections for you.
fetching data, while transferring
data with LOAD DATA).
Total number of init command The number of successful executions is
init_command_executed_count Connection executions, for example, init_command_executed_count -
mysqli_options(MYSQLI_INIT_COMMAND init_command_failed_count.
, ...).
init_command_failed_count Connection Total number of failed init
commands.
COM_* Commands
Statistic Scope Description Notes
The statistics are
incremented after
checking the line and
immediately before
sending the
corresponding MySQL
client server protocol
packet. If mysqlnd
fails to send the
packet over the wire
the statistics will
not be decremented. In
case of a failure
com_quit, com_init_db, mysqlnd emits a PHP
com_query, com_field_list, warning "Error while
com_create_db, com_drop_db, sending %s packet.
com_refresh, com_shutdown, PID=%d."
com_statistics,
com_process_info, Usage examples:
com_connect,
com_process_kill, Total number * Check if PHP sends
com_debug, com_ping, of attempts certain commands
com_time, to send a to MySQL, for
com_delayed_insert, certain example, check if
com_change_user, Connection COM_* a client sends
com_binlog_dump, command from COM_PROCESS_KILL
com_table_dump, PHP to
com_connect_out, MySQL. * Calculate the
com_register_slave, average number of
com_stmt_prepare, prepared statement
com_stmt_execute, executions by
com_stmt_send_long_data, comparing
com_stmt_close, COM_EXECUTE with
com_stmt_reset, COM_PREPARE
com_stmt_set_option,
com_stmt_fetch, com_daemon * Check if PHP has
run any
non-prepared SQL
statements by
checking if
COM_QUERY is zero
* Identify PHP
scripts that run
an excessive
number of SQL
statements by
checking COM_QUERY
and COM_EXECUTE
Miscellaneous
Statistic Scope Description Notes
Total
explicit_stmt_close, number of A close is always considered explicit but for
implicit_stmt_close Process close a failed prepare.
prepared
statements.
mem_emalloc_count,
mem_emalloc_ammount,
mem_ecalloc_count,
mem_ecalloc_ammount,
mem_erealloc_count,
mem_erealloc_ammount, Memory
mem_efree_count, Process management Development only.
mem_malloc_count, calls.
mem_malloc_ammount,
mem_calloc_count,
mem_calloc_ammount,
mem_realloc_count,
mem_realloc_ammount,
mem_free_count
mysqlnd allocates an internal command/network
buffer of mysqlnd.net_cmd_buffer_size
(php.ini) bytes for every connection. If a
MySQL Client Server protocol command, for
example, COM_QUERY (normal query), does not
fit into the buffer, mysqlnd will grow the
buffer to what is needed for sending the
command. Whenever the buffer gets extended for
one connection command_buffer_too_small will
be incremented by one.
If mysqlnd has to grow the buffer beyond its
initial size of mysqlnd.net_cmd_buffer_size
(php.ini) bytes for almost every connection,
you should consider to increase the default
size to avoid re-allocations.
The default buffer size is 2048 bytes in PHP
Number of 5.3.0. In future versions the default will be
network 4kB or larger. The default can changed either
command through the php.ini setting
buffer mysqlnd.net_cmd_buffer_size or using
command_buffer_too_small Connection extensions mysqli_options(MYSQLI_OPT_NET_CMD_BUFFER_SIZE,
while int size).
sending
commands It is recommended to set the buffer size to no
from PHP to less than 4096 bytes because mysqlnd also uses
MySQL. it when reading certain communication packet
from MySQL. In PHP 5.3.0, mysqlnd will not
grow the buffer if MySQL sends a packet that
is larger than the current size of the buffer.
As a consequence mysqlnd is unable to decode
the packet and the client application will get
an error. There are only two situations when
the packet can be larger than the 2048 bytes
default of mysqlnd.net_cmd_buffer_size in PHP
5.3.0: the packet transports a very long error
message or the packet holds column meta data
from COM_LIST_FIELD (mysql_list_fields()) and
the meta data comes from a string column with
a very long default value (>1900 bytes). No
bug report on this exists - it should happen
rarely.
As of PHP 5.3.2 mysqlnd does not allow setting
buffers smaller than 4096 bytes.
connection_reused
----------------------------------------------------------------------
----------------------------------------------------------------------
Notes
This section provides a collection of miscellaneous notes on MySQL Native
Driver usage.
* Using mysqlnd means using PHP streams for underlying connectivity. For
mysqlnd, the PHP streams documentation (Streams) should be consulted
on such details as timeout settings, not the documentation for the
MySQL Client Library.
----------------------------------------------------------------------
----------------------------------------------------------------------
MySQL Native Driver Plugin API
Table of Contents
* A comparison of mysqlnd plugins with MySQL Proxy
* Obtaining the mysqlnd plugin API
* MySQL Native Driver Plugin Architecture
* The mysqlnd plugin API
* Getting started building a mysqlnd plugin
The MySQL Native Driver Plugin API is a feature of MySQL Native Driver, or
mysqlnd. Mysqlnd plugins operate in the layer between PHP applications and
the MySQL server. This is comparable to MySQL Proxy. MySQL Proxy operates
on a layer between any MySQL client application, for example, a PHP
application and, the MySQL server. Mysqlnd plugins can undertake typical
MySQL Proxy tasks such as load balancing, monitoring and performance
optimizations. Due to the different architecture and location, mysqlnd
plugins do not have some of MySQL Proxy's disadvantages. For example, with
plugins, there is no single point of failure, no dedicated proxy server to
deploy, and no new programming language to learn (Lua).
A mysqlnd plugin can be thought of as an extension to mysqlnd. Plugins can
intercept the majority of mysqlnd functions. The mysqlnd functions are
called by the PHP MySQL extensions such as ext/mysql, ext/mysqli, and
PDO_MYSQL. As a result, it is possible for a mysqlnd plugin to intercept
all calls made to these extensions from the client application.
Internal mysqlnd function calls can also be intercepted, or replaced.
There are no restrictions on manipulating mysqlnd internal function
tables. It is possible to set things up so that when certain mysqlnd
functions are called by the extensions that use mysqlnd, the call is
directed to the appropriate function in the mysqlnd plugin. The ability to
manipulate mysqlnd internal function tables in this way allows maximum
flexibility for plugins.
Mysqlnd plugins are in fact PHP Extensions, written in C, that use the
mysqlnd plugin API (which is built into MySQL Native Driver, mysqlnd).
Plugins can be made 100% transparent to PHP applications. No application
changes are needed because plugins operate on a different layer. The
mysqlnd plugin can be thought of as operating in a layer below mysqlnd.
The following list represents some possible applications of mysqlnd
plugins.
* Load Balancing
* Read/Write Splitting. An example of this is the PECL/mysqlnd_ms
(Master Slave) extension. This extension splits read/write
queries for a replication setup.
* Failover
* Round-Robin, least loaded
* Monitoring
* Query Logging
* Query Analysis
* Query Auditing. An example of this is the PECL/mysqlnd_sip (SQL
Injection Protection) extension. This extension inspects queries
and executes only those that are allowed according to a ruleset.
* Performance
* Caching. An example of this is the PECL/mysqlnd_qc (Query Cache)
extension.
* Throttling
* Sharding. An example of this is the PECL/mysqlnd_mc (Multi
Connect) extension. This extension will attempt to split a SELECT
statement into n-parts, using SELECT ... LIMIT part_1, SELECT
LIMIT part_n. It sends the queries to distinct MySQL servers and
merges the result at the client.
MySQL Native Driver Plugins Available
There are a number of mysqlnd plugins already available. These include:
* PECL/mysqlnd_mc - Multi Connect plugin.
* PECL/mysqlnd_ms - Master Slave plugin.
* PECL/mysqlnd_qc - Query Cache plugin.
* PECL/mysqlnd_pscache - Prepared Statement Handle Cache plugin.
* PECL/mysqlnd_sip - SQL Injection Protection plugin.
* PECL/mysqlnd_uh - User Handler plugin.
----------------------------------------------------------------------
A comparison of mysqlnd plugins with MySQL Proxy
Mysqlnd plugins and MySQL Proxy are different technologies using different
approaches. Both are valid tools for solving a variety of common tasks
such as load balancing, monitoring, and performance enhancements. An
important difference is that MySQL Proxy works with all MySQL clients,
whereas mysqlnd plugins are specific to PHP applications.
As a PHP Extension, a mysqlnd plugin gets installed on the PHP application
server, along with the rest of PHP. MySQL Proxy can either be run on the
PHP application server or can be installed on a dedicated machine to
handle multiple PHP application servers.
Deploying MySQL Proxy on the application server has two advantages:
1. No single point of failure
2. Easy to scale out (horizontal scale out, scale by client)
MySQL Proxy (and mysqlnd plugins) can solve problems easily which
otherwise would have required changes to existing applications.
However, MySQL Proxy does have some disadvantages:
* MySQL Proxy is a new component and technology to master and deploy.
* MySQL Proxy requires knowledge of the Lua scripting language.
MySQL Proxy can be customized with C and Lua programming. Lua is the
preferred scripting language of MySQL Proxy. For most PHP experts Lua is a
new language to learn. A mysqlnd plugin can be written in C. It is also
possible to write plugins in PHP using >> PECL/mysqlnd_uh.
MySQL Proxy runs as a daemon - a background process. MySQL Proxy can
recall earlier decisions, as all state can be retained. However, a mysqlnd
plugin is bound to the request-based lifecycle of PHP. MySQL Proxy can
also share one-time computed results among multiple application servers. A
mysqlnd plugin would need to store data in a persistent medium to be able
to do this. Another daemon would need to be used for this purpose, such as
Memcache. This gives MySQL Proxy an advantage in this case.
MySQL Proxy works on top of the wire protocol. With MySQL Proxy you have
to parse and reverse engineer the MySQL Client Server Protocol. Actions
are limited to those that can be achieved by manipulating the
communication protocol. If the wire protocol changes (which happens very
rarely) MySQL Proxy scripts would need to be changed as well.
Mysqlnd plugins work on top of the C API, which mirrors the libmysql
client and Connector/C APIs. This C API is basically a wrapper around the
MySQL Client Server protocol, or wire protocol, as it is sometimes called.
You can intercept all C API calls. PHP makes use of the C API, therefore
you can hook all PHP calls, without the need to program at the level of
the wire protocol.
Mysqlnd implements the wire protocol. Plugins can therefore parse, reverse
engineer, manipulate and even replace the communication protocol. However,
this is usually not required.
As plugins allow you to create implementations that use two levels (C API
and wire protocol), they have greater flexibility than MySQL Proxy. If a
mysqlnd plugin is implemented using the C API, any subsequent changes to
the wire protocol do not require changes to the plugin itself.
----------------------------------------------------------------------
----------------------------------------------------------------------
Obtaining the mysqlnd plugin API
The mysqlnd plugin API is simply part of the MySQL Native Driver PHP
extension, ext/mysqlnd. Development started on the mysqlnd plugin API in
December 2009. It is developed as part of the PHP source repository, and
as such is available to the public either via SVN, or through source
snapshot downloads.
The following table shows PHP versions and the corresponding mysqlnd
version contained within.
PHP Version MySQL Native Driver version
5.3.0 5.0.5
5.3.1 5.0.5
5.3.2 5.0.7
5.3.3 5.0.7
5.3.4 5.0.7
Plugin developers can determine the mysqlnd version through accessing
MYSQLND_VERSION, which is a string of the format "mysqlnd 5.0.7-dev -
091210 - $Revision: 300535", or through MYSQLND_VERSION_ID, which is an
integer such as 50007. Developers can calculate the version number as
follows:
Version (part) Example
Major*10000 5*10000 = 50000
Minor*100 0*100 = 0
Patch 7 = 7
MYSQLND_VERSION_ID 50007
During development, developers should refer to the mysqlnd version number
for compatibility and version tests, as several iterations of mysqlnd
could occur during the lifetime of a PHP development branch with a single
PHP version number.
----------------------------------------------------------------------
----------------------------------------------------------------------
MySQL Native Driver Plugin Architecture
This section provides an overview of the mysqlnd plugin architecture.
MySQL Native Driver Overview
Before developing mysqlnd plugins, it is useful to know a little of how
mysqlnd itself is organized. Mysqlnd consists of the following modules:
Modules Statistics mysqlnd_statistics.c
Connection mysqlnd.c
Resultset mysqlnd_result.c
Resultset Metadata mysqlnd_result_meta.c
Statement mysqlnd_ps.c
Network mysqlnd_net.c
Wire protocol mysqlnd_wireprotocol.c
C Object Oriented Paradigm
At the code level, mysqlnd uses a C pattern for implementing object
orientation.
In C you use a struct to represent an object. Members of the struct
represent object properties. Struct members pointing to functions
represent methods.
Unlike with other languages such as C++ or Java, there are no fixed rules
on inheritance in the C object oriented paradigm. However, there are some
conventions that need to be followed that will be discussed later.
The PHP Life Cycle
When considering the PHP life cycle there are two basic cycles:
* PHP engine startup and shutdown cycle
* Request cycle
When the PHP engine starts up it will call the module initialization
(MINIT) function of each registered extension. This allows each module to
setup variables and allocate resources that will exist for the lifetime of
the PHP engine process. When the PHP engine shuts down it will call the
module shutdown (MSHUTDOWN) function of each extension.
During the lifetime of the PHP engine it will receive a number of
requests. Each request constitutes another life cycle. On each request the
PHP engine will call the request initialization function of each
extension. The extension can perform any variable setup and resource
allocation required for request processing. As the request cycle ends the
engine calls the request shutdown (RSHUTDOWN) function of each extension
so the extension can perform any cleanup required.
How a plugin works
A mysqlnd plugin works by intercepting calls made to mysqlnd by extensions
that use mysqlnd. This is achieved by obtaining the mysqlnd function
table, backing it up, and replacing it by a custom function table, which
calls the functions of the plugin as required.
The following code shows how the mysqlnd function table is replaced:
/* a place to store orginal function table */
struct st_mysqlnd_conn_methods org_methods;
void minit_register_hooks(TSRMLS_D) {
/* active function table */
struct st_mysqlnd_conn_methods * current_methods
= mysqlnd_conn_get_methods();
/* backup original function table */
memcpy(&org_methods, current_methods,
sizeof(struct st_mysqlnd_conn_methods);
/* install new methods */
current_methods->query = MYSQLND_METHOD(my_conn_class, query);
}
Connection function table manipulations must be done during Module
Initialization (MINIT). The function table is a global shared resource. In
an multi-threaded environment, with a TSRM build, the manipulation of a
global shared resource during the request processing will almost certainly
result in conflicts.
Note:
Do not use any fixed-size logic when manipulating the mysqlnd function
table: new methods may be added at the end of the function table. The
function table may change at any time in the future.
Calling parent methods
If the original function table entries are backed up, it is still possible
to call the original function table entries - the parent methods.
In some cases, such as for Connection::stmt_init(), it is vital to call
the parent method prior to any other activity in the derived method.
MYSQLND_METHOD(my_conn_class, query)(MYSQLND *conn,
const char *query, unsigned int query_len TSRMLS_DC) {
php_printf("my_conn_class::query(query = %s)\n", query);
query = "SELECT 'query rewritten' FROM DUAL";
query_len = strlen(query);
return org_methods.query(conn, query, query_len); /* return with call to parent */
}
Extending properties
A mysqlnd object is represented by a C struct. It is not possible to add a
member to a C struct at run time. Users of mysqlnd objects cannot simply
add properties to the objects.
Arbitrary data (properties) can be added to a mysqlnd objects using an
appropriate function of the mysqlnd_plugin_get_plugin__data()
family. When allocating an object mysqlnd reserves space at the end of the
object to hold a void * pointer to arbitrary data. mysqlnd reserves space
for one void * pointer per plugin.
The following table shows how to calculate the position of the pointer for
a specific plugin:
Memory address Contents
0 Beginning of the mysqlnd object C struct
n End of the mysqlnd object C struct
n + (m x sizeof(void*)) void* to object data of the m-th plugin
If you plan to subclass any of the mysqlnd object constructors, which is
allowed, you must keep this in mind!
The following code shows extending properties:
/* any data we want to associate */
typedef struct my_conn_properties {
unsigned long query_counter;
} MY_CONN_PROPERTIES;
/* plugin id */
unsigned int my_plugin_id;
void minit_register_hooks(TSRMLS_D) {
/* obtain unique plugin ID */
my_plugin_id = mysqlnd_plugin_register();
/* snip - see Extending Connection: methods */
}
static MY_CONN_PROPERTIES** get_conn_properties(const MYSQLND *conn TSRMLS_DC) {
MY_CONN_PROPERTIES** props;
props = (MY_CONN_PROPERTIES**)mysqlnd_plugin_get_plugin_connection_data(
conn, my_plugin_id);
if (!props || !(*props)) {
*props = mnd_pecalloc(1, sizeof(MY_CONN_PROPERTIES), conn->persistent);
(*props)->query_counter = 0;
}
return props;
}
The plugin developer is responsible for the management of plugin data
memory.
Use of the mysqlnd memory allocator is recommended for plugin data. These
functions are named using the convention: mnd_*loc(). The mysqlnd
allocator has some useful features, such as the ability to use a debug
allocator in a non-debug build.
When and how to subclass
Each
instance
When to has its
subclass? own How to subclass?
private
function
table?
Connection (MYSQLND) MINIT No mysqlnd_conn_get_methods()
Resultset MINIT or mysqlnd_result_get_methods() or
(MYSQLND_RES) later Yes object method function table
manipulation
Resultset Meta MINIT No mysqlnd_result_metadata_get_methods()
(MYSQLND_RES_METADATA)
Statement MINIT No mysqlnd_stmt_get_methods()
(MYSQLND_STMT)
Network (MYSQLND_NET) MINIT or Yes mysqlnd_net_get_methods() or object
later method function table manipulation
Wire protocol MINIT or mysqlnd_protocol_get_methods() or
(MYSQLND_PROTOCOL) later Yes object method function table
manipulation
You must not manipulate function tables at any time later than MINIT if it
is not allowed according to the above table.
Some classes contain a pointer to the method function table. All instances
of such a class will share the same function table. To avoid chaos, in
particular in threaded environments, such function tables must only be
manipulated during MINIT.
Other classes use copies of a globally shared function table. The class
function table copy is created together with the object. Each object uses
its own function table. This gives you two options: you can manipulate the
default function table of an object at MINIT, and you can additionally
refine methods of an object without impacting other instances of the same
class.
The advantage of the shared function table approach is performance. There
is no need to copy a function table for each and every object.
Constructors
Allocation, construction, Can be Caller
reset modified?
Connection (MYSQLND) mysqlnd_init() No mysqlnd_connect()
Allocation:
* Connection::list_fields()
* Connection::result_init()
Yes, but * Statement::get_result()
Resultset(MYSQLND_RES) Reset and re-initialized call
during: parent! * Statement::prepare()
(Metadata only)
* Result::use_result()
* Statement::resultMetaData()
* Result::store_result
Resultset Meta Yes, but
(MYSQLND_RES_METADATA) Connection::result_meta_init() call Result::read_result_metadata()
parent!
Statement Yes, but
(MYSQLND_STMT) Connection::stmt_init() call Connection::stmt_init()
parent!
Network (MYSQLND_NET) mysqlnd_net_init() No Connection::init()
Wire protocol mysqlnd_protocol_init() No Connection::init()
(MYSQLND_PROTOCOL)
It is strongly recommended that you do not entirely replace a constructor.
The constructors perform memory allocations. The memory allocations are
vital for the mysqlnd plugin API and the object logic of mysqlnd. If you
do not care about warnings and insist on hooking the constructors, you
should at least call the parent constructor before doing anything in your
constructor.
Regardless of all warnings, it can be useful to subclass constructors.
Constructors are the perfect place for modifying the function tables of
objects with non-shared object tables, such as Resultset, Network, Wire
Protocol.
Destruction
Derived method must call Destructor
parent?
Connection yes, after method execution free_contents(), end_psession()
Resultset yes, after method execution free_result()
Resultset Meta yes, after method execution free()
Statement yes, after method execution dtor(), free_stmt_content()
Network yes, after method execution free()
Wire protocol yes, after method execution free()
The destructors are the appropriate place to free properties,
mysqlnd_plugin_get_plugin__data().
The listed destructors may not be equivalent to the actual mysqlnd method
freeing the object itself. However, they are the best possible place for
you to hook in and free your plugin data. As with constructors you may
replace the methods entirely but this is not recommended. If multiple
methods are listed in the above table you will need to hook all of the
listed methods and free your plugin data in whichever method is called
first by mysqlnd.
The recommended method for plugins is to simply hook the methods, free
your memory and call the parent implementation immediately following this.
Caution
Due to a bug in PHP versions 5.3.0 to 5.3.3, plugins do not associate
plugin data with a persistent connection. This is because ext/mysql and
ext/mysqli do not trigger all the necessary mysqlnd end_psession() method
calls and the plugin may therefore leak memory. This has been fixed in PHP
5.3.4.
----------------------------------------------------------------------
----------------------------------------------------------------------
The mysqlnd plugin API
The following is a list of functions provided in the mysqlnd plugin API:
* mysqlnd_plugin_register()
* mysqlnd_plugin_count()
* mysqlnd_plugin_get_plugin_connection_data()
* mysqlnd_plugin_get_plugin_result_data()
* mysqlnd_plugin_get_plugin_stmt_data()
* mysqlnd_plugin_get_plugin_net_data()
* mysqlnd_plugin_get_plugin_protocol_data()
* mysqlnd_conn_get_methods()
* mysqlnd_result_get_methods()
* mysqlnd_result_meta_get_methods()
* mysqlnd_stmt_get_methods()
* mysqlnd_net_get_methods()
* mysqlnd_protocol_get_methods()
There is no formal definition of what a plugin is and how a plugin
mechanism works.
Components often found in plugins mechanisms are:
* A plugin manager
* A plugin API
* Application services (or modules)
* Application service APIs (or module APIs)
The mysqlnd plugin concept employs these features, and additionally enjoys
an open architecture.
No Restrictions
A plugin has full access to the inner workings of mysqlnd. There are no
security limits or restrictions. Everything can be overwritten to
implement friendly or hostile algorithms. It is recommended you only
deploy plugins from a trusted source.
As discussed previously, plugins can use pointers freely. These pointers
are not restricted in any way, and can point into another plugin's data.
Simple offset arithmetic can be used to read another plugin's data.
It is recommended that you write cooperative plugins, and that you always
call the parent method. The plugins should always cooperate with mysqlnd
itself.
Issues: an example of chaining and cooperation
Extension mysqlnd.query() pointer call stack if calling parent
ext/mysqlnd mysqlnd.query() mysqlnd.query
1. mysqlnd_cache.query()
ext/mysqlnd_cache mysqlnd_cache.query()
2. mysqlnd.query
1. mysqlnd_monitor.query()
ext/mysqlnd_monitor mysqlnd_monitor.query() 2. mysqlnd_cache.query()
3. mysqlnd.query
In this scenario, a cache (ext/mysqlnd_cache) and a monitor
(ext/mysqlnd_monitor) plugin are loaded. Both subclass
Connection::query(). Plugin registration happens at MINIT using the logic
shown previously. PHP calls extensions in alphabetical order by default.
Plugins are not aware of each other and do not set extension dependencies.
By default the plugins call the parent implementation of the query method
in their derived version of the method.
PHP Extension Recap
This is a recap of what happens when using an example plugin,
ext/mysqlnd_plugin, which exposes the mysqlnd C plugin API to PHP:
* Any PHP MySQL application tries to establish a connection to
192.168.2.29
* The PHP application will either use ext/mysql, ext/mysqli or
PDO_MYSQL. All three PHP MySQL extensions use mysqlnd to establish the
connection to 192.168.2.29.
* Mysqlnd calls its connect method, which has been subclassed by
ext/mysqlnd_plugin.
* ext/mysqlnd_plugin calls the userspace hook proxy::connect()
registered by the user.
* The userspace hook changes the connection host IP from 192.168.2.29 to
127.0.0.1 and returns the connection established by parent::connect().
* ext/mysqlnd_plugin performs the equivalent of
parent::connect(127.0.0.1) by calling the original mysqlnd method for
establishing a connection.
* ext/mysqlnd establishes a connection and returns to
ext/mysqlnd_plugin. ext/mysqlnd_plugin returns as well.
* Whatever PHP MySQL extension had been used by the application, it
receives a connection to 127.0.0.1. The PHP MySQL extension itself
returns to the PHP application. The circle is closed.
----------------------------------------------------------------------
----------------------------------------------------------------------
Getting started building a mysqlnd plugin
It is important to remember that a mysqlnd plugin is itself a PHP
extension.
The following code shows the basic structure of the MINIT function that
will be used in the typical mysqlnd plugin:
/* my_php_mysqlnd_plugin.c */
static PHP_MINIT_FUNCTION(mysqlnd_plugin) {
/* globals, ini entries, resources, classes */
/* register mysqlnd plugin */
mysqlnd_plugin_id = mysqlnd_plugin_register();
conn_m = mysqlnd_get_conn_methods();
memcpy(org_conn_m, conn_m,
sizeof(struct st_mysqlnd_conn_methods));
conn_m->query = MYSQLND_METHOD(mysqlnd_plugin_conn, query);
conn_m->connect = MYSQLND_METHOD(mysqlnd_plugin_conn, connect);
}
/* my_mysqlnd_plugin.c */
enum_func_status MYSQLND_METHOD(mysqlnd_plugin_conn, query)(/* ... */) {
/* ... */
}
enum_func_status MYSQLND_METHOD(mysqlnd_plugin_conn, connect)(/* ... */) {
/* ... */
}
Task analysis: from C to userspace
class proxy extends mysqlnd_plugin_connection {
public function connect($host, ...) { .. }
}
mysqlnd_plugin_set_conn_proxy(new proxy());
Process:
1. PHP: user registers plugin callback
2. PHP: user calls any PHP MySQL API to connect to MySQL
3. C: ext/*mysql* calls mysqlnd method
4. C: mysqlnd ends up in ext/mysqlnd_plugin
5. C: ext/mysqlnd_plugin
1. Calls userspace callback
2. Or orginal mysqlnd method, if userspace callback not set
You need to carry out the following:
1. Write a class "mysqlnd_plugin_connection" in C
2. Accept and register proxy object through
"mysqlnd_plugin_set_conn_proxy()"
3. Call userspace proxy methods from C (optimization - zend_interfaces.h)
Userspace object methods can either be called using call_user_function()
or you can operate at a level closer to the Zend Engine and use
zend_call_method().
Optimization: calling methods from C using zend_call_method
The following code snippet shows the prototype for the zend_call_method
function, taken from zend_interfaces.h.
ZEND_API zval* zend_call_method(
zval **object_pp, zend_class_entry *obj_ce,
zend_function **fn_proxy, char *function_name,
int function_name_len, zval **retval_ptr_ptr,
int param_count, zval* arg1, zval* arg2 TSRMLS_DC
);
Zend API supports only two arguments. You may need more, for example:
enum_func_status (*func_mysqlnd_conn__connect)(
MYSQLND *conn, const char *host,
const char * user, const char * passwd,
unsigned int passwd_len, const char * db,
unsigned int db_len, unsigned int port,
const char * socket, unsigned int mysql_flags TSRMLS_DC
);
To get around this problem you will need to make a copy of
zend_call_method() and add a facility for additional parameters. You can
do this by creating a set of MY_ZEND_CALL_METHOD_WRAPPER macros.
Calling PHP userspace
This code snippet shows the optimized method for calling a userspace
function from C:
/* my_mysqlnd_plugin.c */
MYSQLND_METHOD(my_conn_class,connect)(
MYSQLND *conn, const char *host /* ... */ TSRMLS_DC) {
enum_func_status ret = FAIL;
zval * global_user_conn_proxy = fetch_userspace_proxy();
if (global_user_conn_proxy) {
/* call userspace proxy */
ret = MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy, host, /*...*/);
} else {
/* or original mysqlnd method = do nothing, be transparent */
ret = org_methods.connect(conn, host, user, passwd,
passwd_len, db, db_len, port,
socket, mysql_flags TSRMLS_CC);
}
return ret;
}
Calling userspace: simple arguments
/* my_mysqlnd_plugin.c */
MYSQLND_METHOD(my_conn_class,connect)(
/* ... */, const char *host, /* ...*/) {
/* ... */
if (global_user_conn_proxy) {
/* ... */
zval* zv_host;
MAKE_STD_ZVAL(zv_host);
ZVAL_STRING(zv_host, host, 1);
MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy, zv_retval, zv_host /*, ...*/);
zval_ptr_dtor(&zv_host);
/* ... */
}
/* ... */
}
Calling userspace: structs as arguments
/* my_mysqlnd_plugin.c */
MYSQLND_METHOD(my_conn_class, connect)(
MYSQLND *conn, /* ...*/) {
/* ... */
if (global_user_conn_proxy) {
/* ... */
zval* zv_conn;
ZEND_REGISTER_RESOURCE(zv_conn, (void *)conn, le_mysqlnd_plugin_conn);
MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy, zv_retval, zv_conn, zv_host /*, ...*/);
zval_ptr_dtor(&zv_conn);
/* ... */
}
/* ... */
}
The first argument of many mysqlnd methods is a C "object". For example,
the first argument of the connect() method is a pointer to MYSQLND. The
struct MYSQLND represents a mysqlnd connection object.
The mysqlnd connection object pointer can be compared to a standard I/O
file handle. Like a standard I/O file handle a mysqlnd connection object
shall be linked to the userspace using the PHP resource variable type.
From C to userspace and back
class proxy extends mysqlnd_plugin_connection {
public function connect($conn, $host, ...) {
/* "pre" hook */
printf("Connecting to host = '%s'\n", $host);
debug_print_backtrace();
return parent::connect($conn);
}
public function query($conn, $query) {
/* "post" hook */
$ret = parent::query($conn, $query);
printf("Query = '%s'\n", $query);
return $ret;
}
}
mysqlnd_plugin_set_conn_proxy(new proxy());
PHP users must be able to call the parent implementation of an overwritten
method.
As a result of subclassing it is possible to refine only selected methods
and you can choose to have "pre" or "post" hooks.
Buildin class: mysqlnd_plugin_connection::connect()
/* my_mysqlnd_plugin_classes.c */
PHP_METHOD("mysqlnd_plugin_connection", connect) {
/* ... simplified! ... */
zval* mysqlnd_rsrc;
MYSQLND* conn;
char* host; int host_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs",
&mysqlnd_rsrc, &host, &host_len) == FAILURE) {
RETURN_NULL();
}
ZEND_FETCH_RESOURCE(conn, MYSQLND* conn, &mysqlnd_rsrc, -1,
"Mysqlnd Connection", le_mysqlnd_plugin_conn);
if (PASS == org_methods.connect(conn, host, /* simplified! */ TSRMLS_CC))
RETVAL_TRUE;
else
RETVAL_FALSE;
}
----------------------------------------------------------------------
----------------------------------------------------------------------
* Introduction
* Overview
* Installation
* Runtime Configuration
* Persistent Connections
* Statistics
* Notes
* MySQL Native Driver Plugin API
* A comparison of mysqlnd plugins with MySQL Proxy
* Obtaining the mysqlnd plugin API
* MySQL Native Driver Plugin Architecture
* The mysqlnd plugin API
* Getting started building a mysqlnd plugin
----------------------------------------------------------------------
----------------------------------------------------------------------
Mysqlnd replication and load balancing plugin
----------------------------------------------------------------------
Introduction
The mysqlnd replication and load balancing plugin (mysqlnd_ms) adds easy
to use MySQL replication support to all PHP MySQL extensions that use
mysqlnd.
As of version PHP 5.3.3 the MySQL native driver for PHP (mysqlnd) features
an internal plugin C API. C plugins, such as the replication and load
balancing plugin, can extend the functionality of mysqlnd.
The MySQL native driver for PHP is a C library which ships together with
PHP as of PHP 5.3.0. It serves as a drop-in replacement for the MySQL
Client Library (AKA libmysql/libmysqlclient). Using mysqlnd has several
advantages: no extra downloads because it comes with PHP, PHP license,
lower memory consumption in certain cases, new functionality such as
asynchronous queries.
Mysqlnd plugins such as the replication and load balancing plugin operate
mostly transparent from an user perspective. The replication and load
balancing plugin supports all PHP applications and all PHP MySQL
extensions ( mysqli, mysql, PDO_MYSQL). It does not change existing APIs.
Therefore, it can easily be used with existing PHP applications.
Note:
The mysqlnd replication and load balancing plugin is in alpha status. It
is not feature complete.
Key Features
* Transparent and therefore easy to use
* supports all PHP MySQL extensions
* no API changes
* very little, if any, application changes required, dependent on
the usage scenario required
* Featured read-write split strategies
* Automatic detection of SELECT, supports SQL hints to overrule
automatism
* user-defined
* Featured load balancing strategies
* Round Robin: choose different slave in round robin fashion for
every slave request.
* Random: choose random slave for every slave request.
* Random once (sticky): choose random slave once to run all slave
requests for the duration of a web request.
* User-defined. The application can register callbacks with
mysqlnd_ms.
Limitations
The plugin does not support MySQL replication setups with more than one
master server.
The built-in read/write-split mechanism is very basic. Every query which
starts with SELECT is considered a read request to be sent to a MySQL
slave server. All other queries, including, for example, SHOW statements,
are considered as write requests to be sent to the MySQL master server.
The build-in behaviour can be overruled using SQL hints or an user-defined
callback function.
The read/write splitter is not aware of multi-statements. Multi-statements
are considered as one statement. The decision of where to run the
statement will be based on the beginning of the statement string.
The plugin does not support native prepared statements. Please note that
PDO_MySQL is using a client-side prepared statement emulation by default.
Client-side emulated prepared statements are fully supported by the
replication and load balancing plugin because the emulation is not using
native prepared statements. If you are using PHP based database
abstraction, please consult the vendor manual to learn if a client-side
prepared statement emulation is used.
Note:
Application must be aware of the consequences of connection switches
performed for load balancing purpose. Please check the documentation on
connection pooling and switching, transaction handling, failover load
balancing and read-write splitting carefully.
On the name
The shortcut mysqlnd_ms stands for mysqlnd master slave plugin. The name
was choosen for a quick-and-dirty proof-of-concept. In the beginning the
developers did not expect to continue using the code base.
----------------------------------------------------------------------
----------------------------------------------------------------------
Quickstart and Examples
Table of Contents
* Setup
* Running statements
* Connection state
* SQL Hints
* Transactions
The mysqlnd replication load balancing plugin is easy to use. The
quickstart will demo typical use-cases and give practical advice on
getting started.
It is strongly recommended to read the reference sections in addition to
the quickstart. The quickstart tries to avoid discussing theoretical
concepts and limitations. Instead, it will link to the reference sections.
It is safe to begin with the quickstart. However, before using the plugin
in mission critical environments we urge you to read additionally the
background information from the reference sections.
----------------------------------------------------------------------
Setup
The plugin is implemented as a PHP extension. Please, follow the
installation instructions to install the >> PECL/mysqlnd_ms extension.
Then, load the extension into PHP and activate the plugin in the PHP
configuration file using the PHP configuration directive named
mysqlnd_ms.enable.
The plugin is using its own configuration file. Use the PHP configuration
directive mysqlnd_ms.ini_file to set the full path to the plugin-specific
configuration file. This file must be readable by PHP.
Example #1 Enabling the plugin (php.ini)
mysqlnd_ms.enable=1
mysqlnd_ms.ini_file=/path/to/mysqlnd_ms_plugin.ini
Create a plugin-specific configuration file. Save the file to the path set
by the PHP configuration directive mysqlnd_ms.ini_file. The
plugin-specific file must be readable by PHP.
The plugins configuration file is divided into one or more sections. Each
section has a name, for example, myapp. Every section makes its own set of
configuration settings.
A section must at least list the MySQL replication master server. The
plugin supports using only one master server per section. Multi-master
MySQL replication setups are not supported. Use the configuration
directive master[] to set the hostname and the port or socket of the MySQL
master server.
Example #2 Minimal plugin-specific configuration file
(mysqlnd_ms_plugin.ini)
[myapp]
master[]=localhost:/tmp/mysql.sock
It is allowed to set no MySQL slave server but it is not recommended to
do. You should always configure at least one slave server as well. Slave
servers are set using the configuration directive slave[]. A configuration
section may contain no, one or multiple slave[] directives to set no, one
or multiple MySQL slaves.
Example #3 Recommended minimal plugin-specific config
(mysqlnd_ms_plugin.ini)
[myapp]
master[]=localhost:/tmp/mysql.sock
slave[]=192.168.2.27:3306
If there are at least two servers in total, the plugin can start to load
balance and switch connections. Switching connections is not always
transparent and can cause issues in certain cases. The reference section
on connection pooling and switching, transaction handling, fail over load
balancing and read-write splitting gives details. For now you can continue
reading the quickstart. Potential pitfalls will be described later in the
quickstart guide.
It is responsibility of the application to handle potential issues caused
by connection switches. By always configuring a master and at lease one
slave server you can be sure to detect issues early because switches
become possible.
The MySQL master and MySQL slave servers, which you configure, do not need
to be part of MySQL replication setup. For testing purpose you can use
single MySQL server and make it known to the plugin as a master and slave
server as shown below. This could help you to detect many potential issues
with connection switches. However, such a setup will not be prone to the
issues caused by replication lag.
Example #4 Using one server as a master and as a slave (testing only!)
[myapp]
master[]=localhost:/tmp/mysql.sock
slave[]=127.0.0.1:3306
----------------------------------------------------------------------
----------------------------------------------------------------------
Running statements
The plugin can be used with any PHP MySQL extension (mysqli, mysql,
PDO_MYSQL) compiled to use the mysqlnd library. PECL/mysqlnd_ms plugs into
the mysqlnd library. It does not change the PHP MySQL extensions and their
API.
Whenever a connection to MySQL is being opened, the plugin compares the
host parameter value of the connect call with the section names from the
plugin specific configuration file. If, for example, the plugin specific
configuration file has a section myapp the section should be referenced by
opening a MySQL connection to the host myapp
Example #1 Plugin specific configuration file (mysqlnd_ms_plugin.ini)
[myapp]
master[]=localhost:/tmp/mysql.sock
slave[]=192.168.2.27:3306
Example #2 Opening a load balanced connection
All of three connections opened in the example will be load balanced. The
plugin will send read-only statements to the MySQL slave server with the
IP 192.168.2.27 and listening on port 3306 for MySQL client connection.
All other statements will be directed to the MySQL master server running
on the host localhost accepting MySQL client connection on the Unix domain
socket /tmp/mysql.sock. The plugin will use the user name username and the
password password to connect to any of the MySQL servers listed in the
section myapp of the plugins configuration file. Upon connect, the plugin
will select database as the current schemata. The username, password and
schema name are taken from the connect API calls and used for all servers.
In other words: you must use the same username and password for every
MySQL server listed in a plugin configuration file section.
The plugin does not change the API for running statements. Read-write
splitting works out of the box. The following example assumes that there
is no significant replication lag between the master and the slave.
Example #3 Executing statements
query("DROP TABLE IF EXISTS test")) {
printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
if (!$mysqli->query("CREATE TABLE test(id INT)")) {
printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
if (!$mysqli->query("INSERT INTO test(id) VALUES (1)")) {
printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
/* read-only: statement will be run on a slave */
if (!($res = $mysqli->query("SELECT id FROM test")) {
printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
} else {
$row = $res->fetch_assoc();
$res->close();
printf("Slave returns id = '%s'\n", $row['id'];
}
$mysqli->close();
?>
The above example will output:
Slave returns id = '1'
Note:
The plugin does not support native prepared statements. Prepared
statements are not load balanced. Most users of PDO_MYSQL will be
unaffected by this restriction because PDO_MYSQL is using a client-side
prepared statement emulation by default.
----------------------------------------------------------------------
----------------------------------------------------------------------
Connection state
The plugin changes the semantics of a PHP MySQL connection handle. A
connection handle does no longer represent a single MySQL client-server
network connection but a connection pool. The connection pool consists of
a master connection and none, one or multiple slave connections.
Every connection from the connection pool has its own state. For example,
SQL user variables, temporary tables and transactions are part of the
state. Please, find a complete list of what belongs to the state of a
connection at the concepts page on connection pooling and switching. If
the plugin decides to switch connections for load balancing the
application could be given connection which has a different state.
Applications must be made aware of this!
Example #1 Plugin config with one slave and one master
[myapp]
master[]=localhost:/tmp/mysql.sock
slave[]=192.168.2.27:3306
Example #2 Pitfall: connection state and SQL user variables
query("SET @myrole='master'")) {
printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
/* Connection 2, run on slave because SELECT */
if (!($res = $mysqli->query("SELECT @myrole AS _role"))) {
printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
} else {
$row = $res->fetch_assoc();
$res->close();
printf("@myrole = '%s'\n", $row['_role']);
}
$mysqli->close();
?>
The above example will output:
@myrole = ''
The example openes a load balanced connection and executes two statements.
The first statement SET @myrole='master' does not begin with the string
SELECT. Therefore the plugin does not recognize it as a read-only query
which shall be run on a slave. The plugin runs the statement on the
connection to the master. The statement sets a SQL user variable which is
bound to the master connection. The state of the master connection has
been changed.
The next statement is SELECT @myrole AS _role. The plugin does recognize
it as a read-only query and sends it to the slave. The statement is run on
a connection to the slave. This second connection does not have any SQL
user variables bound to it. It has a different state than the first
connection to the master. The requested SQL user variable is not set. The
example script prints @myrole = ''.
It is the responsibility of the application developer to take care of the
connection state. The plugin does not monitor all connection state
changing activities. Monitoring all possible cases would be a very CPU
intensive task, if it could be done at all.
The pitfalls can easily be worked around using SQL hints.
----------------------------------------------------------------------
----------------------------------------------------------------------
SQL Hints
SQL hints can be used to force the plugin to pick a certain server from
the connection pool. Hinting the plugin to use a certain server can solve
issues caused by connection switches and connection state.
SQL hints are standard compliant SQL comments. Because SQL comments are
supposed to be ignored by SQL processing systems they do not infere with
other programs such as the MySQL Server, the MySQL Proxy or a firewall.
Three SQL hints are supported by the plugin: MYSQLND_MS_MASTER_SWITCH,
MYSQLND_MS_SLAVE_SWITCH and MYSQLND_MS_LAST_USED_SWITCH.
MYSQLND_MS_MASTER_SWITCH makes the plugin run a statement on the master,
MYSQLND_MS_SLAVE_SWITCH enforces the use of the slave and
MYSQLND_MS_MASTER_SWITCH will run a statement on the same server that has
been used for running the previous statement.
The plugin scans the beginning of a statement for the existance of a SQL
hint. SQL hints are only recognized if they appear at the very beginning
of the statement.
Example #1 Plugin config with one slave and one master
[myapp]
master[]=localhost:/tmp/mysql.sock
slave[]=192.168.2.27:3306
Example #2 SQL hints to prevent connection switches
query("SET @myrole='master'")) {
printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
/* Connection 1, run on master because of SQL hint */
if (!($res = $mysqli->query(sprintf("/*%s*/SELECT @myrole AS _role", MYSQLND_MS_LAST_USED_SWITCH)))) {
printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
} else {
$row = $res->fetch_assoc();
$res->close();
printf("@myrole = '%s'\n", $row['_role']);
}
$mysqli->close();
?>
The above example will output:
@myrole = 'master'
In the example the session variables issue from the previous page is
solved using MYSQLND_MS_LAST_USED_SWITCH to prevent switching from the
master to a slave when running the SELECT statement.
SQL hints can also be used to run SELECT statements on the MySQL master
server. This may be desired if the MySQL slave servers tend to be behind
the master but you need current data from the database.
Example #3 Fighting replication lag
query(sprintf("/*%s*/SELECT critical_data FROM important_table", MYSQLND_MS_MASTER_SWITCH))) {
printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
?>
use case may include the creation of tables on a slave. If no SQL hint is
given, the plugin will send CREATE and INSERT statements to the master.
Use the SQL hint MYSQLND_MS_SLAVE_SWITCH if you want to run any such
statement on a slave, for example, to build temporary reporting tables.
Example #4 Table creation on a slave
query(sprintf("/*%s*/CREATE TABLE slave_reporting(id INT)", MYSQLND_MS_SLAVE_SWITCH))) {
printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
/* Continue using this particular slave connection */
if (!$mysqli->query(sprintf("/*%s*/INSERT INTO slave_reporting(id) VALUES (1), (2), (3)", MYSQLND_MS_LAST_USED_SWITCH))) {
printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
/* Don't use MYSQLND_MS_SLAVE_SWITCH which would allow switching to another slave! */
if ($res = $mysqli->query(sprintf("/*%s*/SELECT COUNT(*) AS _num FROM slave_reporting", MYSQLND_MS_LAST_USED_SWITCH))) {
$row = $res->fetch_assoc();
$res->close();
printf("There are %d rows in the table 'slave_reporting'", $row['_num']);
} else {
printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
$mysqli->close();
?>
The SQL hint MYSQLND_MS_LAST_USED forbids switching connection and forces
the use of the previously used connection.
----------------------------------------------------------------------
----------------------------------------------------------------------
Transactions
The current version of the plugin is not transaction safe, because it is
not transaction aware. SQL transactions are units of work to be run on a
single server. The plugin does not know when the unit of work starts and
when it ends. Therefore, the plugin may decide to switch connections in
the middle of a transaction.
You must use SQL hints to work around this limitation.
Example #1 Plugin config with one slave and one master
[myapp]
master[]=localhost:/tmp/mysql.sock
slave[]=192.168.2.27:3306
Example #2 Using SQL hints for transactions
query("START TRANSACTION")) {
/* Please use better error handling in your code */
die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
/* Prevent connection switch! */
if (!$mysqli->query(sprintf("/*%s*/INSERT INTO test(id) VALUES (1)", MYSQLND_MS_LAST_USED_SWITCH)))) {
/* Please do proper ROLLBACK in your code, don't just die */
die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if ($res = $mysqli->query(sprintf("/*%s*/SELECT COUNT(*) AS _num FROM test", MYSQLND_MS_LAST_USED_SWITCH)))) {
$row = $res->fetch_assoc();
$res->close();
if ($row['_num'] > 1000) {
if (!$mysqli->query(sprintf("/*%s*/INSERT INTO events(task) VALUES ('cleanup')", MYSQLND_MS_LAST_USED_SWITCH)))) {
die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
}
} else {
die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if (!$mysqli->query(sprintf("/*%s*/UPDATE log SET last_update = NOW()", MYSQLND_MS_LAST_USED_SWITCH)))) {
die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if (!$mysqli->query(sprintf("/*%s*/COMMIT", MYSQLND_MS_LAST_USED_SWITCH)))) {
die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
$mysqli->close();
?>
Starting with PHP 5.3.99 the mysqlnd library allows the plugin to monitor
the status of the autocommit mode, if the mode is set by API calls instead
of using SQL statements such as SET AUTOCOMMIT=0. This makes it possible
for the plugin to become transaction aware.
If using PHP 5.3.99, API calls to set the autocommit mode and setting the
experimental plugin configuration option trx_stickiness=master the plugin
can automatically disable load balancing and connection switches for SQL
transactions. In this configuration the plugin stops load balancing, if
autocommit is disabled and directs all statements to the master. This is
done to prevent connection switches in the middle of a transaction. Once
autocommit gets enabled again, the plugin starts to load balance
statements again.
Example #3 Experimental trx_stickiness setting
[myapp]
master[]=localhost:/tmp/mysql.sock
slave[]=192.168.2.27:3306
trx_stickiness=master
Example #4 Outlook: transaction aware
autocommit(FALSE);
if (!$mysqli->query("INSERT INTO test(id) VALUES (1)")) {
/* Please do proper ROLLBACK in your code, don't just die */
die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if ($res = $mysqli->query("SELECT COUNT(*) AS _num FROM test")) {
$row = $res->fetch_assoc();
$res->close();
if ($row['_num'] > 1000) {
if (!$mysqli->query("INSERT INTO events(task) VALUES ('cleanup')")) {
die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
}
} else {
die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if (!$mysqli->query("UPDATE log SET last_update = NOW()")) {
die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if (!$mysqli->commit()) {
die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
/* Plugin assumes that the transaction has ended and starts load balancing again */
$mysqli->autocommit(TRUE);
$mysqli->close();
?>
Note:
The plugin configuration option trx_stickiness=master is an experimental
feature. It requires PHP 5.3.99.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Concepts
Table of Contents
* Architecture
* Connection pooling and switching
* Transaction handling
* Failover
* Load balancing
* Read-write splitting
----------------------------------------------------------------------
Architecture
The mysqlnd replication and load balancing plugin is implemented as a PHP
extension. It is written in C and operates under the hood of PHP. During
the startup of the PHP interpreter, in the module init phase of the PHP
engine, it gets registered as a mysqlnd plugin to replace selected mysqlnd
C methods.
At PHP run time it inspects queries send from mysqlnd (PHP) to the MySQL
server. If a query is recognized as read-only it will be sent to one of
the configured slave servers. Statements are considered read-only if they
either start with SELECT, the SQL hint /*ms=slave*/ or a slave had been
choose for running the previous query and the query starts with the SQL
hint /*ms=last_used*/. In all other cases the query will be sent to the
MySQL replication master server.
The plugin takes care internally of opening and closing the database
connections to the master server and the slave servers. From an
application point of view there continues to be only one connection
handle. However, internally, this one public connection handle represents
a pool of internal connections managed by the plugin. The plugin proxies
queries to the master server and the slave ones using multiple
connections.
Database connections have a state consisting, for example, transaction
status, transaction settings, character set settings, temporary tables.
The plugin will try to maintain the same state among all internal
connections, whenever this can be done in an automatic and transparent
way. In cases where it is not easily possible to maintain state among all
connections, such as when using BEGIN TRANSACTION, the plugin leaves it to
the user to handle. Please, find further details below.
----------------------------------------------------------------------
----------------------------------------------------------------------
Connection pooling and switching
The replication and load balancing plugin changes the semantics of a PHP
MySQL connection handle. The existing API of the PHP MySQL extensions
(mysqli, mysql, PDO_MYSQL) are not changed in a way that functions are
added or removed. But their behaviour changes when using the plugin.
Existing applications do not need to be adapted to a new API. But they may
need to be modified because of the behaviour changes.
The plugin breaks the one-by-one relationship between a mysqli, mysql,
PDO_MYSQL connection handle and a MySQL wire connection. If using the
plugin a mysqli, mysql, PDO_MYSQL connection handle represents a local
pool of connections to the configured MySQL replication master and the
MySQL replication slave servers. The plugin redirects queries to the
master and slave servers. At some point in time one and the same PHP
connection handle may point to the MySQL master server. Later on, it may
point to one of the slave servers or still the master. Manipulating and
replacing the wire connection referenced by a PHP MySQL connection handle
is not a transparent operation.
Every MySQL connection has a state. The state of the connections in the
connection pool of the plugin can differ. Whenever the plugin switches
from one wire connection to another, the current state of the user
connection may change. The applications must be aware of this.
The following listshows what the connection state consists of.
* Transaction status
* Temporary tables
* Table locks
* Session system variables and session user variables
* Session system variables and session user variables
* Prepared statements
* HANDLER variables
* Locks acquired with GET_LOCK()
The plugins philosophy is to align the state of connections in the pool
only if the state is under full control of the plugin, or if it is
necessary for security reasons. Just a few actions that change the state
of the connection fall into this category. The plugin does broadcast the
following state changing client calls to all currently open connections in
the connection pool: change_user, select_db, set_charset,
set_server_option, set_client_option, autocommit.
The plugin does not proxy or "remember" settings to apply them on
connections opened in the future. This is important to remember, if using
lazy connections. Lazy connections are connections which are not opened
before the client sends the first connection. Use of lazy connections is
the default plugin action.
Connection switches happen right before queries are run. The plugin does
not switch the current connection until the moment in time when the next
statement is executed.
Please, do not miss the MySQL reference manual chapter on replication
features and issues. Some restrictions you hit may not be related to the
PHP plugin but are properties of the MySQL replication system.
----------------------------------------------------------------------
----------------------------------------------------------------------
Transaction handling
Transaction handling is fundamentally changed. A SQL transaction is a unit
of work run on one database server. The unit of work consists of one or
more SQL statements.
By default the plugin is not aware of SQL transactions. The plugin may
switch connections for load balancing at any point in time. Connection
switches may happen in the middle of a transaction. This is against the
nature of a SQL transaction. By default the plugin is not transaction
safe.
At the time of writing, applications using SQL transactions together with
the plugin must use SQL hints to disable connection switches in the middle
of a SQL transaction. Please, find details in the examples section.
The latest version of the mysqlnd library, as found in PHP 5.3.99, allows
the plugin to subclass the library C API call trx_autocommit() to detect
the status of the autocommit mode. The PHP MySQL extensions either issue a
query such as SET AUTOCOMMIT=0|1 or use the mysqlnd library call
trx_autcommit() to control the autocommit setting. If an extension makes
use of trx_autocommit(), the plugin can be made transaction aware.
Transaction awareness cannot be achieved, if using SQL to set the
autocommit mode.
The experimental pluging configuration option trx_stickiness=master can be
used to make the plugin transaction aware if using PHP 5.3.99. In this
mode the plugin stops load balancing if autocommit gets disabled and
directs all statements to the master until autocommit gets enabled.
----------------------------------------------------------------------
----------------------------------------------------------------------
Failover
Connection failover handling is left to the user. The application is
responsible for checking return values of the database functions it calls
and reacting to possible errors. If, for example, the plugin recognizes a
query as a read-only query to be sent to the slave servers and the slave
server selected by the plugin is not available, the plugin will raise an
error after not executing the statement.
It is up to the application to handle the error and, if need be, re-issue
the query to trigger selection of another slave server for statement
execution. The plugin will make no attempts to failover automatically
because the plugin cannot ensure that an automatic failover will not
change the state of the connection. For example, the application may have
issued a query which depends on SQL user variables which are bound to a
specific connection. Such a query might return wrong results if the plugin
would switch the connection implicitly as part of automatic failover. To
ensure correct results the application must take care of the failover and
rebuild the required connection state. Therefore, by default, no automatic
failover is done by the plugin.
An user who does not change the connection state after opening a
connection may activate automatic master failover.
The failover policy is configured in the plugins configuration file by
help of the failover configuration directive.
----------------------------------------------------------------------
----------------------------------------------------------------------
Load balancing
Four load balancing strategies are supported to distribute read-only
statements over the configured MySQL slave servers: random, random_once
(default), roundrobin, user.
The load balancing policy is configured in the plugins configuration file
using the pick[] configuration directive.
----------------------------------------------------------------------
----------------------------------------------------------------------
Read-write splitting
The plugin runs read-only statements on the configured MySQL slaves and
all other queries on the MySQL master. Statements are considered read-only
if they either start with SELECT, the SQL hint /*ms=slave*/ or a slave had
been chosen for running the previous query and the query starts with the
SQL hint /*ms=last_used*/. In all other cases the query will be send to
the MySQL replication master server.
SQL hints are a special kind of standard compliant SQL comments. The
plugin does check every statement for certain SQL hints. The SQL hints are
described together with the constants exported by the extension. Other
systems involved in the statement processing, such as the MySQL server,
SQL firewalls or SQL proxies are unaffected by the SQL hints because those
systems are supposed to ignore SQL comments.
The built-in read-write splitter can be replaced by a user-defined one,
see also mysqlnd_ms_set_user_pick_server().
A user-defined read-write splitter can ask the built-in logic to make a
proposal where to sent a statement by invoking mysqlnd_ms_is_select().
Note:
The built-in read-write splitter is not aware of multi-statements.
Multi-statements are seen as one statement. The splitter will check the
beginning of the statement to decide where to run the statement. If, for
example, a multi-statement begins with SELECT 1 FROM DUAL; INSERT INTO
test(id) VALUES (1); ... the plugin will run it on a slave although the
statement is not read-only.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Plugin configuration file
----------------------------------------------------------------------
Requirements
PHP 5.3.6 or newer.
The mysqlnd_ms replication and load balancing plugin supports all PHP
applications and all availablePHP MySQL extensions (mysqli, mysql,
PDO_MYSQL). The PHP MySQL extension must be configured to use mysqlnd in
order to be able to use the mysqlnd_ms plugin for mysqlnd.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
Note:
The mysqlnd replication and load balancing plugin is in alpha status. It
is not feature complete.
This >> PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here:
>> http://pecl.php.net/package/mysqlnd_ms
A DLL for this PECL extension is currently unavailable. See also the
building on Windows section.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Mysqlnd_ms Configure Options
Name Default Changeable Changelog
mysqlnd_ms.enable 0 its PHP_INI_* value
mysqlnd_ms.force_config_usage 0 its PHP_INI_* value
mysqlnd_ms.ini_file its PHP_INI_* value
mysqlnd_ms.collect_statistics its PHP_INI_* value
Here's a short explanation of the configuration directives.
mysqlnd_ms.enable integer
Enables or disables the plugin. If set to disabled, the extension
will not plug into mysqlnd to proxy internal mysqlnd C API calls.
mysqlnd_ms.force_config_usage integer
If enabled the plugin checks if the host (server) parameter value
of any MySQL connection attempt matches a section name from the
plugin configuration file. If not, the connection attempt is
blocked.
mysqlnd_ms.ini_file string
Plugin specific configuration file.
mysqlnd_ms.collect_statistics integer
Enables or disables the collection of statistics. The collection
of statistics is disabled by default for performance reasons.
Statistics are returned by the function mysqlnd_ms_get_stats().
----------------------------------------------------------------------
----------------------------------------------------------------------
Plugin configuration file
The plugin is using its own configuration file. The configuration file
holds information on the MySQL replication master server, the MySQL
replication slave servers, the server pick (load balancing) policy, the
failover strategy and the use of lazy connections.
The PHP configuration directive mysqlnd_ms.ini_file is used to set the
plugins configuration file.
The configuration file minics standard php.ini format. It consists of one
or more sections. Every section defines its own unit of settings. There is
no global section for setting defaults.
Applications reference sections by their name. Applications use section
names as the host (server) parameter to the various connect methods of the
mysqli, mysql and PDO_MYSQL extensions. Upon connect the mysqlnd plugin
compares the hostname with all section names from the plugin configuration
file. If hostname and section name match, the plugin will load the
sections settings.
Example #1 Using section names example
[myapp]
master[] = localhost
slave[] = 192.168.2.27
slave[] = 192.168.2.28:3306
[localhost]
master[] = localhost:/tmp/mysql/mysql.sock
slave[] = 192.168.3.24:3305
slave[] = 192.168.3.65:3309
Section names are strings. It is valid to use a section name such as
192.168.2.1, 127.0.0.1 or localhost. If, for example, an application
connects to localhost and a plugin configuration section [localhost]
exists, the semantics of the connect operation are changed. The
application will no longer only use the MySQL server running on the host
localhost but the plugin will start to load balance MySQL queries
following the rules from the [localhost] configuration section. This way
you can load balance queries from an application without changing the
applications source code.
The master[], slave[] and pick[] configuration directives use a list-like
syntax. Configuration directives supporting list-like syntax may appear
multiple times in a configuration section. The plugin maintains the order
in which entries appear when interpreting them. For example, the below
example shows two slave[] configuration directives in the configuration
section [myapp]. If doing round-robin load balancing for read-only
queries, the plugin will send the first read-only query to the MySQL
server mysql_slave_1 because it is the first in the list. The second
read-only query will be send to the MySQL server mysql_slave_2 because it
is the second in the list. Configuration directives supporting list-like
syntax result are ordered from top to bottom in accordance to their
appearance within a configuration section.
Example #2 List-like syntax
[myapp]
master[] = mysql_master_server
slave[] = mysql_slave_1
slave[] = mysql_slave_2
Here is a short explanation of the configuration directives that can be
used.
master[] string
URI of a MySQL replication master server. The URI follows the
syntax hostname[:port|unix_domain_socket].
The plugin supports using only one master server.
Setting a master server is mandatory. The plugin will report a
warning upon connect if the user has failed to provide a master
server for a configuration section. The warning may read
(mysqlnd_ms) Cannot find master section in config. Furthermore the
plugin may set an error code for the connection handle such as
HY000/2000 (CR_UNKNOWN_ERROR). The corresponding error message
depends on your language settings.
slave[] string
URI of one or more MySQL replication slave servers. The URI
follows the syntax hostname[:port|unix_domain_socket].
The plugin supports using one or more slave servers.
Setting a slave server is mandatory. The plugin will report a
warning upon connect if the user has failed to provide at least
one slave server for a configuration section. The warning may read
(mysqlnd_ms) Cannot find slaves section in config. Furthermore the
plugin may set an error code for the connection handle such as
HY000/2000 (CR_UNKNOWN_ERROR). The corresponding error message
depends on your language settings.
pick[] string
Load balancing (server picking) policy. Supported policies:
random, random_once (default), roundrobin, user.
If no load balancing policy is set, the plugin will default to
random_once. The random_once policy picks a random slave server
when running the first read-only statement. The slave server will
be used for all read-only statements until the PHP script
execution ends.
The random policy will pick a random server whenever a read-only
statement is to be executed.
If using roundrobin the plugin iterates over the list of
configured slave servers to pick a server for statement execution.
If the plugin reaches the end of the list, it wraps around to the
beginning of the list and picks the first configured slave server.
Setting more than one load balancing policy for a configuration
section makes only sense in conjunction with user and
mysqlnd_ms_set_user_pick_server(). If the user defined callback
fails to pick a server, the plugin falls back to the second
configured load balancing policy.
failover string
Failover policy. Supported policies: disabled (default), master.
If no failover policy is set, the plugin will not do any automatic
failover (failover=disabled). Whenever the plugin fails to connect
a server it will emit a warning and set the connections error code
and message. Thereafter it is up to the application to handle the
error and, for example, resent the last statement to trigger the
selection of another server.
If using failover=master the plugin will implicitly failover to a
slave, if available. Please check the concepts documentation to
learn about potential pitfalls and risks of using failover=master.
lazy_connections bool
Controls the use of lazy connections. Lazy connections are
connections which are not opened before the client sends the first
connection.
It is strongly recommended to use lazy connections. Lazy
connections help to keep the number of open connections low. If
you disable lazy connections and, for example, configure one MySQL
replication master server and two MySQL replication slaves, the
plugin will open three connections upon the first call to a
connect function although the application might use the master
connection only.
Lazy connections bare a risk if you make heavy use of actions
which change the state of a connection. The plugin does not
dispatch all state changing actions to all connections from the
connection pool. The few dispatched actions are applied to already
opened connections only. Lazy connections opened in the future are
not affected. If, for example, the connection character set is
changed using a PHP MySQL API call, the plugin will change the
character set of all currently opened connection. It will not
remeber the character set change to apply it on lazy connections
opened in the future. As a result the internal connection pool
would hold connections using different character sets. This is not
desired. Remember that character sets are taken into account for
escaping.
master_on_write bool
If set, the plugin will use the master server only after the first
statement has been executed on the master. Applications can still
send statements to the slaves using SQL hints to overrule the
automatic decision.
The setting may help with replication lag. If an application runs
an INSERT the plugin will, by default, use the master to execute
all following statements, including SELECT statements. This helps
to avoid problems with reads from slaves which have not replicated
the INSERT yet.
trx_stickiness string
Transaction stickiness policy. Supported policies: disabled
(default), master.
Experimental feature.
The setting requires 5.3.99 or newer. If used with PHP older than
5.3.99, the plugin will emit a warning like (mysqlnd_ms)
trx_stickiness strategy is not supported before PHP 5.3.99.
If no transaction stickiness policy is set or, if setting
trx_stickiness=disabled, the plugin is not transaction aware.
Thus, the plugin may load balance connections and switch
connections in the middle of a transaction. The plugin is not
transaction safe. SQL hints must be used avoid connection switches
during a transaction.
As of PHP 5.3.99 the mysqlnd library allows the plugin to monitor
the autocommit mode set by calls to the libraries trx_autocommit()
function. If setting trx_stickiness=master and autocommit gets
disabled by a PHP MySQL extension invoking the mysqlnd library
internal function call trx_autocommit(), the plugin is made aware
of the begin of a transaction. Then, the plugin stops load
balancing and directs all statements to the master server until
autocommit is enabled. Thus, no SQL hints are required.
An example of a PHP MySQL API function calling the mysqlnd library
internal function call trx_autocommit() is mysqli_autocommit().
Although setting trx_stickiness=master, the plugin cannot be made
aware of autocommit mode changes caused by SQL statements such as
SET AUTOCOMMIT=0.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
SQL hint related
The mysqlnd replication and load balancing plugin (mysqlnd_ms) does
read/write splitting to direct write queries to a MySQL master server and
read-only queries to MySQL slave servers in a MySQL replication setup. The
plugin has a built-in read/write split logic. The logic is very basic. All
queries which start with SELECT are considered read-only queries which
shall be send to a MySQL slave server listed in the plugin configuration
file. All other queries shall be directed to the MySQL master server
specified in the plugin configuration file.
User supplied SQL hints can be used to overrule automatic read/write
splitting to gain full control on the process. SQL hints are standards
compliant SQL comments. The plugin will scan the beginning of a query
string for a SQL comment with certain contents which control query
redirection. Other systems involved in the query processing are unaffected
by the plugins SQL hints because other systems will ignore the SQL
comments.
The plugin supports three SQL hints to direct queries to the MySQL slave
servers, the MySQL master server and the last used MySQL server. SQL hints
must be placed at the beginning to be recognized by the plugin.
It is recommended to use the string constants MYSQLND_MS_MASTER_SWITCH,
MYSQLND_MS_SLAVE_SWITCH and MYSQLND_MS_LAST_USED_SWITCH instead of their
literal values for better portability.
The above examples will output:
master_query = /*ms=master*/SELECT id FROM test
slave_query = /*ms=slave*/SHOW TABLES
MYSQLND_MS_MASTER_SWITCH (string)
SQL hint used to send a query to the MySQL replication master
server.
MYSQLND_MS_SLAVE_SWITCH (string)
SQL hint used to send a query to one of the MySQL replication
slave servers.
MYSQLND_MS_LAST_USED_SWITCH (string)
SQL hint used to send a query to the last used MySQL server. The
last used MySQL server can either be a master or a slave server in
a MySQL replication setup.
mysqlnd_ms_is_select() related
MYSQLND_MS_QUERY_USE_MASTER (integer)
If mysqlnd_ms_is_select() returns MYSQLND_MS_QUERY_USE_MASTER for
a given query, the built-in read/write split mechanism recommends
sending the query to a MySQL replication master server.
MYSQLND_MS_QUERY_USE_SLAVE (integer)
If mysqlnd_ms_is_select() returns MYSQLND_MS_QUERY_USE_SLAVE for a
given query, the built-in read/write split mechanism recommends
sending the query to a MySQL replication slave server.
MYSQLND_MS_QUERY_USE_LAST_USED (integer)
If mysqlnd_ms_is_select() returns MYSQLND_MS_QUERY_USE_LAST_USED
for a given query, the built-in read/write split mechanism
recommends sending the query to the last used server.
Other
The plugins version number can be obtained using MYSQLND_MS_VERSION or
MYSQLND_MS_VERSION_ID. MYSQLND_MS_VERSION is the string representation of
the numerical version number MYSQLND_MS_VERSION_ID, which is an integer
such as 10000. Developers can calculate the version number as follows.
Version (part) Example
Major*10000 1*10000 = 10000
Minor*100 0*100 = 0
Patch 0 = 0
MYSQLND_MS_VERSION_ID 10000
MYSQLND_MS_VERSION (string)
Plugin version string, for example, "1.0.0-prototype".
MYSQLND_MS_VERSION_ID (integer)
Plugin version number, for example, 10000.
----------------------------------------------------------------------
----------------------------------------------------------------------
Mysqlnd_ms Functions
----------------------------------------------------------------------
mysqlnd_ms_get_stats
(PECL mysqlnd_ms >= 1.0.0)
mysqlnd_ms_get_stats - Returns query distribution and connection
statistics
Description
array mysqlnd_ms_get_stats ( void )
Returns an array of statistics collected by the replication and load
balancing plugin.
The PHP configuration setting mysqlnd_ms.collect_statistics controls the
collection of statistics. The collection of statistics is disabled by
default for performance reasons.
The scope of the statistics is the PHP process. Depending on your
deployment model a PHP process may handle one or multiple requests.
Statistics are aggregated for all connections. It is not possible to tell
how much queries originating from mysqli, PDO_MySQL or mysql API calls
have contributed to the aggregated data values.
Parameters
This function has no parameters.
Return Values
Returns NULL if the PHP configuration directive mysqlnd_ms.enable has
disabled the plugin. Otherwise, returns array of statistics.
Array of statistics
Statistic Description Version
Number of statements considered as
read-only by the built-in query
analyzer. Neither statements which
begin with a SQL hint to force use
use_slave of slave nor statements directed to Since
a slave by an user-defined callback 1.0.0.
are included. The total number of
statements sent to the slaves is
use_slave + use_slave_sql_hint +
use_slave_callback.
Number of statements not considered
as read-only by the built-in query
analyzer. Neither statements which
begin with a SQL hint to force use
of master nor statements directed Since
use_master to a master by an user-defined 1.0.0.
callback are included. The total
number of statements sent to the
master is use_master +
use_master_sql_hint +
use_master_callback.
Number of statements sent to a Since
use_slave_sql_hint slave because statement begins with 1.0.0.
the SQL hint to force use of slave.
Number of statements sent to a
use_master_sql_hint master because statement begins Since
with the SQL hint to force use of 1.0.0.
master.
Number of statements sent to server
which has run the previous Since
use_last_used_sql_hint statement, because statement begins 1.0.0.
with the SQL hint to force use of
previously used server.
Number of statements sent to a
use_slave_callback slave because an user-defined Since
callback has chosen a slave server 1.0.0.
for statement execution.
Number of statements sent to a
use_master_callback master because an user-defined Since
callback has chosen a master server 1.0.0.
for statement execution.
Number of successfully opened slave
connections from configurations not
using lazy connections. The total Since
non_lazy_connections_slave_success number of successfully opened slave 1.0.0.
connections is
non_lazy_connections_slave_success
+ lazy_connections_slave_success
Number of failed slave connection
attempts from configurations not
using lazy connections. The total Since
non_lazy_connections_slave_failed number of failed slave connection 1.0.0.
attempts is
non_lazy_connections_slave_failed +
lazy_connections_slave_failed
Number of successfully opened
master connections from
configurations not using lazy
non_lazy_connections_master_success connections. The total number of Since
successfully opened master 1.0.0.
connections is
non_lazy_connections_master_success
+ lazy_connections_master_success
Number of failed master connection
attempts from configurations not
using lazy connections. The total Since
non_lazy_connections_master_failed number of failed master connection 1.0.0.
attempts is
non_lazy_connections_master_failed
+ lazy_connections_master_failed
Number of successfully opened slave Since
lazy_connections_slave_success connections from configurations 1.0.0.
using lazy connections.
Number of failed slave connection Since
lazy_connections_slave_failed attempts from configurations using 1.0.0.
lazy connections.
Number of successfully opened
lazy_connections_master_success master connections from Since
configurations using lazy 1.0.0.
connections.
Number of failed master connection Since
lazy_connections_master_failed attempts from configurations using 1.0.0.
lazy connections.
Number of autocommit mode
activations via API calls. This
figure may be used to monitor
activity related to the plugin
configuration setting
trx_stickiness. If, for example,
you want to know if a certain API
trx_autocommit_on call invokes the mysqlnd library Since
function trx_autocommit(), which is 1.0.0.
a requirement for trx_stickiness,
you may call the user API function
in question and check if the
statistic has changed. The
statistic is modified only by the
plugins internal subclassed
trx_autocommit() method.
trx_autocommit_off Number of autocommit mode Since
deactivations via API calls. 1.0.0.
Number of statemens redirected to
trx_master_forced the master while Since
trx_stickiness=master and 1.0.0.
autocommit mode is disabled.
Examples
Example #1 mysqlnd_ms_get_stats() example
The above example will output:
mysqlnd_ms.collect_statistics = 0
array(13) {
["use_slave"]=>
string(1) "0"
["use_master"]=>
string(1) "0"
["use_slave_forced"]=>
string(1) "0"
["use_master_forced"]=>
string(1) "0"
["use_last_used_forced"]=>
string(1) "0"
["non_lazy_connections_slave_success"]=>
string(1) "0"
["non_lazy_connections_slave_failure"]=>
string(1) "0"
["non_lazy_connections_master_success"]=>
string(1) "0"
["non_lazy_connections_master_failure"]=>
string(1) "0"
["lazy_connections_slave_success"]=>
string(1) "0"
["lazy_connections_slave_failure"]=>
string(1) "0"
["lazy_connections_master_success"]=>
string(1) "0"
["lazy_connections_master_failure"]=>
string(1) "0"
["trx_autocommit_on"]=>
string(1) "0"
["trx_autocommit_off"]=>
string(1) "0"
["trx_master_forced"]=>
string(1) "0"
}
See Also
* Runtime configuration
* mysqlnd_ms.collect_statistics
* mysqlnd_ms.enable
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqlnd_ms_query_is_select
(PECL mysqlnd_ms >= 1.0.0)
mysqlnd_ms_query_is_select - Find whether to send the query to the master,
the slave or the last used MySQL server
Description
int mysqlnd_ms_query_is_select ( string $query )
Finds whether to send the query to the master, the slave or the last used
MySQL server.
The plugins built-in read/write split mechanism will be used to analyze
the query string to make a recommendation where to send the query. The
built-in read/write split mechanism is very basic and simple. The plugin
will recommend sending all queries to the MySQL replication master server
but those which begin with SELECT, or begin with a SQL hint which enforces
sending the query to a slave server. Due to the basic but fast algorithm
the plugin may propose to run some read-only statements such as SHOW
TABLES on the replication master.
Parameters
query
Query string to test.
Return Values
A return value of MYSQLND_MS_QUERY_USE_MASTER indicates that the query
should be send to the MySQL replication master server. The function
returns a value of MYSQLND_MS_QUERY_USE_SLAVE if the query can be run on a
slave because it is considered read-only. A value of
MYSQLND_MS_QUERY_USE_LAST_USED is returned to recommend running the query
on the last used server. This can either be a MySQL replication master
server or a MySQL replication slave server.
Examples
Example #1 mysqlnd_ms_query_is_select() example
The above example will output:
INSERT INTO test(id) VALUES (1) should be run on the master.
SELECT 1 FROM DUAL should be run on a slave.
/*ms=last_used*/SELECT 2 FROM DUAL should be run on the server that has run the previous query
See Also
* Predefined Constants
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqlnd_ms_set_user_pick_server
(PECL mysqlnd_ms >= 1.0.0)
mysqlnd_ms_set_user_pick_server - Sets a callback for user-defined
read/write splitting
Description
bool mysqlnd_ms_set_user_pick_server ( string $function )
Sets a callback for user-defined read/write splitting. The plugin will
call the callback only if pick[]=user is the default rule for server
picking in the relevant section of the plugins configuration file.
The plugins built-in read/write query split mechanism decisions can be
overwritten in two ways. The easiest way is to prepend the query string
with the SQL hints MYSQLND_MS_MASTER_SWITCH, MYSQLND_MS_SLAVE_SWITCH or
MYSQLND_MS_LAST_USED_SWITCH. Using SQL hints one can control, for example,
whether a query shall be send to the MySQL replication master server or
one of the slave servers. By help of SQL hints it is not possible to pick
a certain slave server for query execution.
Full control on server selection can be gained using a callback function.
Use of a callback is recommended to expert users only because the callback
has to cover all cases otherwise handled by the plugin.
The plugin will invoke the callback function for selecting a server from
the lists of configured master and slave servers. The callback function
inspects the query to run and picks a server for query execution by
returning the hosts URI, as found in the master and slave list.
If the lazy connections are enabled and the callback choses a slave server
for which no connection has been established so far and establishing the
connection to the slave fails, the plugin will return an error upon the
next action on the failed connection, for example, when running a query.
It is the responsibility of the application developer to handle the error.
For example, the application can re-run the query to trigger a new server
selection and callback invocation. If so, the callback must make sure to
select a different slave, or check slave availability, before returning to
the plugin to prevent an endless loop.
Parameters
function
The function to be called. Class methods may also be invoked
statically using this function by passing array($classname,
$methodname) to this parameter. Additionally class methods of an
object instance may be called by passing array($objectinstance,
$methodname) to this parameter.
Return Values
Host to run the query on. The host URI is to be taken from the master and
slave connection lists passed to the callback function. If callback
returns a value neither found in the master nor in the slave connection
lists the plugin will fallback to the second pick method configured via
the pick[] setting in the plugin configuration file. If not second pick
method is given, the plugin falls back to the build-in default pick method
for server selection.
Examples
Example #1 mysqlnd_ms_set_user_pick_server() example
[myapp]
master[] = localhost
slave[] = 192.168.2.27:3306
slave[] = 192.168.78.136:3306
pick[] = user
query("SELECT 1 FROM DUAL")))
printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
else
$res->close();
if (!($res = $mysqli->query("SELECT 2 FROM DUAL")))
printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
else
$res->close();
if (!($res = $mysqli->query("SELECT * FROM table_on_slave_a_only")))
printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
else
$res->close();
$mysqli->close();
?>
The above example will output:
User has connected to 'myapp'...
... deciding where to run 'SELECT 1 FROM DUAL'
... some read-only query for a slave
... ret = 'tcp://192.168.2.27:3306'
User has connected to 'myapp'...
... deciding where to run 'SELECT 2 FROM DUAL'
... some read-only query for a slave
... ret = 'tcp://192.168.78.136:3306'
User has connected to 'myapp'...
... deciding where to run 'SELECT * FROM table_on_slave_a_only'
... access to table available only on slave A detected
... ret = 'tcp://192.168.2.27:3306'
See Also
* mysqlnd_ms_query_is_select() - Find whether to send the query to the
master, the slave or the last used MySQL server
----------------------------------------------------------------------
Table of Contents
* mysqlnd_ms_get_stats - Returns query distribution and connection
statistics
* mysqlnd_ms_query_is_select - Find whether to send the query to the
master, the slave or the last used MySQL server
* mysqlnd_ms_set_user_pick_server - Sets a callback for user-defined
read/write splitting
----------------------------------------------------------------------
* Introduction
* Quickstart and Examples
* Setup
* Running statements
* Connection state
* SQL Hints
* Transactions
* Concepts
* Architecture
* Connection pooling and switching
* Transaction handling
* Failover
* Load balancing
* Read-write splitting
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Plugin configuration file
* Predefined Constants
* Mysqlnd_ms Functions
* mysqlnd_ms_get_stats - Returns query distribution and connection
statistics
* mysqlnd_ms_query_is_select - Find whether to send the query to
the master, the slave or the last used MySQL server
* mysqlnd_ms_set_user_pick_server - Sets a callback for
user-defined read/write splitting
----------------------------------------------------------------------
----------------------------------------------------------------------
Mysqlnd query result cache plugin
----------------------------------------------------------------------
Introduction
The mysqlnd query result cache plugin adds easy to use client-side query
caching to all PHP MySQL extensions using mysqlnd.
As of version PHP 5.3.3 the MySQL native driver for PHP ( mysqlnd)
features an internal plugin C API. C plugins, such as the query cache
plugin, can extend the functionality of mysqlnd.
The MySQL native driver for PHP is a C library which ships together with
PHP as of PHP 5.3.0. It serves as a drop-in replacement for the MySQL
Client Library (AKA libmysql/libmysqlclient). Using mysqlnd has several
advantages: no extra downloads because it comes with PHP, PHP license,
lower memory consumption in certain cases, new functionality such as
asynchronous queries.
Mysqlnd plugins such as the query cache plugin operate transparent from a
user perspective. The cache plugin supports all PHP applications and all
PHP MySQL extensions ( mysqli, mysql, PDO_MYSQL). It does not change
existing APIs.
No significant application changes are required to cache a query. The
cache has two operation modes. It will either cache all queries (not
recommended) or only those queries marked with a certain SQL hint
(recommended).
Key Features
* Transparent and therefore easy to use
* supports all PHP MySQL extensions
* no API changes
* very little application changes required
* Flexible invalidation strategy
* Time-to-Live (TTL)
* user-defined
* Storage with different scope and life-span
* Default (Hash)
* APC
* MEMCACHE
* sqlite
* user-defined
Limitations
The query cache plugin prototype will not cache unbuffered queries or
results from prepared statements. This limitation is likely to be lifted
soon.
The following popular user API calls use buffered queries which can be
cached:
* mysqli
* mysqli_query()
* mysqli_real_query() + mysqli_store_result()
* PDO_MYSQL
* PDO::query() if PDO::ATTR_EMULATE_PREPARES = 1 (default setting)
* mysql
* mysql_query()
Architecture
The query cache is implemented as a PHP extension. It is written in C and
operates under the hood of PHP. During the startup of the PHP interpreter
it gets registered as a mysqlnd plugin to replace selected mysqlnd C
methods.
At PHP run time it proxies queries send from mysqlnd (PHP) to the MySQL
server. If a query string starts with the SQL hint ( /*qc=on*/) to enable
caching of it and the query is not cached (cache miss), the query cache
plugin will record the raw wire protocol data send from MySQL to PHP to
answer the query. The query cache records the wire protocol data in its
cache and replays it, if still valid, on a cache hit.
Note that the query cache does not hold decoded result sets consisting of
zvals (C struct representing a PHP variable). It stores the raw wire data
of the MySQL client server protocol. In case of a cache hits, mysqlnd
still needs to decode the cached raw wire data into PHP variables before
passing the result to the user space. This approach has one major
advantage: simplicity. Furthermore this approach eliminates the need for
serializing data for cache storage.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
----------------------------------------------------------------------
Requirements
PHP 5.3.3 or newer.
For using APC storage handler: APC 3.1.3p1-beta or newer.
For using MEMCACHE storage handler: libmemcache 0.38 or newer.
For using sqlite storage handler: sqlite3 bundled with PHP.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
This >> PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here:
>> http://pecl.php.net/package/mysqlnd_qc
A DLL for this PECL extension is currently unavailable. See also the
building on Windows section.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
mysqlnd_qc Configure Options
Name Default Changeable Changelog
mysqlnd_qc.enable_qc 1 PHP_INI_SYSTEM
mysqlnd_qc.ttl 30 PHP_INI_ALL
mysqlnd_qc.cache_by_default 0 PHP_INI_ALL
mysqlnd_qc.cache_no_table 0 PHP_INI_ALL
mysqlnd_qc.use_request_time 0 PHP_INI_ALL
mysqlnd_qc.time_statistics 1 PHP_INI_ALL
mysqlnd_qc.collect_statistics 0 PHP_INI_ALL
mysqlnd_qc.collect_query_trace 0 PHP_INI_SYSTEM
mysqlnd_qc.query_trace_bt_depth 3 PHP_INI_SYSTEM
mysqlnd_qc.slam_defense 0 PHP_INI_SYSTEM
mysqlnd_qc.slam_defense_ttl 30 PHP_INI_SYSTEM
mysqlnd_qc.collect_normalized_query_trace 0 PHP_INI_SYSTEM
mysqlnd_qc.std_data_copy 0 PHP_INI_SYSTEM
mysqlnd_qc.apc_prefix qc_ PHP_INI_ALL
mysqlnd_qc.memc_server 127.0.0.1 PHP_INI_ALL
mysqlnd_qc.memc_port 11211 PHP_INI_ALL
mysqlnd_qc.sqlite_data_file :memory: PHP_INI_ALL
Here's a short explanation of the configuration directives.
mysqlnd_qc.enable_qc integer
Enables or disables the plugin. If disabled the extension will not
plug into mysqlnd to proxy internal mysqlnd C API calls.
mysqlnd_qc.ttl integer
Default Time-to-Live (TTL) for cache entries in seconds.
mysqlnd_qc.cache_by_default integer
Cache all queries regardless if they begin with the SQL hint that
enables caching of a query or not. Storage handler cannot overrule
the setting. It is evaluated by the core of the plugin.
mysqlnd_qc.cache_no_table integer
Cache queries with no table name in any of columns meta data of
their result set, e.g. SELECT SLEEP(1)?
mysqlnd_qc.use_request_time integer
Use PHP global request time to avoid gettimeofday() system calls?
If using APC storage handler it should be set to the value of
apc.use_request_time , if not warnings will be generated.
mysqlnd_qc.time_statistics integer
Collect run time and store time statistics using gettimeofday()
system call? Data will be collected only if you also set
mysqlnd_qc.collect_statistics = 1,
mysqlnd_qc.collect_statistics integer
Collect statistics for mysqlnd_qc_get_core_stats()? Does not
influence storage handler statistics! Handler statistics can be an
integral part of the handler internal storage format. Thereofore,
collection of some handler statistics cannot be disabled.
mysqlnd_qc.collect_query_trace integer
Collect query back traces?
mysqlnd_qc.query_trace_bt_depth integer
Maximum depth/level of a query code backtrace.
mysqlnd_qc.slam_defense integer
Activates handler based slam defense if available. Supported by
Default and APC storage handler
mysqlnd_qc.slam_defense_ttl integer
TTL for stale cache entries which are served while another client
updates the entries. Supported by APC storage handler.
mysqlnd_qc.collect_normalized_query_trace integer
Collect aggregated normalized query traces? The setting has no
effect by default. You compile the extension using the define
NORM_QUERY_TRACE_LOG to make use of the setting.
mysqlnd_qc.std_data_copy integer
Default storage handler: copy cached wire data? EXPERIMENTAL - use
default setting!
mysqlnd_qc.apc_prefix string
The APC storage handler stores data in the APC user cache. The
setting sets a prefix to be used for cache entries.
mysqlnd_qc.memc_server string
MEMCACHE storage handler: memcache server host.
mysqlnd_qc.memc_port integer
MEMCACHE storage handler: memcached server port.
mysqlnd_qc.sqlite_data_file string
sqlite storage handler: data file. Any setting but :memory: may be
of little practical value.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
SQL hint related
The query cache is controled by SQL hints. SQL hints are used to enable
and disable caching. SQL hints can be used to set the TTL of a query.
The SQL hints recognized by the query cache can be manually changed at
compile time. This makes it possible to use mysqlnd_qc in environments in
which the default SQL hints are already taken and interpreted by other
systems. Therefore it is recommended to use the SQL hint string constants
instead of manually adding the default SQL hints to the query string.
The above examples will output:
MYSQLND_QC_ENABLE_SWITCH: qc=on
MYSQLND_QC_DISABLE_SWITCH: qc=off
MYSQLND_QC_TTL_SWITCH: qc_ttl=
MYSQLND_QC_ENABLE_SWITCH ( string)
SQL hint used to enable caching of a query.
MYSQLND_QC_DISABLE_SWITCH ( string)
SQL hint used to disable caching of a query if
mysqlnd_qc.cache_by_default = 1.
MYSQLND_QC_TTL_SWITCH ( string)
SQL hint used to set the TTL of a result set.
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Table of Contents
* Basic usage
* Setting the TTL
* Cache by default
* Procedural user-defined storage handler
----------------------------------------------------------------------
Basic usage
The Query Cache plugin supports caching of queries issued by the following
user API calls:
* mysqli
* mysqli_query()
* mysqli_real_query() + mysqli_store_result()
* PDO_MYSQL
* PDO::query() if PDO::ATTR_EMULATE_PREPARES = 1 (default setting)
* mysql
* mysql_query()
A query which shall be cached must begin with the SQL hint /*qc=on*/. It
is recommended to use the PHP constant MYSQLND_QC_ENABLE_SWITCH instead of
using the string value.
* uncached: SELECT id FROM test
* cached: /*qc=on*/SELECT id FROM test
Example using the most advanced PHP MySQL API, which is mysqli :
query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");
/* Will be cached because of the SQL hint: cache put and cache_miss */
$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();
/* Will NOT be cached and will NOT hit the cache: no SQL hint */
$res = $mysqli->query("SELECT id FROM test WHERE id = 2");
var_dump($res->fetch_assoc());
$res->free();
/* Display cache statistics */
$stats = mysqlnd_qc_get_core_stats();
printf("Cache hit\t: %d\n", $stats['cache_hit']);
printf("Cache miss\t: %d\n", $stats['cache_miss']);
printf("Cache put\t: %d\n", $stats['cache_put']);
?>
The above examples will output:
array(1) {
["id"]=>
string(1) "1"
}
array(1) {
["id"]=>
string(1) "2"
}
Cache hit : 0
Cache miss : 1
Cache put : 1
The default invalidation strategy of the cache is Time-to-Live ( TTL).
Cache entries are valid for a certain duration. The default duration is
set by the PHP configuration directive mysqlnd_qc.tll
----------------------------------------------------------------------
----------------------------------------------------------------------
Setting the TTL
The default invalidation strategy of the query cache plugin is
Time-to-Live ( TTL). The built-in storage handler will use the default TTL
defined by the PHP configuration value mysqlnd_qc.ttl unless the query
string contains a hint for setting a different TTL. The TTL is specified
in seconds.
Any TTL based cache can serve stale data. Cache entries are not
automatically invalidated, if underlying data changes.
User-defined cache storage handler can implement any invalidation strategy
to work around this limitation.
query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");
printf("Default TTL\t: %d seconds\n", ini_get("mysqlnd_qc.ttl"));
/* Will be cached because of the SQL hint */
$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();
$mysqli->query("DELETE FROM test WHERE id = 1");
/* Cache hit - no automatic invalidation! */
$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();
sleep(ini_get("mysqlnd_qc.ttl"));
/* Cache miss - cache entry has expired */
$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();
?>
The above examples will output:
Default TTL: : 30 seconds
array(1) {
["id"]=>
string(1) "1"
}
array(1) {
["id"]=>
string(1) "1"
}
NULL
The default TTL can be overruled using the SQL hint /*qc_tt=seconds*/. The
SQL hint must be appear immediately after the SQL hint which enables
caching. It is recommended to use the PHP constant MYSQLND_QC_TTL_SWITCH
instead of using the string value.
query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");
printf("Default TTL\t: %d seconds\n", ini_get("mysqlnd_qc.ttl"));
/* Will be cached for 2 seconds */
$sql = sprintf("/*%s*//*%s%d*/SELECT id FROM test WHERE id = 1",
MYSQLND_QC_ENABLE_SWITCH,
MYSQLND_QC_TTL_SWITCH,
2);
$res = $mysqli->query($sql);
var_dump($res->fetch_assoc());
$res->free();
$mysqli->query("DELETE FROM test WHERE id = 1");
sleep(1);
/* Cache hit - no automatic invalidation and still valid! */
$res = $mysqli->query($sql);
var_dump($res->fetch_assoc());
$res->free();
sleep(2);
/* Cache miss - cache entry has expired */
$res = $mysqli->query($sql);
var_dump($res->fetch_assoc());
$res->free();
printf("Script runtime\t: %d seconds\n", microtime(true) - $start);
?>
The above examples will output:
Default TTL : 30 seconds
array(1) {
["id"]=>
string(1) "1"
}
array(1) {
["id"]=>
string(1) "1"
}
NULL
Script runtime : 3 seconds
----------------------------------------------------------------------
----------------------------------------------------------------------
Cache by default
The query cache plugin will cache all queries regardless if the query
string begins with the SQL hint which enables caching or not, if the PHP
configuration directive mysqlnd_qc.cache_by_default is set to 1. The
setting mysqlnd_qc.cache_by_default is evaluated by the core of the query
cache plugins. Neither the built-in nor user-defined storage handler can
overrule the setting.
The SQL hint /*qc=off*/ can be used to disable caching of individual
queries if mysqlnd_qc.cache_by_default = 1 It is recommended to use the
PHP constant MYSQLND_QC_DISABLE_SWITCH instead of using the string value.
query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");
/* Will be cached although no SQL hint is present because of mysqlnd_qc.cache_by_default = 1*/
$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();
$mysqli->query("DELETE FROM test WHERE id = 1");
/* Cache hit - no automatic invalidation and still valid! */
$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();
/* Cache miss - query must not be cached or served from cache because of the SQL hint */
$res = $mysqli->query("/*" . MYSQLND_QC_DISABLE_SWITCH . "*/SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();
?>
The above examples will output:
array(1) {
["id"]=>
string(1) "1"
}
array(1) {
["id"]=>
string(1) "1"
}
NULL
----------------------------------------------------------------------
----------------------------------------------------------------------
Procedural user-defined storage handler
The query cache plugin supports the use of user-defined storage handler.
User-defined storage handler can use arbitrarily complex invalidation
algorithms and support arbitrary storage media.
All user-defined storage handlers have to provide a certain interface. The
functions of the user-defined storage handler will be called by the core
of the cache plugin. The necessary interface consists of seven public
functions. Both procedural and object oriented user-defined storage
handler must implement the same set of functions.
Please check the example for details.
$data,
"row_count" => $row_count,
"valid_until" => time() + $ttl,
"hits" => 0,
"run_time" => $run_time,
"store_time" => $store_time,
"cached_run_times" => array(),
"cached_store_times" => array(),
);
return TRUE;
}
function query_is_select($query) {
printf("\t%s('%s'): ", __FUNCTION__, $query);
$ret = FALSE;
if (stristr($query, "SELECT") !== FALSE) {
/* cache for 5 seconds */
$ret = 5;
}
printf("%s\n", (FALSE === $ret) ? "FALSE" : $ret);
return $ret;
}
function update_query_run_time_stats($key, $run_time, $store_time) {
global $__cache;
printf("\t%s(%d)\n", __FUNCTION__, func_num_args());
if (isset($__cache[$key])) {
$__cache[$key]['hits']++;
$__cache[$key]["cached_run_times"][] = $run_time;
$__cache[$key]["cached_store_times"][] = $store_time;
}
}
function get_stats($key = NULL) {
global $__cache;
printf("\t%s(%d)\n", __FUNCTION__, func_num_args());
if ($key && isset($__cache[$key])) {
$stats = $__cache[$key];
} else {
$stats = array();
foreach ($__cache as $key => $details) {
$stats[$key] = array(
'hits' => $details['hits'],
'bytes' => strlen($details['data']),
'uncached_run_time' => $details['run_time'],
'cached_run_time' => (count($details['cached_run_times']))
? array_sum($details['cached_run_times']) / count($details['cached_run_times'])
: 0,
);
}
}
return $stats;
}
function clear_cache() {
global $__cache;
printf("\t%s(%d)\n", __FUNCTION__, func_num_args());
$__cache = array();
return TRUE;
}
/* Install procedural user-defined storage handler */
if (!mysqlnd_qc_set_user_handlers("get_hash", "find_query_in_cache",
"return_to_cache", "add_query_to_cache_if_not_exists",
"query_is_select", "update_query_run_time_stats",
"get_stats", "clear_cache")) {
printf("Failed to install user-defined storage handler\n");
}
/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");
printf("\nCache put/cache miss\n");
$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();
/* Delete record to verify we get our data from the cache */
$mysqli->query("DELETE FROM test WHERE id = 1");
printf("\nCache hit\n");
$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();
printf("\nDisplay cache statistics\n");
var_dump(mysqlnd_qc_get_cache_info());
printf("\nFlushing cache, cache put/cache miss");
var_dump(mysqlnd_qc_clear_cache());
$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();
?>
The above examples will output:
query_is_select('DROP TABLE IF EXISTS test'): FALSE
query_is_select('CREATE TABLE test(id INT)'): FALSE
query_is_select('INSERT INTO test(id) VALUES (1), (2)'): FALSE
Cache put/cache miss
query_is_select('SELECT id FROM test WHERE id = 1'): 5
get_hash(5)
find_query_in_cache(1)
add_query_to_cache_if_not_exists(6)
array(1) {
["id"]=>
string(1) "1"
}
query_is_select('DELETE FROM test WHERE id = 1'): FALSE
Cache hit
query_is_select('SELECT id FROM test WHERE id = 1'): 5
get_hash(5)
find_query_in_cache(1)
return_to_cache(1)
update_query_run_time_stats(3)
array(1) {
["id"]=>
string(1) "1"
}
Display cache statistics
get_stats(0)
array(4) {
["num_entries"]=>
int(1)
["handler"]=>
string(4) "user"
["handler_version"]=>
string(5) "1.0.0"
["data"]=>
array(1) {
["18683c177dc89bb352b29965d112fdaa"]=>
array(4) {
["hits"]=>
int(1)
["bytes"]=>
int(71)
["uncached_run_time"]=>
int(398)
["cached_run_time"]=>
int(4)
}
}
}
Flushing cache, cache put/cache miss clear_cache(0)
bool(true)
query_is_select('SELECT id FROM test WHERE id = 1'): 5
get_hash(5)
find_query_in_cache(1)
add_query_to_cache_if_not_exists(6)
NULL
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqlnd_qc Functions
----------------------------------------------------------------------
mysqlnd_qc_change_handler
(No version information available, might only be in SVN)
mysqlnd_qc_change_handler - Change current storage handler
Description
bool mysqlnd_qc_change_handler ( mixed $handler )
Sets the storage handler used by the query cache. A list of available
storage handler can be obtained from mysqlnd_qc_get_handler(). Which
storage are available depends on the compile time configuration of the
query cache plugin. The default storage handler is always available. All
other storage handler must be enabled explicitly when building the
extension.
Parameters
handler
Handler can be of type string representing the name of a built-in
storage handler or an object of type mysqlnd_qc_handler_default.
The names of the built-in storage handler are default, APC,
MEMCACHE, sqlite.
Return Values
Returns TRUE on success or FALSE on failure.
If changing the storage handler fails a catchable fatal error will be
thrown. The query cache cannot operate if the previous storage handler has
been shutdown but no new storage handler has been installed.
Examples
The example shows the output from the built-in default storage handler.
Other storage handler may report different data.
The above examples will output:
bool(true)
Default storage handler activated
Catchable fatal error: mysqlnd_qc_change_handler(): Unknown handler 'unknown' in (file) on line (line)
See Also
* Installation
* mysqlnd_qc_get_handler() - Returns a list of available storage handler
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqlnd_qc_clear_cache
(No version information available, might only be in SVN)
mysqlnd_qc_clear_cache - Flush all cache contents
Description
bool mysqlnd_qc_clear_cache ( void )
Flush all cache contents.
Flushing the cache is a storage handler responsibility. All built-in
storage handler but the memcache storage handler support flushing the
cache. The memcache storage handler cannot flush its cache contents.
User-defined storage handler may or may not support the operation.
Parameters
This function has no parameters.
Return Values
Returns TRUE on success or FALSE on failure.
A return value of FALSE indicates that flushing all cache contents has
failed or the operation is not supported by the active storage handler.
Applications must not expect that calling the function will always flush
the cache.
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqlnd_qc_get_cache_info
(No version information available, might only be in SVN)
mysqlnd_qc_get_cache_info - Returns information on the current handler,
the number of cache entries and cache entries, if available
Description
array mysqlnd_qc_get_cache_info ( void )
Parameters
This function has no parameters.
Return Values
Returns information on the current handler, the number of cache entries
and cache entries, if available. If and what data will be returned for the
cache entries is subject to the active storage handler. Storage handler
are free to return any data. Storage handler are recommended to return at
least the data provided by the default handler, if technically possible.
Examples
The example shows the output from the built-in default storage handler.
Other storage handler may report different data.
query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/SELECT id FROM test");
/* Display cache information */
var_dump(mysqlnd_qc_get_cache_info());
?>
The above examples will output:
array(4) {
["num_entries"]=>
int(1)
["handler"]=>
string(7) "default"
["handler_version"]=>
string(5) "1.0.0"
["data"]=>
array(1) {
["Localhost via UNIX socket 3306 user schema|/*qc=on*/SELECT id FROM test"]=>
array(2) {
["statistics"]=>
array(11) {
["rows"]=>
int(6)
["stored_size"]=>
int(101)
["cache_hits"]=>
int(0)
["run_time"]=>
int(471)
["store_time"]=>
int(27)
["min_run_time"]=>
int(0)
["max_run_time"]=>
int(0)
["min_store_time"]=>
int(0)
["max_store_time"]=>
int(0)
["avg_run_time"]=>
int(0)
["avg_store_time"]=>
int(0)
}
["metadata"]=>
array(1) {
[0]=>
array(8) {
["name"]=>
string(2) "id"
["orig_name"]=>
string(2) "id"
["table"]=>
string(4) "test"
["orig_table"]=>
string(4) "test"
["db"]=>
string(4) "schema"
["max_length"]=>
int(1)
["length"]=>
int(11)
["type"]=>
int(3)
}
}
}
}
}
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqlnd_qc_get_core_stats
(No version information available, might only be in SVN)
mysqlnd_qc_get_core_stats - Statistics collected by the core of the query
cache
Description
array mysqlnd_qc_get_core_stats ( void )
Returns an array of statistics collected by the core of the cache plugin.
The same data fields will be reported for any storage handler because the
data is collected by the core.
The PHP configuration setting mysqlnd_qc.collect_statistics controls the
collection of statistics. The collection of statistics is disabled by
default for performance reasons. Disabling the collection of statistics
will also disable the collection of time related statistics.
The PHP configuration setting mysqlnd_qc.collect_time_statistics controls
the collection of time related statistics.
The scope of the core statistics is the PHP process. Depending on your
deployment model a PHP process may handle one or multiple requests.
Statistics are aggregated for all cache entries. It is not possible to
tell how much queries originating from mysqli, PDO_MySQL or mysql API
calls have contributed to the aggregated data values.
Parameters
This function has no parameters.
Return Values
Array of core statistics
Statistic Description Version
Statement is considered cacheable
and cached data has been reused.
Statement is considered cacheable
cache_hit and a cache miss happened but the Since
statement got cached by someone 1.0.0.
else while we process it and thus
we can fetch the result from the
refreshed cache.
Statement is considered
cacheable...
* ... and has been added to the
cache
* ... but the PHP configuration
directive setting of Since
cache_miss mysqlnd_qc.cache_no_table = 1 1.0.0.
has prevented caching.
* ... but an unbuffered result
set is requested.
* ... but a buffered result set
was empty.
Statement is considered cacheable
and has been added to the cache.
Take care when calculating derived
statistics. Storage handler with a
storage life time beyond process
scope may report cache_put = 0 Since
cache_put together with cache_hit > 0, if 1.0.0.
another process has filled the
cache. You may want to use
num_entries from
mysqlnd_qc_get_cache_info() if the
handler supports it ( default,
APC).
Statement is considered cacheable
based on query string analysis. Since
query_should_cache The statement may or may not be 1.0.0.
added to the cache. See also
cache_put.
Statement is considered not Since
query_should_not_cache cacheable based on query string 1.0.0.
analysis.
Statement is considered not
cacheable or it is considered Since
query_not_cached cachable but the storage handler 1.0.0.
has not returned a hash key for
it.
Statement is considered
cacheable...
* ... and statement has been run
without errors
* ... and meta data shows at Since
query_could_cache least one column in the result 1.0.0.
set
The statement may or may not be in
the cache already. It may or may
not be added to the cache later
on.
Statement is considered cacheable
and we have found it in the cache
but we have not replayed the
cached data yet and we have not Since
query_found_in_cache send the result set to the client 1.0.0.
yet. This is not considered a
cache hit because the client might
not fetch the result or the cached
data may be faulty.
Statement is considered cacheable
and it may or may not be in the
query_uncached_other cache already but either replaying
cached data has failed, no result
set is available or some other
error has happened.
Statement has not been cached
because the result set has at
least one column which has no
table name in its meta data. An
example of such a query is SELECT
SLEEP(1). To cache those Since
query_uncached_no_table statements you have to change 1.0.0.
default value of the PHP
configuration directive
mysqlnd_qc.cache_no_table and set
mysqlnd_qc.cache_no_table = 1.
Often, it is not desired to cache
such statements.
Statement would have been cached
if a buffered result set had been
query_uncached_use_result used. The situation is also Since
consiered as a cache miss and 1.0.0.
cache_miss will be incremented as
well.
Aggregated run time (ms) of all
query_aggr_run_time_cache_hit cached queries. Cached queries are Since
those which have incremented 1.0.0.
cache_hit.
Aggregated run time (ms) of all
query_aggr_run_time_cache_put uncached queries that have been Since
put into the cache. See also 1.0.0.
cache_put.
Aggregated run time (ms) of all
query_aggr_run_time_total uncached and cached queries that Since
have been inspected and executed 1.0.0.
by the query cache.
Aggregated store time (ms) of all
query_aggr_store_time_cache_hit cached queries. Cached queries are Since
those which have incremented 1.0.0.
cache_hit.
Aggregated store time ( ms) of all
query_aggr_store_time_cache_put uncached queries that have been Since
put into the cache. See also 1.0.0.
cache_put.
Aggregated store time (ms) of all
query_aggr_store_time_total uncached and cached queries that Since
have been inspected and executed 1.0.0.
by the query cache.
Recorded incoming network traffic
( bytes) send from MySQL to PHP.
The traffic may or may not have Since
receive_bytes_recorded been added to the cache. The 1.0.0.
traffic is the total for all
queries regardless if cached or
not.
Network traffic replayed during
cache. This is the total amount of Since
receive_bytes_replayed incoming traffic saved because of 1.0.0.
the usage of the query cache
plugin.
Recorded outgoing network traffic
( bytes) send from MySQL to PHP.
The traffic may or may not have Since
send_bytes_recorded been added to the cache. The 1.0.0.
traffic is the total for all
queries regardless if cached or
not.
Network traffic replayed during
cache. This is the total amount of Since
send_bytes_replayed outgoing traffic saved because of 1.0.0.
the usage of the query cache
plugin.
Number of cache misses which
slam_stale_refresh triggered serving stale data until Since
the client causing the cache miss 1.0.0.
has refreshed the cache entry.
slam_stale_hit Number of cache hits while a stale Since
cache entry gets refreshed. 1.0.0.
Examples
query("/*qc=on*/SELECT id FROM test");
/* Cache hit */
$mysqli->query("/*qc=on*/SELECT id FROM test");
/* Display core statstics */
var_dump(mysqlnd_qc_get_core_stats());
?>
The above examples will output:
array(26) {
["cache_hit"]=>
string(1) "1"
["cache_miss"]=>
string(1) "1"
["cache_put"]=>
string(1) "1"
["query_should_cache"]=>
string(1) "2"
["query_should_not_cache"]=>
string(1) "0"
["query_not_cached"]=>
string(1) "0"
["query_could_cache"]=>
string(1) "2"
["query_found_in_cache"]=>
string(1) "1"
["query_uncached_other"]=>
string(1) "0"
["query_uncached_no_table"]=>
string(1) "0"
["query_uncached_no_result"]=>
string(1) "0"
["query_uncached_use_result"]=>
string(1) "0"
["query_aggr_run_time_cache_hit"]=>
string(1) "4"
["query_aggr_run_time_cache_put"]=>
string(3) "395"
["query_aggr_run_time_total"]=>
string(3) "399"
["query_aggr_store_time_cache_hit"]=>
string(1) "2"
["query_aggr_store_time_cache_put"]=>
string(1) "8"
["query_aggr_store_time_total"]=>
string(2) "10"
["receive_bytes_recorded"]=>
string(2) "65"
["receive_bytes_replayed"]=>
string(2) "65"
["send_bytes_recorded"]=>
string(2) "29"
["send_bytes_replayed"]=>
string(2) "29"
["slam_stale_refresh"]=>
string(1) "0"
["slam_stale_hit"]=>
string(1) "0"
["request_counter"]=>
int(1)
["process_hash"]=>
int(3547549858)
}
See Also
* Runtime configuration
* mysqlnd_qc.collect_statistics
* mysqlnd_qc.time_statistics
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqlnd_qc_get_handler
(No version information available, might only be in SVN)
mysqlnd_qc_get_handler - Returns a list of available storage handler
Description
array mysqlnd_qc_get_handler ( void )
Which storage are available depends on the compile time configuration of
the query cache plugin. The default storage handler is always available.
All other storage handler must be enabled explicitly when building the
extension.
Parameters
This function has no parameters.
Return Values
Returns an array of available built-in storage handler. For each storage
handler the version number and version string is given.
Examples
The above examples will output:
array(5) {
["default"]=>
array(2) {
["version"]=>
string(5) "1.0.0"
["version_number"]=>
int(100000)
}
["user"]=>
array(2) {
["version"]=>
string(5) "1.0.0"
["version_number"]=>
int(100000)
}
["APC"]=>
array(2) {
["version"]=>
string(5) "1.0.0"
["version_number"]=>
int(100000)
}
["MEMCACHE"]=>
array(2) {
["version"]=>
string(5) "1.0.0"
["version_number"]=>
int(100000)
}
["sqlite"]=>
array(2) {
["version"]=>
string(5) "1.0.0"
["version_number"]=>
int(100000)
}
}
See Also
* Installation
* mysqlnd_qc_change_handler() - Change current storage handler
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqlnd_qc_get_query_trace_log
(No version information available, might only be in SVN)
mysqlnd_qc_get_query_trace_log - Returns a backtrace for each query
inspected by the query cache
Description
array mysqlnd_qc_get_query_trace_log ( void )
Returns a backtrace for each query inspected by the query cache. The
collection of the backtrace is disabled by default. To collect the
backtrace you have to set the PHP configuration directive
mysqlnd_qc.collect_query_trace to 1
The maximum depth of the backtrace is limited to the depth set with the
PHP configuration directive mysqlnd_qc.query_trace_bt_depth.
Parameters
This function has no parameters.
Return Values
An array of query backtrace. Every list entry contains the query string, a
backtrace and further detail information.
Key Description
query Query string.
origin Code backtrace.
Query run time in milliseconds. The collection of all
run_time times and the necessary gettimeofday system calls can
be disabled by setting the PHP configuration
directive mysqlnd_qc.time_statistics to 0
Query result set store time in milliseconds. The
collection of all times and the necessary
store_time gettimeofday system calls can be disabled by setting
the PHP configuration directive
mysqlnd_qc.time_statistics to 0
eligible_for_caching TRUE if query is cacheble otherwise FALSE.
TRUE if the query has generated a result set and at
least one column from the result set has no table
name set in its metadata. This is usually the case
no_table with queries which one probably do not want to cache
such as SELECT SLEEP(1). By default any such query
will not be added to the cache. See also PHP
configuration directive mysqlnd_qc.cache_no_table.
was_added TRUE if the query result has been put into the cache,
otherwise FALSE.
TRUE if the query result would have been added to the
was_already_in_cache cache if it was not already in the cache (cache hit).
Otherwise FALSE.
Examples
query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");
$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();
$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 2");
var_dump($res->fetch_assoc());
$res->free();
$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 2");
var_dump($res->fetch_assoc());
$res->free();
?>
The above examples will output:
array(1) {
["id"]=>
string(1) "1"
}
array(1) {
["id"]=>
string(1) "2"
}
array(1) {
["id"]=>
string(1) "2"
}
array(6) {
[0]=>
array(8) {
["query"]=>
string(25) "DROP TABLE IF EXISTS test"
["origin"]=>
string(85) "#0 /home/nixnutz/php/phpdoc/foo.php(7): mysqli->query('DROP TABLE IF E...')
#1 {main}"
["run_time"]=>
int(0)
["store_time"]=>
int(0)
["eligible_for_caching"]=>
bool(false)
["no_table"]=>
bool(false)
["was_added"]=>
bool(false)
["was_already_in_cache"]=>
bool(false)
}
[1]=>
array(8) {
["query"]=>
string(25) "CREATE TABLE test(id INT)"
["origin"]=>
string(85) "#0 /home/nixnutz/php/phpdoc/foo.php(8): mysqli->query('CREATE TABLE te...')
#1 {main}"
["run_time"]=>
int(0)
["store_time"]=>
int(0)
["eligible_for_caching"]=>
bool(false)
["no_table"]=>
bool(false)
["was_added"]=>
bool(false)
["was_already_in_cache"]=>
bool(false)
}
[2]=>
array(8) {
["query"]=>
string(36) "INSERT INTO test(id) VALUES (1), (2)"
["origin"]=>
string(85) "#0 /home/nixnutz/php/phpdoc/foo.php(9): mysqli->query('INSERT INTO tes...')
#1 {main}"
["run_time"]=>
int(0)
["store_time"]=>
int(0)
["eligible_for_caching"]=>
bool(false)
["no_table"]=>
bool(false)
["was_added"]=>
bool(false)
["was_already_in_cache"]=>
bool(false)
}
[3]=>
array(8) {
["query"]=>
string(32) "SELECT id FROM test WHERE id = 1"
["origin"]=>
string(86) "#0 /home/nixnutz/php/phpdoc/foo.php(11): mysqli->query('SELECT id FROM ...')
#1 {main}"
["run_time"]=>
int(0)
["store_time"]=>
int(15)
["eligible_for_caching"]=>
bool(false)
["no_table"]=>
bool(false)
["was_added"]=>
bool(false)
["was_already_in_cache"]=>
bool(false)
}
[4]=>
array(8) {
["query"]=>
string(41) "/*qc=on*/SELECT id FROM test WHERE id = 2"
["origin"]=>
string(86) "#0 /home/nixnutz/php/phpdoc/foo.php(15): mysqli->query('/*qc=on*/SELECT...')
#1 {main}"
["run_time"]=>
int(340)
["store_time"]=>
int(3)
["eligible_for_caching"]=>
bool(true)
["no_table"]=>
bool(false)
["was_added"]=>
bool(true)
["was_already_in_cache"]=>
bool(false)
}
[5]=>
array(8) {
["query"]=>
string(41) "/*qc=on*/SELECT id FROM test WHERE id = 2"
["origin"]=>
string(86) "#0 /home/nixnutz/php/phpdoc/foo.php(19): mysqli->query('/*qc=on*/SELECT...')
#1 {main}"
["run_time"]=>
int(4)
["store_time"]=>
int(2)
["eligible_for_caching"]=>
bool(true)
["no_table"]=>
bool(false)
["was_added"]=>
bool(false)
["was_already_in_cache"]=>
bool(true)
}
}
See Also
* Runtime configuration
* mysqlnd_qc.collect_query_trace
* mysqlnd_qc.query_trace_bt_depth
* mysqlnd_qc.time_statistics
* mysqlnd_qc.cache_no_table
----------------------------------------------------------------------
----------------------------------------------------------------------
mysqlnd_qc_set_user_handlers
(No version information available, might only be in SVN)
mysqlnd_qc_set_user_handlers - Sets the callback functions for a
user-defined procedural storage handler
Description
bool mysqlnd_qc_set_user_handlers ( string $get_hash , string
$find_query_in_cache , string $return_to_cache , string
$add_query_to_cache_if_not_exists , string $query_is_select , string
$update_query_run_time_stats , string $get_stats , string $clear_cache )
Sets the callback functions for a user-defined procedural storage handler.
Parameters
get_hash
Name of the user function implementing the storage handler
get_hash functionality.
find_query_in_cache
Name of the user function implementing the storage handler
find_in_cache functionality.
return_to_cache
Name of the user function implementing the storage handler
return_to_cache functionality.
add_query_to_cache_if_not_exists
Name of the user function implementing the storage handler
add_query_to_cache_if_not_exists functionality.
query_is_select
Name of the user function implementing the storage handler
query_is_select functionality.
update_query_run_time_stats
Name of the user function implementing the storage handler
update_query_run_time_stats functionality.
get_stats
Name of the user function implementing the storage handler
get_stats functionality.
clear_cache
Name of the user function implementing the storage handler
clear_cache functionality.
Return Values
Returns TRUE on success or FALSE on FAILURE.
See Also
* Procedural user-defined storage handler example
----------------------------------------------------------------------
Table of Contents
* mysqlnd_qc_change_handler - Change current storage handler
* mysqlnd_qc_clear_cache - Flush all cache contents
* mysqlnd_qc_get_cache_info - Returns information on the current
handler, the number of cache entries and cache entries, if available
* mysqlnd_qc_get_core_stats - Statistics collected by the core of the
query cache
* mysqlnd_qc_get_handler - Returns a list of available storage handler
* mysqlnd_qc_get_query_trace_log - Returns a backtrace for each query
inspected by the query cache
* mysqlnd_qc_set_user_handlers - Sets the callback functions for a
user-defined procedural storage handler
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Predefined Constants
* Examples
* Basic usage
* Setting the TTL
* Cache by default
* Procedural user-defined storage handler
* mysqlnd_qc Functions
* mysqlnd_qc_change_handler - Change current storage handler
* mysqlnd_qc_clear_cache - Flush all cache contents
* mysqlnd_qc_get_cache_info - Returns information on the current
handler, the number of cache entries and cache entries, if
available
* mysqlnd_qc_get_core_stats - Statistics collected by the core of
the query cache
* mysqlnd_qc_get_handler - Returns a list of available storage
handler
* mysqlnd_qc_get_query_trace_log - Returns a backtrace for each
query inspected by the query cache
* mysqlnd_qc_set_user_handlers - Sets the callback functions for a
user-defined procedural storage handler
----------------------------------------------------------------------
----------------------------------------------------------------------
Oracle OCI8
----------------------------------------------------------------------
Introduction
These functions allow you to access Oracle Database 11g, 10g, 9i and 8i.
They support SQL and PL/SQL statements. Basic features include transaction
control, binding of PHP variables to Oracle placeholders, and support for
large object (LOB) types and collections. Oracle's scalability features
such as Database Resident Connection Pooling (DRCP) and result caching are
also supported.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Testing
* Runtime Configuration
----------------------------------------------------------------------
Requirements
The OCI8 extension requires Oracle 9iR2, 10g or 11g Client libraries. If
the Oracle Database is on the same machine as PHP, the database software
already contains the necessary libraries. When PHP is on a different
machine, use the free >> Oracle Instant Client libraries.
To use Oracle Instant Client, install the basic or basiclite Oracle
Instant Client ZIP file or RPM package. When building PHP from source
code, also install the sdk ZIP file or devel RPM package.
On Windows, the php_oci8 DLL needs client libraries from version 10gR2 or
greater. In PHP 5.3 up to and including PHP 5.3.5, the php_oci8_11g DLL
requires Oracle 11gR1 or greater client libraries. From PHP 5.3.6 the
php_oci8_11g DLL requires Oracle 11gR2 or greater client libraries. With
some versions of Instant Client you may additionally need mfc71.dll and
msvcr71.dll libraries.
You should run PHP with the same, or more recent, version of the Oracle
libraries that OCI8 was built with.
Note:
If OCI8 uses 9iR2 or 10g client libraries, then PHP can connect to
Oracle Database 8i, 9iR2, 10g or 11g. If OCI8 uses 11g client libraries,
the database can be 9iR2, 10g or 11g.
Note:
Full OCI8 feature support is only available when using the most recent
versions of the client libraries and database.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
Configuring PHP with OCI8
Review the previous Requirements section before configuring OCI8.
To enable the OCI8 extension, configure PHP with the option --with-oci8 .
Before starting the web server, OCI8 typically requires several Oracle
environment variables (see below) to locate libraries, point to
configuration files, and set some basic properties such as the character
set used by Oracle libraries. The variables should be set before any PHP
process starts.
PHP should be run with the same, or more recent, major version of Oracle
libraries as it was configured with. For example, if you build OCI8 with
Oracle 11.2 libraries, then PHP should also be deployed and run with
Oracle 11.2 libraries.
Installing OCI8 as a Shared Extension
The configuration shared option builds OCI8 as a shared library that can
be dynamically loaded into PHP. Building a shared extension allows OCI8 to
be upgraded easily without impacting the rest of PHP.
Configure OCI8 using one of the following configure options.
* If using Oracle Instant Client, then do:
./configure --with-oci8=shared,instantclient,/path/to/instant/client/lib
If Instant Client is installed from ZIP files, make sure to create the
library symbolic link, for example ln -s libclntsh.so.11.1
libclntsh.so.
If using an RPM-based installation of Oracle Instant Client, the
configure line will look like this:
./configure --with-oci8=shared,instantclient,/usr/lib/oracle//client/lib
For example,
--with-oci8=shared,instantclient,/usr/lib/oracle/11.2/client/lib .
Note that Oracle Instant Client support first appeared in PHP 4.3.11
and 5.0.4 and originally used the option --with-oci8-instant-client to
configure PHP.
* If using an Oracle database or full Oracle Client installation then
do:
./configure --with-oci8=shared,$ORACLE_HOME
Make sure the web server user (nobody, www) has access to the
libraries, initialization files and tnsnames.ora (if used) under the
$ORACLE_HOME directory. With Oracle 10gR2, you may need to run the
$ORACLE_HOME/install/changePerm.sh utility to give directory access.
After configuration, follow the usual PHP building procedure, e.g. make
install. The OCI8 shared extension oci8.so library will be created. It may
need to be manually moved to the PHP extension directory, specified by the
extension_dir option in your php.ini file.
To complete installation of OCI8, edit php.ini and add the line:
extension=oci8.so
Installing OCI8 as a Statically Compiled Extension
Configure OCI8 using one of the following configure options.
* If using Oracle Instant Client, then do:
./configure --with-oci8=instantclient,/path/to/instant/client/lib
* If using an Oracle database or full Oracle Client installation then
do:
./configure --with-oci8=$ORACLE_HOME
After configuration, follow the usual PHP building procedure, e.g. make
install. After successful compilation, you do not need to add oci8.so to
php.ini. No additional build steps are required.
Installing OCI8 from PECL
The OCI8 extension can be added to an existing PHP installation either
automatically or manually from >> http://pecl.php.net/. Information for
installing this PECL extension may be found in the manual chapter titled
Installation of PECL extensions. Additional information such as new
releases, downloads, source files, maintainer information, and a
CHANGELOG, can be located here: >> http://pecl.php.net/package/oci8.
For an automated install follow these steps:
* If you are behind a firewall, set PEAR's proxy, for example:
pear config-set http_proxy http://my-proxy.example.com:80/
* Run
pecl install oci8
When prompted, enter either the value of $ORACLE_HOME, or
instantclient,/path/to/instant/client/lib.
Note: Do not enter the variable $ORACLE_HOME because it will not be
expanded. Instead, enter the actual path of the Oracle home directory.
For a manual install, download the PECL OCI8 package, e.g. oci8-1.3.5.tgz.
* Extract the package:
tar -zxf oci8-1.3.5.tgz
cd oci8-1.3.5
* Prepare the package:
phpize
* Configure the package, either using $ORACLE_HOME or Instant Client
./configure -with-oci8=shared,$ORACLE_HOME
or
./configure -with-oci8=shared,instantclient,/path/to/instant/client/lib
* Install the package:
make install
After either an automatic or manual install, edit your php.ini file and
add the line:
extension=oci8.so
Make sure the php.ini directive extension_dir is set to the directory that
oci8.so was installed in.
Installing OCI8 on Windows
On Windows, uncomment the php.ini line extension=php_oci8.dll when using
Oracle 10gR2 client libraries. Uncomment extension=php_oci8_11g.dll when
using Oracle 11g client libraries. These two DLLs contain equivalent
functionality and only one may be enabled at a time. Make sure
extension_dir is set to the directory containing the PHP extension DLLs.
If using Instant Client, set the system PATH environment variable to the
Oracle library directory.
Setting the Oracle Environment
Before using this extension, make sure that the Oracle environment
variables are properly set for the web daemon user. If your web server is
automatically started at boot time then make sure that the boot-time
environment is also configured correctly.
Note:
Do not set Oracle environment variables using putenv() in a PHP script
because Oracle libraries may be loaded and initialized before your
script runs. Variables set with putenv() may then cause conflicts,
crashes, or unpredictable behavior. Some functions may work but others
might give subtle errors. The variables should be set up before the web
server is started.
On Red Hat Linux and variants, export variables at the end of
/etc/sysconfig/httpd. Other systems with Apache 2 may use an envvars
script in the Apache bin directory. A third option, the Apache SetEnv
directive in httpd.conf, may work in some systems but is known to be
insufficient in others.
To check that environment variables are set correctly, use phpinfo() and
check the Environment (not the Apache Environment) section contains the
expected variables.
The variables that might be needed are included in the following table.
Refer to the Oracle documentation for more information on all the
variables.
Common Oracle Environment Variables
Name Purpose
Contains the directory of the full Oracle Database
ORACLE_HOME software. Do not set this when using Oracle Instant Client
as it is unnecessary and may cause installation problems.
Contains the name of the database on the local machine to
ORACLE_SID be connected to. There is no need to set this if you using
Oracle Instant Client, or always pass the connection
parameter to oci_connect().
Set this (or its platform equivalent, such as
DYLD_LIBRARY_PATH, LIBPATH, or SHLIB_PATH) to the location
LD_LIBRARY_PATH of the Oracle libraries, for example $ORACLE_HOME/lib or
/usr/lib/oracle/11.1/client/lib. This variable is not
needed if the libraries are located by a different search
mechanism, such as with ldconfig or with LD_PRELOAD.
This is the primary variable for setting the character set
NLS_LANG and globalization information used by the Oracle
libraries.
ORA_SDTZ Sets the Oracle session timezone.
Contains the directory where the Oracle Net Services
configuration files such as tnsnames.ora and sqlnet.ora
are kept. Not needed if the oci_connect() connection
TNS_ADMIN string uses the Easy Connect naming syntax such as
localhost/XE. Not needed if the network configuration
files are in one of the default locations such as
$ORACLE_HOME/network/admin or /etc.
Less frequently used Oracle environment variables include TWO_TASK,
ORA_TZFILE, and the various Oracle globalization settings like NLS* and
the ORA_NLS_* variables.
Troubleshooting
The most common problem with installing OCI8 is not having the Oracle
environment correctly set. This typically appears as a problem using
oci_connect() or oci_pconnect(). The error may be a PHP error such as Call
to undefined function oci_connect(), an Oracle error such as ORA-12705, or
even an Apache crash. Check the Apache log files for startup errors and
see the sections above to resolve this problem.
While network errors like ORA-12154 or ORA-12514 indicate an Oracle
network naming or configuration issue, the root cause may be because the
PHP environment is incorrectly set up and Oracle libraries are unable to
locate the tnsnames.ora configuration file.
On Windows, having multiple versions of Oracle on the one machine can
easily cause library clashes unless care is taken to make sure PHP only
uses the correct version of Oracle.
A utility to examine what libraries are being looked for and loaded can
help resolve missing or clashing library issues, particularly on Windows.
Note: If the web server doesn't start or crashes at startup
Check that Apache is linked with the pthread library:
# ldd /www/apache/bin/httpd
libpthread.so.0 => /lib/libpthread.so.0 (0x4001c000)
libm.so.6 => /lib/libm.so.6 (0x4002f000)
libcrypt.so.1 => /lib/libcrypt.so.1 (0x4004c000)
libdl.so.2 => /lib/libdl.so.2 (0x4007a000)
libc.so.6 => /lib/libc.so.6 (0x4007e000)
/lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
If the libpthread is not listed, then reinstall Apache:
# cd /usr/src/apache_1.3.xx
# make clean
# LIBS=-lpthread ./config.status
# make
# make install
Please note that on some systems like UnixWare, it is libthread instead
of libpthread. PHP and Apache have to be configured with
EXTRA_LIBS=-lthread.
----------------------------------------------------------------------
----------------------------------------------------------------------
Testing
The OCI8 test suite is in ext/oci8/tests. After OCI8 tests are run this
directory will also contain logs of any failures.
Before running PHP's tests, edit details.inc and set $user, $password and
the $dbase connection string. The OCI8 test suite has been developed using
the SYSTEM account. Some tests will fail if the test user does not have
equivalent permissions.
If the database is on the same machine as PHP, set $oracle_on_localhost to
TRUE.
If Oracle 11g Database Resident Connection Pooling is being tested, set
$test_drcp to TRUE and ensure the connection string uses an appropriate
DRCP pooled server.
An alternative to editing details.inc is the set environment variables,
for example:
$ export PHP_OCI8_TEST_USER=system
$ export PHP_OCI8_TEST_PASS=oracle
$ export PHP_OCI8_TEST_DB=localhost/XE
$ export PHP_OCI8_TEST_DB_ON_LOCALHOST=TRUE
$ export PHP_OCI8_TEST_DRCP=FALSE
Note in some shells these variables are not propagated correctly to the
PHP process and tests will fail to connect if this method is used.
Next, set any necessary environment for the Oracle database. With Oracle
10g XE do:
$ . /usr/lib/oracle/xe/app/oracle/product/10.2.0/server/bin/oracle_env.sh
For other versions of the Oracle database do:
$ . /usr/local/bin/oraenv
Some shells require that php.ini has E in the variables_order parameter,
for example:
variables_order = "EGPCS"
Run all the PHP tests with:
$ cd your_php_src_directory
$ make test
or run only the OCI8 tests with
$ cd your_php_src_directory
$ make test TESTS=ext/oci8
When the tests have completed, review any test failures. On slow systems,
some tests may take longer than the default test timeout in run-tests.php.
To correct this, set the environment variable TEST_TIMEOUT to a larger
number of seconds.
On fast machines with a local database configured for light load (e.g.
Oracle 10g XE) some tests might fail with ORA-12516 or ORA-12520 errors.
To prevent this, increase the database PROCESSES parameter using the
following steps:
Connect as the oracle software owner:
$ su - oracle
Set the necessary Oracle environment with oracle_env.sh or oraenv, as
described above.
Start the SQL*Plus command line tool and increase PROCESSES
$ sqlplus / as sysdba
SQL> alter system set processes=100 scope=spfile
Restart the database:
SQL> startup force
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
OCI8 Configuration Options
Name Default Changeable Changelog
oci8.connection_class "" PHP_INI_ALL Available since PHP
5.3 (PECL OCI8 1.3).
oci8.default_prefetch "100" PHP_INI_SYSTEM Available since PHP
5.1.2 (PECL OCI8 1.1).
oci8.events Off PHP_INI_SYSTEM Available since PHP
5.3 (PECL OCI8 1.3).
oci8.max_persistent "-1" PHP_INI_SYSTEM Available since PHP
5.1.2 (PECL OCI8 1.1).
oci8.old_oci_close_semantics Off PHP_INI_SYSTEM Available since PHP
5.1.2 (PECL OCI8 1.1).
oci8.persistent_timeout "-1" PHP_INI_SYSTEM Available since PHP
5.1.2 (PECL OCI8 1.1).
oci8.ping_interval "60" PHP_INI_SYSTEM Available since PHP
5.1.2 (PECL OCI8 1.1).
oci8.privileged_connect Off PHP_INI_SYSTEM Available since PHP
5.1.2 (PECL OCI8 1.1).
oci8.statement_cache_size "20" PHP_INI_SYSTEM Available since PHP
5.1.2 (PECL OCI8 1.1).
Here's a short explanation of the configuration directives.
oci8.connection_class string
This user defined text is used by Oracle 11g Database Resident
Connection Pooling (DRCP) connections to sub-partition the
connection pool. It allows OCI8 persistent connections from an
application to reuse database sessions from a previous PHP script,
giving better scalability. When an application uses a database
pooled process previously used with a different connection class,
the session settings such as the default Oracle date format are
reset. This prevents accidental sharing of information between
different applications.
The value can be set at runtime with ini_set() prior to
connecting.
To use DRCP, OCI8 must be linked with Oracle 11g libraries and the
database must be Oracle 11g. The connection pool must be enabled
in the database, the oci8.connection_class should be set to the
same string for all web servers running the same application, and
the OCI8 connection string must specify to use a pooled server.
oci8.default_prefetch int
This option sets the default number of extra rows that will be
fetched and cached automatically whenever a low-level request for
data from the database is made. Setting a value of 0 turns off
prefetching.
The prefetch value does not alter the number of rows that
functions like oci_fetch_array() return to the user; the
prefetching and caching of rows is handled internally in OCI8.
The value can be set per-statement with oci_set_prefetch() prior
to statement execution.
In PHP 5.3 (PECL OCI8 1.3.4) the default value was increased from
10 to 100.
In PHP 5.3.2 (PECL OCI8 1.4) the minimum value settable was
reduced from 1 to 0, allowing prefetching to be turned off.
Note: A larger prefetch can result in improved performance, at
the cost of some increased memory usage. For queries that return
large amounts of data, the performance benefit can be
significant.
oci8.events boolean
Using On allows PHP to be notified of database Fast Application
Notification (FAN) events.
Without FAN, when a database instance or machine node fails
unexpectedly, PHP applications may be blocked waiting for a
database response until a TCP timeout expires. With FAN events,
PHP applications are quickly notified of failures that affect
their established database connections. The OCI8 extension will
clean up unusable connections in the persistent connection cache.
When using On, the database must also be configured to post FAN
events.
FAN support is available when OCI8 is linked with Oracle 10gR2 (or
later) libraries and connected to Oracle Database 10gR2 (or
later).
oci8.max_persistent int
The maximum number of persistent OCI8 connections per PHP process.
Setting this option to -1 means that there is no limit.
oci8.old_oci_close_semantics boolean
This option controls oci_close() behaviour. Enabling it means that
oci_close() will do nothing; the connection will not be closed
until the end of the script. This is for backward compatibility
only. If you find that you need to enable this setting, you are
strongly encouraged to adjust the oci_close() calls in your
application instead of enabling this option.
oci8.persistent_timeout int
The maximum number of seconds that a PHP process is allowed to
keep an idle persistent connection open. Setting this option to -1
means that idle persistent connections will be retained until the
PHP process terminates or the connection is explicitly closed with
oci_close().
Note: In PHP, the expiry of idle resources is not alarm-based.
It occurs when PHP finishes processing a script and checks the
last-used timestamp of resources. Hence there is a paradox that
idle connections can only be closed when there is some activity
(though not necessarily OCI8 related) in the PHP process. The
introduction of Database Resident Connection Pooling (DRCP) in
Oracle 11g resolves the memory and resource issues that
oci8.max_persistent and oci8.persistent_timeout previously
attempted to overcome.
Note: In PHP 5.3 (PECL OCI8 1.3), persistent connections can be
closed with oci_close().
oci8.ping_interval int
The number of seconds that must pass before issuing a ping during
oci_pconnect(). A ping ensures that the database connection is
valid. When set to 0, persistent connections will be pinged every
time oci_pconnect() is called. To disable pings completely, set
this option to -1.
Note: Disabling pings allows oci_pconnect() to operate at the
highest efficiency, but PHP may not be able to detect unusable
connections, such as caused by network dropout, or if the Oracle
database has gone down since PHP connected, until the connection
is used later in the script. Consult the oci_pconnect()
documentation for more information.
oci8.privileged_connect boolean
This option allows connections to use the privileged external
credentials OCI_SYSOPER or OCI_SYSDBA.
Note: Seting this On can allow scripts on web servers running
with the appropriate OS user privileges to connect as privileged
database users without requiring a database password. This can
be a security risk.
oci8.statement_cache_size int
This option enables statement caching, and specifies how many
statements to cache. To disable statement caching just set this
option to 0.
Statement caching removes the need to transmit the statement text
to the database and removes the need to transmit any meta data
about the statement back to PHP. This can significantly improve
overall system performance in applications which reuse statements
during the lifetime of a connection. Some extra database "cursors"
may be held open under the assumption that statements will be
reused.
Set this value to the size of the working set of statements used
by your application. Setting too small a value can cause
statements to be flushed from the cache before they are reused.
This option is of most use with persistent connections.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
OCI8 Function and Method Modes
Constant Description
Used with oci_fetch_all() and
OCI_ASSOC oci_fetch_array() to get results as an
associative array.
Used with oci_fetch_all() and
OCI_BOTH oci_fetch_array() to get results as an array
with both associative and number indices.
Statement execution mode for oci_execute()
OCI_COMMIT_ON_SUCCESS call. Automatically commit changes when the
statement has succeeded.
Used with oci_connect() for using Oracles'
OCI_CRED_EXT External or OS authentication. Introduced in
PHP 5.3 and PECL OCI8 1.3.4.
Statement execution mode for oci_execute().
The transaction is not automatically
OCI_DEFAULT committed when using this mode. From PHP
5.3.2 (PECL OCI8 1.4) onwards,
OCI_NO_AUTO_COMMIT is preferred instead of
OCI_DEFAULT.
Statement execution mode for oci_execute().
OCI_DESCRIBE_ONLY Use this mode if you want meta data such as
the column names but don't want to fetch rows
from the query.
Obsolete. Statement fetch mode. Used when the
application knows in advance exactly how many
rows it will be fetching. This mode turns
OCI_EXACT_FETCH prefetching off for Oracle release 8 or later
mode. The cursor is canceled after the
desired rows are fetched which may result in
reduced server-side resource usage.
OCI_FETCHSTATEMENT_BY_COLUMN Default mode of oci_fetch_all().
OCI_FETCHSTATEMENT_BY_ROW Alternative mode of oci_fetch_all().
OCI_LOB_BUFFER_FREE Used with OCI-Lob->flush to free buffers
used.
Statement execution mode for oci_execute().
The statement is not committed automatically
OCI_NO_AUTO_COMMIT when using this mode. For readability in new
code, use this value instead of the obsolete
OCI_DEFAULT constant. Introduced in PHP 5.3.2
(PECL OCI8 1.4).
Used with oci_fetch_all() and
OCI_NUM oci_fetch_array() to get results as an
enumerated array.
OCI_RETURN_LOBS Used with oci_fetch_array() to get the data
value of the LOB instead of the descriptor.
Used with oci_fetch_array() to get empty
OCI_RETURN_NULLS array elements if the row items value is
NULL.
OCI_SEEK_CUR Used with OCI-Lob->seek to set the seek
position.
OCI_SEEK_END Used with OCI-Lob->seek to set the seek
position.
OCI_SEEK_SET Used with OCI-Lob->seek to set the seek
position.
OCI_SYSDATE Obsolete.
Used with oci_connect() to connect with the
OCI_SYSDBA SYSDBA privilege. The php.ini setting
oci8.privileged_connect should be enabled to
use this.
Used with oci_connect() to connect with the
OCI_SYSOPER SYSOPER privilege. The php.ini setting
oci8.privileged_connect should be enabled to
use this.
OCI_TEMP_BLOB Used with OCI-Lob->writeTemporary to indicate
that a temporary BLOB should be created.
OCI_TEMP_CLOB Used with OCI-Lob->writeTemporary to indicate
that a temporary CLOB should be created.
OCI8 Bind and Define Types
Constant Description
OCI_B_BFILE Used with oci_bind_by_name() when binding BFILEs.
OCI_B_BIN
OCI_B_BLOB Used with oci_bind_by_name() when binding BLOBs.
OCI_B_CFILEE Used with oci_bind_by_name() when binding CFILEs.
OCI_B_CLOB Used with oci_bind_by_name() when binding CLOBs.
OCI_B_CURSOR Used with oci_bind_by_name() when binding cursors, previously
allocated with oci_new_descriptor().
OCI_B_INT Used with oci_bind_array_by_name() to bind arrays of INTEGER.
OCI_B_NTY Used with oci_bind_by_name() when binding named data types.
Note: in PHP < 5.0 it was called OCI_B_SQLT_NTY.
OCI_B_NUM Used with oci_bind_array_by_name() to bind arrays of NUMBER.
OCI_B_ROWID Used with oci_bind_by_name() when binding ROWIDs.
SQLT_AFC Used with oci_bind_array_by_name() to bind arrays of CHAR.
SQLT_AVC Used with oci_bind_array_by_name() to bind arrays of
VARCHAR2.
SQLT_BDOUBLE
SQLT_BFILEE The same as OCI_B_BFILE.
SQLT_BFLOAT
SQLT_BIN Used with oci_bind_by_name() to bind RAW values.
SQLT_BLOB The same as OCI_B_BLOB.
SQLT_CFILEE The same as OCI_B_CFILEE.
SQLT_CHR Used with oci_bind_array_by_name() to bind arrays of
VARCHAR2. Also used with oci_bind_by_name().
SQLT_CLOB The same as OCI_B_CLOB.
SQLT_FLT Used with oci_bind_array_by_name() to bind arrays of FLOAT.
SQLT_INT The same as OCI_B_INT.
SQLT_LBI Used with oci_bind_by_name() to bind LONG RAW values.
SQLT_LNG Used with oci_bind_by_name() to bind LONG values.
SQLT_LVC Used with oci_bind_array_by_name() to bind arrays of LONG
VARCHAR.
SQLT_NTY The same as OCI_B_NTY.
SQLT_NUM The same as OCI_B_NUM.
SQLT_ODT Used with oci_bind_array_by_name() to bind arrays of LONG.
SQLT_RDD The same as OCI_B_ROWID.
SQLT_RSET The same as OCI_B_CURSOR.
SQLT_STR Used with oci_bind_array_by_name() to bind arrays of STRING.
SQLT_UIN
SQLT_VCS Used with oci_bind_array_by_name() to bind arrays of VARCHAR.
OCI8 Descriptor Types
Constant Description
OCI_DTYPE_FILE This flag tells oci_new_descriptor() to initialize a new
FILE descriptor.
OCI_DTYPE_LOB This flag tells oci_new_descriptor() to initialize a new
LOB descriptor.
OCI_DTYPE_ROWID This flag tells oci_new_descriptor() to initialize a new
ROWID descriptor.
OCI_D_FILE The same as OCI_DTYPE_FILE.
OCI_D_LOB The same as OCI_DTYPE_LOB.
OCI_D_ROWID The same as OCI_DTYPE_ROWID.
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
These examples connect as the HR user, which is the sample "Human
Resources" schema supplied with the Oracle database. The account may need
to be unlocked and the password reset before you can use it.
The examples connect to the XE database on your machine. Change the
connect string to your database before running the examples.
Example #1 Basic query
This shows querying and displaying results. Statements in OCI8 use a
prepare-execute-fetch sequence of steps.
\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
print "\n";
foreach ($row as $item) {
print " " . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . " \n";
}
print " \n";
}
print "\n";
oci_free_statement($stid);
oci_close($conn);
?>
Example #2 Inserting with bind variables
Bind variables improve performance by allowing reuse of execution contexts
and caches. Bind variables improve security by preventing some kinds of
SQL Injection problems.
Example #3 Inserting data into a CLOB column
For large data use binary long object (BLOB) or character long object
(CLOB) types. This example uses CLOB.
save("A very long string");
oci_commit($conn);
// Fetching CLOB data
$query = 'SELECT myclob FROM mytable WHERE mykey = :mykey';
$stid = oci_parse ($conn, $query);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_execute($stid);
print '';
while ($row = oci_fetch_array($stid, OCI_ASSOC)) {
$result = $row['MYCLOB']->load();
print ''.$result.' ';
}
print '
';
?>
Example #4 Using a PL/SQL stored function
You must bind a variable for the return value and optionally for any
PL/SQL function arguments.
Example #5 Using a PL/SQL stored procedure
With stored procedures, you should bind variables for any arguments.
Example #6 Calling a PL/SQL function that returns a REF CURSOR
Each returned value from the query is a REF CURSOR that can be fetched
from.
\n";
while (($row = oci_fetch_array($stid, OCI_ASSOC))) {
echo "\n";
$rc = $row['MFRC'];
oci_execute($rc); // returned column value from the query is a ref cursor
while (($rc_row = oci_fetch_array($rc, OCI_ASSOC))) {
echo " " . $rc_row['CITY'] . " \n";
}
oci_free_statement($rc);
echo " \n";
}
echo "\n";
// Output is:
// Beijing
// Bern
// Bombay
// Geneva
oci_free_statement($stid);
oci_close($conn);
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
Connection Handling
Connection Functions
The OCI8 extension provides three different functions for connecting to
Oracle. The standard connection function is oci_connect(). This creates a
connection to an Oracle database and returns a resource used by subsequent
database calls.
Connecting to an Oracle server is a reasonably expensive operation in
terms of the time that it takes to complete. The oci_pconnect() function
uses a persistent cache of connections that can be re-used across
different script requests. This means that the connection overhead will
typically only occur once per PHP process (or Apache child).
If the application connects to Oracle using a different set of credentials
for each web user, the persistent cache employed by oci_pconnect() will
become less useful as the number of concurrent users increases, to the
point where it may start to adversely affect the overall performance of
the Oracle server due to maintaining too many idle connections. If the
application is structured in this way, it is recommended to either tune
the application using the oci8.max_persistent and oci8.persistent_timeout
configuration settings (these will give control over the persistent
connection cache size and lifetime), use Oracle 11g Database Resident
Connection Pooling, or use oci_connect() instead.
Both oci_connect() and oci_pconnect() employ a connection cache; if
multiple calls to oci_connect() use the same parameters in a given script,
the second and subsequent calls return the existing connection handle. The
cache used by oci_connect() is cleaned up at the end of the script run, or
when the connection handle is explicitly closed. The function
oci_pconnect() has similar behavior, although its cache is maintained
separately and survives between HTTP requests.
This caching feature means the two handles are not transactionally
isolated (they are in fact the same connection handle, so there is no
isolation of any kind). If the application needs two separate,
transactionally isolated connections, then use oci_new_connect().
The oci_pconnect() cache is cleared and any database connections closed
when the PHP process terminates, so effective use of persistent
connections requires that PHP be an Apache module or used with FGCI, or
similar. Persistent connections will not have any benefits over
oci_connect() when PHP is used with CGI or via the command-line.
The function oci_new_connect() always creates a new connection to the
Oracle server, regardless of what other connections might already exist.
High traffic web applications should avoid using oci_new_connect(),
especially in the busiest sections of the application.
DRCP Connection Pooling
PHP 5.3 (PECL OCI8 1.3) supports Oracle 11g Database Resident Connection
Pooling (DRCP). DRCP allows more efficient use of database machine memory
and provides high scalability. No, or minimal, application changes are
needed to use DRCP.
DRCP is suited for applications that connect using few database schemas
and hold database connections open for a short period of time. Other
applications should use Oracle's default Dedicated database server
processes, or use Shared servers.
DRCP benefits all three connection functions, but gives the highest
scalability when connections are created with oci_pconnect().
For DRCP to be available in OCI8, Oracle client libraries used by PHP and
the version of the Oracle Database must both be 11g.
Documentation on DRCP is found in several Oracle manuals. For example, see
>> Configuring Database Resident Connection Pooling in the Oracle
documentation for usage information. A >> DRCP white paper contains
background information on DRCP.
To use DRCP, build PHP with the OCI8 1.3 extension and Oracle 11g
libraries and then follow these steps:
* As a privileged database administrator, use a program like SQL*Plus to
start the connection pool in the database:
SQL> execute dbms_connection_pool.start_pool;
* Optionally use dbms_connection_pool.alter_param() to configure DRCP
settings. The current pool settings can be queried from the
DBA_CPOOL_INFO view.
* Update the connection strings used. For PHP applications that
currently connect using a Network Connect Name like MYDB:
$c = oci_pconnect("myuser", "mypassword", "MYDB");
modify the tnsnames.ora file and add a (SERVER=POOLED) clause, for
example:
MYDB = (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp) (HOST=myhost.dom.com)
(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=sales)
(SERVER=POOLED)))
Alternatively, modify the Easy Connect syntax in PHP and add :POOLED
after the service name:
$c = oci_pconnect("myuser", "mypassword", "myhost.dom.com:1521/sales:POOLED");
* Edit php.ini and choose a connection class name. This name indicates a
logical division of the connection pool and can be used to isolate
pooling for separate applications. Any PHP applications with the same
user name and connection class value will be able to share connections
in the pool, giving greater scalability.
oci8.connection_class = "MY_APPLICATION_NAME"
* Run the application, connecting to the 11g database.
Note:
Applications using Oracle 10g that require the performance of persistent
connections can reduce the amount of database server memory needed by
using Oracle Shared servers (previously known as Multi Threaded
Servers). Refer to Oracle documentation for information.
DRCP Recommendations and Known Limitations
Changing a password over DRCP connections will fail with the error
ORA-56609: Usage not supported with DRCP. This is a documented restriction
of Oracle Database 11g.
With the OCI8 1.3 extension, persistent connections can now be closed by
the user, allowing greater control over connection resource usage.
Persistent connections will now also be closed automatically when there is
no PHP variable referencing them, such as at the end of scope of a PHP
user function. This will rollback any uncommitted transaction. These
changes to persistent connections make them behave similarly to
non-persistent connections, simplifying the interface, allowing for
greater application consistency and predictability. Use
oci8.old_oci_close_semantics set to On to retain the historical behavior.
If the Oracle Database is version 11.1.0.6, then the Oracle database patch
for Oracle bug 6474441 must be applied to use DRCP. Without this patch,
errors such as ORA-01000: maximum open cursors exceeded, ORA-01001 invalid
cursor or ORA-01002 fetch out of sequence may occur. This bug was fixed in
Oracle 11.1.0.7 onwards.
If the Oracle 11.1.0.6 database patch cannot be applied, one of the
following three workarounds can be used instead:
* Connect using Oracle Dedicated or Shared servers instead of DRCP.
* Set PHP's oci8.statement_cache_size to 0.
* Set an event in the database initialization parameter file:
event="56699 trace name context forever, level 128".
Oracle Database 11.1.0.7 and the Oracle Database 11.1.0.6 patch for Oracle
bug 6474441 allow PHP applications with DRCP connection to use a database
LOGON trigger to set session properties at the time of session creation.
Examples of such settings are the NLS language and the date format.
If the Oracle 11.1.0.6 database patch cannot be applied, one of the
following workarounds can be used instead of using LOGON triggers:
* After logon, explicitly set the session properties using PHP
application code.
* Connect using Oracle Dedicated or Shared servers instead of DRCP.
The automatic re-establishment of PHP persistent connections after an
Apache or FGCI process respawns means LOGON triggers in PHP are only
recommended for setting session attributes and not for per-application
user connection requests. This is even more so with DRCP due to the
automatic pool sizing and with the way LOGON triggers fire with DRCP
authentication.
Fast Application Notification (FAN) Support
FAN support gives fast connection failover, a high availability feature.
This allows PHP OCI8 scripts to be notified when a database machine or
database instance becomes unavailable. Without FAN, OCI8 can hang until a
TCP timeout occurs and an error is returned, which might be several
minutes. Enabling FAN in OCI8 can allow applications to detect errors and
re-connect to an available database instance without the web user being
aware of an outage.
FAN support is available when the Oracle client libraries that PHP links
with and the Oracle Database are either version 10gR2 or 11g.
FAN benefits users of Oracle's clustering technology (RAC) because
connections to surviving database instances can be immediately made. Users
of Oracle's Data Guard with a broker will see the FAN events generated
when the standby database goes online. Standalone databases will send FAN
events when the database restarts.
For active connections, when a machine or database instance becomes
unavailable, a connection failure error will be returned by the OCI8
extension function currently being called. On a subsequent PHP script
re-connect, a connection to a surviving database instance will be
established. The OCI8 extension also transparently cleans up any idle
connections affected by a database machine or instance failure so PHP
connect calls will establish a fresh connection without the script being
aware of any service disruption.
When oci8.events is On, it is suggested to set oci8.ping_interval to -1 to
disable pinging, since enabling FAN events provide pro-active connection
management of idle connections made invalid by a service disruption.
To enable FAN support in PHP, build PHP with Oracle 10gR2 or 11g libraries
and then follow these steps:
* As a privileged database administrator, use a program like SQL*Plus to
enable the database service to post FAN events, for example:
SQL> execute dbms_service.modify_service(
SERVICE_NAME => 'sales',
AQ_HA_NOTIFICATIONS => TRUE);
* Edit php.ini and add
oci8.events = On
* If the application does not already handle OCI8 error conditions,
modify it to detect failures and take appropriate action. This may
include re-connecting and re-executing statements.
* Run the application, connecting to an Oracle 10gR2 or 11g database.
----------------------------------------------------------------------
----------------------------------------------------------------------
Supported Datatypes
The driver supports the following types when binding parameters using
oci_bind_by_name() function:
Type Mapping
Maps a native collection type from a PHP collection
SQLT_NTY object, such as those created by
oci_new_collection().
SQLT_BFILEE Maps a native descriptor, such as those created by
oci_new_descriptor().
SQLT_CFILEE Maps a native descriptor, such as those created by
oci_new_descriptor().
SQLT_CLOB Maps a native descriptor, such as those created by
oci_new_descriptor().
SQLT_BLOB Maps a native descriptor, such as those created by
oci_new_descriptor().
SQLT_RDD Maps a native descriptor, such as those created by
oci_new_descriptor().
SQLT_NUM Converts the PHP parameter to a 'C' long type, and
binds to that value.
Maps a native statement handle, such as those
SQLT_RSET created by oci_parse() or those retrieved from
other OCI queries.
SQLT_CHR and any other Converts the PHP parameter to a string type and
type binds as a string.
The following types are supported when retrieving columns from a result
set:
Type Mapping
SQLT_RSET Creates an oci statement resource to represent the cursor.
SQLT_RDD Creates a ROWID object.
SQLT_BLOB Creates a LOB object.
SQLT_CLOB Creates a LOB object.
SQLT_BFILE Creates a LOB object.
SQLT_LNG Bound as SQLT_CHR, returned as a string
SQLT_LBI Bound as SQLT_BIN, returned as a string
Any other type Bound as SQLT_CHR, returned as a string
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI8 Functions
----------------------------------------------------------------------
oci_bind_array_by_name
(PHP 5 >= 5.1.2, PECL OCI8 >= 1.2.0)
oci_bind_array_by_name - Binds a PHP array to an Oracle PL/SQL array
parameter
Description
bool oci_bind_array_by_name ( resource $statement , string $name , array
&$var_array , int $max_table_length [, int $max_item_length = -1 [, int
$type = SQLT_AFC ]] )
Binds the PHP array var_array to the Oracle placeholder name, which points
to an Oracle PL/SQL array. Whether it will be used for input or output
will be determined at run-time.
Parameters
statement
A valid OCI statement identifier.
name
The Oracle placeholder.
var_array
An array.
max_table_length
Sets the maximum length both for incoming and result arrays.
max_item_length
Sets maximum length for array items. If not specified or equals to
-1, oci_bind_array_by_name() will find the longest element in the
incoming array and will use it as the maximum length.
type
Should be used to set the type of PL/SQL array items. See list of
available types below:
* SQLT_NUM - for arrays of NUMBER.
* SQLT_INT - for arrays of INTEGER (Note: INTEGER it is
actually a synonym for NUMBER(38), but SQLT_NUM type won't
work in this case even though they are synonyms).
* SQLT_FLT - for arrays of FLOAT.
* SQLT_AFC - for arrays of CHAR.
* SQLT_CHR - for arrays of VARCHAR2.
* SQLT_VCS - for arrays of VARCHAR.
* SQLT_AVC - for arrays of CHARZ.
* SQLT_STR - for arrays of STRING.
* SQLT_LVC - for arrays of LONG VARCHAR.
* SQLT_ODT - for arrays of DATE.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 oci_bind_array_by_name() example
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_bind_by_name
(PHP 5, PECL OCI8 >= 1.1.0)
oci_bind_by_name - Binds a PHP variable to an Oracle placeholder
Description
bool oci_bind_by_name ( resource $statement , string $bv_name , mixed
&$variable [, int $maxlength = -1 [, int $type = SQLT_CHR ]] )
Binds a PHP variable variable to the Oracle bind variable placeholder
bv_name. Binding is important for Oracle database performance and also as
a way to avoid SQL Injection security issues.
Binding allows the database to reuse the statement context and caches from
previous executions of the statement, even if another user or process
originally executed it. Binding reduces SQL Injection concerns because the
data associated with a bind variable is never treated as part of the SQL
statement. It does not need quoting or escaping.
PHP variables that have been bound can be changed and the statement
re-executed without needing to re-parse the statement or re-bind.
In Oracle, bind variables are commonly divided into IN binds for values
that are passed into the database, and OUT binds for values that are
returned to PHP. A bind variable may be both IN and OUT. Whether a bind
variable will be used for input or output is determined at run-time.
You must specify maxlength when using an OUT bind so that PHP allocates
enough memory to hold the returned value.
For IN binds it is recommended to set the maxlength length if the
statement is re-executed multiple times with different values for the PHP
variable. Otherwise Oracle may truncate data to the length of the initial
PHP variable value. If you don't know what the maximum length will be,
then re-call oci_bind_by_name() with the current data size prior to each
oci_execute() call. Binding an unnecessarily large length will have an
impact on process memory in the database.
A bind call tells Oracle which memory address to read data from. For IN
binds that address needs to contain valid data when oci_execute() is
called. This means that the variable bound must remain in scope until
execution. If it doesn't, unexpected results or errors such as "ORA-01460:
unimplemented or unreasonable conversion requested" may occur. For OUT
binds one symptom is no value being set in the PHP variable.
For a statement that is repeatedly executed, binding values that never
change may reduce the ability of the Oracle optimizer to choose the best
statement execution plan. Long running statements that are rarely
re-executed may not benefit from binding. However in both cases, binding
might be safer than joining strings into a SQL statement, as this can be a
security risk if unfiltered user text is concatenated.
Parameters
statement
A valid OCI8 statement identifer.
bv_name
The colon-prefixed bind variable placeholder used in the
statement. The colon is optional in bv_name. Oracle does not use
question marks for placeholders.
variable
The PHP variable to be associated with bv_name
maxlength
Sets the maximum length for the data. If you set it to -1, this
function will use the current length of variable to set the
maximum length. In this case the variable must exist and contain
data when oci_bind_by_name() is called.
type
The datatype that Oracle will treat the data as. The default type
used is SQLT_CHR. Oracle will convert the data between this type
and the database column (or PL/SQL variable type), when possible.
If you need to bind an abstract datatype (LOB/ROWID/BFILE) you
need to allocate it first using the oci_new_descriptor() function.
The length is not used for abstract datatypes and should be set to
-1.
Possible values for type are:
* SQLT_BFILEE or OCI_B_BFILE - for BFILEs;
* SQLT_CFILEE or OCI_B_CFILEE - for CFILEs;
* SQLT_CLOB or OCI_B_CLOB - for CLOBs;
* SQLT_BLOB or OCI_B_BLOB - for BLOBs;
* SQLT_RDD or OCI_B_ROWID - for ROWIDs;
* SQLT_NTY or OCI_B_NTY - for named datatypes;
* SQLT_INT or OCI_B_INT - for integers;
* SQLT_CHR - for VARCHARs;
* SQLT_BIN or OCI_B_BIN - for RAW columns;
* SQLT_LNG - for LONG columns;
* SQLT_LBI - for LONG RAW columns;
* SQLT_RSET - for cursors created with oci_new_cursor().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Inserting data with oci_bind_by_name()
Example #2 Binding once for multiple executions
Example #3 Binding with a foreach() loop
'IT Support', ':loc' => 1700);
foreach ($ba as $key => $val) {
// oci_bind_by_name($stid, $key, $val) does not work
// because it binds each placeholder to the same location: $val
// instead use the actual location of the data: $ba[$key]
oci_bind_by_name($stid, $key, $ba[$key]);
}
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
foreach ($row as $item) {
print $item." \n";
}
oci_free_statement($stid);
oci_close($conn);
?>
Example #4 Binding in a WHERE clause
\n";
// Output is
// Kochhar
oci_free_statement($stid);
oci_close($conn);
?>
Example #5 Binding with a LIKE clause
\n";
}
// Output is
// South Brunswick
// South San Francisco
// Southlake
oci_free_statement($stid);
oci_close($conn);
?>
Example #6 Binding with REGEXP_LIKE
\n";
}
// Output is
// Beijing
// Singapore
oci_free_statement($stid);
oci_close($conn);
?>
For a small, fixed number of IN clause conditions, use individual bind
variables. Values unknown at run time can be set to NULL. This allows a
single statement to be used by all application users, maximizing Oracle DB
cache efficiency.
Example #7 Binding Multiple Values in an IN Clause
\n";
}
// Output is
// Ernst
// Hunold
oci_free_statement($stid);
oci_close($conn);
?>
Example #8 Binding a ROWID returned by a query
Example #9 Binding a ROWID on INSERT
"Larry",
2222 => "Bill",
3333 => "Jim");
// Salary of each person
$salary = 10000;
// Insert and immediately update each row
foreach ($data as $id => $name) {
oci_execute($ins_stid);
oci_execute($upd_stid);
}
$rowid->free();
oci_free_statement($upd_stid);
oci_free_statement($ins_stid);
// Show the new rows
$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid);
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
var_dump($row);
}
oci_free_statement($stid);
oci_close($conn);
?>
Example #10 Binding for a PL/SQL stored function
Example #11 Binding parameters for a PL/SQL stored procedure
Example #12 Binding a CLOB column
save("A very long string");
oci_commit($conn);
// Fetching CLOB data
$query = 'SELECT myclob FROM mytab WHERE mykey = :mykey';
$stid = oci_parse ($conn, $query);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_execute($stid);
print '';
while ($row = oci_fetch_array($stid, OCI_ASSOC)) {
$result = $row['MYCLOB']->load();
print ''.$result.' ';
}
print '
';
?>
Return Values
Returns TRUE on success or FALSE on failure.
Notes
Warning
Do not use magic_quotes_gpc or addslashes() and oci_bind_by_name()
simultaneously as no quoting is needed. Any magically applied quotes will
be written into your database because oci_bind_by_name() inserts data
verbatim and does not remove quotes or escape characters.
Note:
If you bind a string to a CHAR column in a WHERE clause, remember that
Oracle uses blank-padded comparison semantics for CHAR columns. Your PHP
variable should be blank padded to the same width as the column for the
WHERE clause to succeed.
Note:
The PHP variable argument is a reference. Some forms of loops do not
work as expected:
$value) {
oci_bind_by_name($stid, $key, $value);
}
?>
This binds each key to the location of $value, so all bound variables
end up pointing to the last loop iteration's value. Instead use the
following:
$value) {
oci_bind_by_name($stid, $key, $myarray[$key]);
}
?>
Note:
In PHP versions before 5.0.0 you must use ocibindbyname() instead. The
old function name can still be used in current versions, however it is
deprecated and not recommended.
See Also
* oci_bind_array_by_name() - Binds a PHP array to an Oracle PL/SQL array
parameter
* oci_parse() - Prepares an Oracle statement for execution
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_cancel
(PHP 5, PECL OCI8 >= 1.1.0)
oci_cancel - Cancels reading from cursor
Description
bool oci_cancel ( resource $statement )
Invalidates a cursor, freeing all associated resources and cancels the
ability to read from it.
Parameters
statement
An OCI statement.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_client_version
(PHP 5.3.7, PECL OCI8 >= 1.4.6)
oci_client_version - Returns the Oracle client library version
Description
string oci_client_version ( void )
Returns a string containing the version number of the Oracle C client
library that PHP is linked with.
Parameters
None
Return Values
Returns the version number as a string.
Examples
Example #1 oci_client_version() example
Notes
Note:
Oracle libraries before 10gR2 do not have the underlying functionality
to get the client library version number. The string "Unknown" will be
returned in this case.
See Also
* oci_server_version() - Returns the Oracle Database version
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_close
(PHP 5, PECL OCI8 >= 1.1.0)
oci_close - Closes an Oracle connection
Description
bool oci_close ( resource $connection )
Unsets connection. The underlying database connection is closed if no
other resources are using it and if it was created with oci_connect() or
oci_new_connect().
It is recommended to close connections that are no longer needed because
this makes database resources available for other users.
Parameters
connection
An Oracle connection identifier returned by oci_connect(),
oci_pconnect(), or oci_new_connect().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Closing a connection
Resources associated with a connection should be closed to ensure the
underlying database connection is properly terminated and the database
resources are released.
Example #2 Database connections are not closed until all references are
closed
The internal refcount of a connection identifier must be zero before the
underlying connection to the database is closed.
Example #3 Closing a connection opened more than once
When database credentials are reused, both connections must be closed
before the underlying database connection is closed.
Example #4 Connections are closed when variables go out of scope
When all variables referencing a connection go out of scope and are freed
by PHP, a rollback occurs (if necessary) and the underlying connection to
the database is closed.
Notes
Note:
Variables that have a dependency on the connection identifier, such as
statement identifiers returned by oci_parse(), must also be freed before
the underlying database connection is closed.
Note:
Prior to version PHP 5.1.2 (PECL OCI8 1.1) oci_close() was a no-op. In
more recent versions it correctly closes the Oracle connection. Use
oci8.old_oci_close_semantics option to restore old behavior of this
function.
Note:
The oci_close() function does not close the underlying database
connections created with oci_pconnect().
Note:
In PHP versions before 5.0.0 you must use ocilogoff() instead. The old
function name can still be used in current versions, however it is
deprecated and not recommended.
See Also
* oci_connect() - Connect to an Oracle database
* oci_free_statement() - Frees all resources associated with statement
or cursor
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Collection->append
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Collection->append - Appends element to the collection
Description
bool OCI-Collection::append ( mixed $value )
Appends element to the end of the collection.
Parameters
value
The value to be added to the collection. Can be a string or a
number.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* OCI-Collection->assign
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Collection->assign
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Collection->assign - Assigns a value to the collection from another
existing collection
Description
bool OCI-Collection::assign ( OCI-Collection $from )
Assigns a value to the collection from another, previously created
collection. Both collections must be created with oci_new_collection()
prior to using them.
Parameters
from
An instance of OCI-Collection.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* OCI-Collection->append
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Collection->assignElem
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Collection->assignElem - Assigns a value to the element of the
collection
Description
bool OCI-Collection::assignElem ( int $index , mixed $value )
Assigns a value to the element with index index.
Parameters
index
The element index. First index is 1.
value
Can be a string or a number.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* OCI-Collection->getElem
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Collection->free
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Collection->free - Frees the resources associated with the collection
object
Description
bool OCI-Collection::free ( void )
Frees the resources associated with the collection object.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* oci_new_collection
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Collection->getElem
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Collection->getElem - Returns value of the element
Description
mixed OCI-Collection::getElem ( int $index )
Returns element's value with the index index (1-based).
Parameters
index
The element index. First index is 1.
Return Values
Returns FALSE if such element doesn't exist; NULL if element is NULL;
string if element is column of a string datatype or number if element is
numeric field.
See Also
* OCI-Collection->assignElem
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Collection->max
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Collection->max - Returns the maximum number of elements in the
collection
Description
int OCI-Collection::max ( void )
Returns the maximum number of elements in the collection.
Return Values
Returns the maximum number as an integer, or FALSE on errors.
If the returned value is 0, then the number of elements is not limited.
See Also
* OCI-Collection->size
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Collection->size
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Collection->size - Returns size of the collection
Description
int OCI-Collection::size ( void )
Returns the size of the collection.
Return Values
Returns the number of elements in the collection or FALSE on error.
See Also
* OCI-Collection->max
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Collection->trim
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Collection->trim - Trims elements from the end of the collection
Description
bool OCI-Collection::trim ( int $num )
Trims num of elements from the end of the collection.
Parameters
num
The number of elements to be trimmed.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* OCI-Collection->size
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_commit
(PHP 5, PECL OCI8 >= 1.1.0)
oci_commit - Commits the outstanding database transaction
Description
bool oci_commit ( resource $connection )
Commits the outstanding transaction for the Oracle connection. A commit
ends the current transaction and makes permanent all changes. It releases
all locks held.
A transaction begins when the first SQL statement that changes data is
executed with oci_execute() using the OCI_NO_AUTO_COMMIT flag. Further
data changes made by other statements become part of the same transaction.
Data changes made in a transaction are temporary until the transaction is
committed or rolled back. Other users of the database will not see the
changes until they are committed.
When inserting or updating data, using transactions is recommended for
relational data consistency and for performance reasons.
Parameters
connection
An Oracle connection identifier, returned by oci_connect(),
oci_pconnect(), or oci_new_connect().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 oci_commit() example
Notes
Note:
Transactions are automatically rolled back when you close the
connection, or when the script ends, whichever is soonest. You need to
explicitly call oci_commit() to commit the transaction.
Any call to oci_execute() that uses OCI_COMMIT_ON_SUCCESS mode
explicitly or by default will commit any previous uncommitted
transaction.
Any Oracle DDL statement such as CREATE or DROP will automatically
commit any uncommitted transaction.
Note:
In PHP versions before 5.0.0 you must use ocicommit() instead. The old
function name can still be used in current versions, however it is
deprecated and not recommended.
See Also
* oci_execute() - Executes a statement
* oci_rollback() - Rolls back the outstanding database transaction
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_connect
(PHP 5, PECL OCI8 >= 1.1.0)
oci_connect - Connect to an Oracle database
Description
resource oci_connect ( string $username , string $password [, string
$connection_string [, string $character_set [, int $session_mode ]]] )
Returns a connection identifier needed for most other OCI8 operations.
See Connection Handling for general information on connection management
and connection pooling.
From PHP 5.1.2 (PECL OCI8 1.1) oci_close() can be used to close the
connection.
The second and subsequent calls to oci_connect() with the same parameters
will return the connection handle returned from the first call. This means
that transactions in one handle are also in the other handles, because
they use the same underlying database connection. If two handles need to
be transactionally isolated from each other, use oci_new_connect()
instead.
Parameters
username
The Oracle user name.
password
The password for username.
connection_string
Contains the Oracle instance to connect to. It can be an >> Easy
Connect string, or a Connect Name from the tnsnames.ora file, or
the name of a local Oracle instance.
If not specified, PHP uses environment variables such as TWO_TASK
(on Linux) or LOCAL (on Windows) and ORACLE_SID to determine the
Oracle instance to connect to.
To use the Easy Connect naming method, PHP must be linked with
Oracle 10g or greater Client libraries. The Easy Connect string
for Oracle 10g is of the form:
[//]host_name[:port][/service_name]. With Oracle 11g, the syntax
is:
[//]host_name[:port][/service_name][:server_type][/instance_name].
Service names can be found by running the Oracle utility lsnrctl
status on the database server machine.
The tnsnames.ora file can be in the Oracle Net search path, which
includes $ORACLE_HOME/network/admin and /etc. Alternatively set
TNS_ADMIN so that $TNS_ADMIN/tnsnames.ora is read. Make sure the
web daemon has read access to the file.
character_set
Determines the character set used by the Oracle Client libraries.
The character set does not need to match the character set used by
the database. If it doesn't match, Oracle will do its best to
convert data to and from the database character set. Depending on
the character sets this may not give usable results. Conversion
also adds some time overhead.
If not specified, the Oracle Client libraries determine a
character set from the NLS_LANG environment variable.
Passing this parameter can reduce connection time.
session_mode
This parameter is available since version PHP 5 (PECL OCI8 1.1)
and accepts the following values: OCI_DEFAULT, OCI_SYSOPER and
OCI_SYSDBA. If either OCI_SYSOPER or OCI_SYSDBA were specified,
this function will try to establish privileged connection using
external credentials. Privileged connections are disabled by
default. To enable them you need to set oci8.privileged_connect to
On.
PHP 5.3 (PECL OCI8 1.3.4) introduced the OCI_CRED_EXT mode value.
This tells Oracle to use External or OS authentication, which must
be configured in the database. The OCI_CRED_EXT flag can only be
used with username of "/" and a empty password.
oci8.privileged_connect may be On or Off.
OCI_CRED_EXT may be combined with the OCI_SYSOPER or OCI_SYSDBA
modes.
OCI_CRED_EXT is not supported on Windows for security reasons.
Return Values
Returns a connection identifier or FALSE on error.
Examples
Example #1 Basic oci_connect() using Easy Connect syntax
\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "\n";
foreach ($row as $item) {
echo " " . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . " \n";
}
echo " \n";
}
echo "\n";
?>
Example #2 Basic oci_connect() using a Network Connect name
\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "\n";
foreach ($row as $item) {
echo " " . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . " \n";
}
echo " \n";
}
echo "\n";
?>
Example #3 oci_connect() with an explicit character set
\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "\n";
foreach ($row as $item) {
echo " " . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . " \n";
}
echo " \n";
}
echo "\n";
?>
Example #4 Using multiple calls to oci_connect()
\n";
echo "c2 is $c2 \n";
function create_table($conn)
{
$stmt = oci_parse($conn, "create table hallo (test varchar2(64))");
oci_execute($stmt);
echo "Created table \n";
}
function drop_table($conn)
{
$stmt = oci_parse($conn, "drop table hallo");
oci_execute($stmt);
echo "Dropped table \n";
}
function insert_data($connname, $conn)
{
$stmt = oci_parse($conn, "insert into hallo
values(to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
oci_execute($stmt, OCI_DEFAULT);
echo "$connname inserted row without committing \n";
}
function rollback($connname, $conn)
{
oci_rollback($conn);
echo "$connname rollback \n";
}
function select_data($connname, $conn)
{
$stmt = oci_parse($conn, "select * from hallo");
oci_execute($stmt, OCI_DEFAULT);
echo "$connname ----selecting \n";
while (oci_fetch($stmt)) {
echo " " . oci_result($stmt, "TEST") . " \n";
}
echo "$connname ----done \n";
}
create_table($c1);
insert_data('c1', $c1); // Insert a row using c1
sleep(2); // sleep to show a different timestamp for the 2nd row
insert_data('c2', $c2); // Insert a row using c2
select_data('c1', $c1); // Results of both inserts are returned
select_data('c2', $c2); // Results of both inserts are returned
rollback('c1', $c1); // Rollback using c1
select_data('c1', $c1); // Both inserts have been rolled back
select_data('c2', $c2);
drop_table($c1);
// Closing one of the connections makes the PHP variable unusable, but
// the other could be used
oci_close($c1);
echo "c1 is $c1 \n";
echo "c2 is $c2 \n";
// Output is:
// c1 is Resource id #5
// c2 is Resource id #5
// Created table
// c1 inserted row without committing
// c2 inserted row without committing
// c1 ----selecting
// 09-DEC-09 12:14:43
// 09-DEC-09 12:14:45
// c1 ----done
// c2 ----selecting
// 09-DEC-09 12:14:43
// 09-DEC-09 12:14:45
// c2 ----done
// c1 rollback
// c1 ----selecting
// c1 ----done
// c2 ----selecting
// c2 ----done
// Dropped table
// c1 is
// c2 is Resource id #5
?>
Notes
Note:
An incorrectly installed or configured OCI8 extension will often
manifest itself as a connection problem or error. See
Installing/Configuring for troubleshooting information.
Note:
In PHP versions before 5.0.0 use ocilogon() instead. The old function
name can still be used in current versions, however it is deprecated and
not recommended.
See Also
* oci_pconnect() - Connect to an Oracle database using a persistent
connection
* oci_new_connect() - Connect to the Oracle server using a unique
connection
* oci_close() - Closes an Oracle connection
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_define_by_name
(PHP 5, PECL OCI8 >= 1.1.0)
oci_define_by_name - Associates a PHP variable with a column for query
fetches
Description
bool oci_define_by_name ( resource $statement , string $column_name ,
mixed &$variable [, int $type = SQLT_CHR ] )
Associates a PHP variable with a column for query fetches using
oci_fetch().
The oci_define_by_name() call must occur before executing oci_execute().
Parameters
statement
A valid OCI8 statement identifier created by oci_parse() and
executed by oci_execute(), or a REF CURSOR statement identifier.
column_name
The column name used in the query.
Use uppercase for Oracle's default, non-case sensitive column
names. Use the exact column name case for case-sensitive column
names.
variable
The PHP variable that will contain the returned column value.
type
The data type to be returned. Generally not needed. Note that
Oracle-style data conversions are not performed. For example,
SQLT_INT will be ignored and the returned data type will still be
SQLT_CHR.
You can optionally use oci_new_descriptor() to allocate
LOB/ROWID/BFILE descriptors.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 oci_define_by_name() example
\n";
}
// Displays:
// Location id 1000 is Roma
// Location id 1100 is Venice
oci_free_statement($stid);
oci_close($conn);
?>
Example #2 oci_define_by_name() with case sensitive column names
\n";
}
// Displays:
// id 1 is Iced Coffee
oci_free_statement($stid);
oci_close($conn);
?>
Example #3 oci_define_by_name() with LOB columns
load(100) . " \n";
}
// Displays:
// 1 is apple
// 2 is orange
$fruit->free();
oci_free_statement($stid);
oci_close($conn);
?>
Example #4 oci_define_by_name() with an explicit type
load(100) . " \n";
}
// Displays:
// 1 is apple
// 2 is orange
$fruit->free();
oci_free_statement($stid);
oci_close($conn);
?>
Notes
Note:
In PHP versions before 5.0.0 use ocidefinebyname() instead. The old
function name can still be used in current versions, however it is
deprecated and not recommended.
See Also
* oci_fetch() - Fetches the next row from a query into internal buffers
* oci_new_descriptor() - Initializes a new empty LOB or FILE descriptor
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_error
(PHP 5, PECL OCI8 >= 1.1.0)
oci_error - Returns the last error found
Description
array oci_error ([ resource $resource ] )
Returns the last error found.
The function should be called immediately after an error occurs. Errors
are cleared by a successful statement.
Parameters
resource
For most errors, resource is the resource handle that was passed
to the failing function call. For connection errors with
oci_connect(), oci_new_connect() or oci_pconnect() do not pass
resource.
Return Values
If no error is found, oci_error() returns FALSE. Otherwise, oci_error()
returns the error information as an associative array.
oci_error() Array Description
Array key Type Description
code integer The Oracle error number.
message string The Oracle error text.
offset integer The byte position of an error in the SQL statement. If
there was no statement, this is 0
sqltext string The SQL statement text. If there was no statement, this
is an empty string.
Changelog
Version Description
4.3.0 The offset and sqltext entries were added.
Examples
Example #1 Displaying the Oracle error message after a connection error
Example #2 Displaying the Oracle error message after a parsing error
Example #3 Displaying the Oracle error message, the problematic statement,
and the position of the problem of an execution error
\n";
print htmlentities($e['sqltext']);
printf("\n%".($e['offset']+1)."s", "^");
print "\n\n";
}
?>
Notes
Note:
In PHP versions before 5.0.0 you must use ocierror() instead. The old
function name can still be used in current versions, however it is
deprecated and not recommended.
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_execute
(PHP 5, PECL OCI8 >= 1.1.0)
oci_execute - Executes a statement
Description
bool oci_execute ( resource $statement [, int $mode =
OCI_COMMIT_ON_SUCCESS ] )
Executes a statement previously returned from oci_parse().
After execution, statements like INSERT will have data committed to the
database by default. For statements like SELECT, execution performs the
logic of the query. Query results can subsequently be fetched in PHP with
functions like oci_fetch_array().
Each parsed statement may be executed multiple times, saving the cost of
re-parsing. This is commonly used for INSERT statements when data is bound
with oci_bind_by_name().
Parameters
statement
A valid OCI statement identifier.
mode
An optional second parameter can be one of the following
constants:
Execution Modes
Constant Description
Automatically commit all outstanding changes
OCI_COMMIT_ON_SUCCESS for this connection when the statement has
succeeded. This is the default.
Obsolete as of PHP 5.3.2 (PECL OCI8 1.4) but
OCI_DEFAULT still available for backward compatibility.
Use the equivalent OCI_NO_AUTO_COMMIT in new
code.
Make query meta data available to functions
OCI_DESCRIBE_ONLY like oci_field_name() but do not create a
result set. Any subsequent fetch call such
as oci_fetch_array() will fail.
Do not automatically commit changes. Prior
OCI_NO_AUTO_COMMIT to PHP 5.3.2 (PECL OCI8 1.4) use OCI_DEFAULT
which is an alias for OCI_NO_AUTO_COMMIT.
Using OCI_NO_AUTO_COMMIT mode starts a transaction. Transactions
are automatically rolled back when the connection is closed, or
when the script ends. Explicitly call oci_commit() to commit a
transaction, or oci_rollback() to abort it.
When inserting or updating data, using transactions is recommended
for relational data consistency and for performance reasons.
If OCI_NO_AUTO_COMMIT mode is used for any statement including
queries, and oci_commit() or oci_rollback() is not subsequently
called, then OCI8 will perform a rollback at the end of the script
even if no data was changed. To avoid an unnecessary rollback,
many scripts do not use OCI_NO_AUTO_COMMIT mode for queries or
PL/SQL. Be careful to ensure the appropriate transactional
consistency for the application when using oci_execute() with
different modes in the same script.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 oci_execute() for queries
\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "\n";
foreach ($row as $item) {
echo " " . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . " \n";
}
echo " \n";
}
echo "\n";
?>
Example #2 oci_execute() without specifying a mode example
Example #3 oci_execute() with OCI_NO_AUTO_COMMIT example
Example #4 oci_execute() with different commit modes example
Example #5 oci_execute() with OCI_DESCRIBE_ONLY example
\n";
}
?>
Notes
Note:
Transactions are automatically rolled back when connections are closed,
or when the script ends, whichever is soonest. Explicitly call
oci_commit() to commit a transaction.
Any call to oci_execute() that uses OCI_COMMIT_ON_SUCCESS mode
explicitly or by default will commit any previous uncommitted
transaction.
Any Oracle DDL statement such as CREATE or DROP will automatically
commit any uncommitted transaction.
Note:
Because the oci_execute() function generally sends the statement to the
database, oci_execute() can identify some statement syntax errors that
the lightweight, local oci_parse() function does not.
Note:
In PHP versions before 5.0.0 use ociexecute() instead. The old function
name can still be used in current versions, however it is deprecated and
not recommended.
See Also
* oci_parse() - Prepares an Oracle statement for execution
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_fetch_all
(PHP 5, PECL OCI8 >= 1.1.0)
oci_fetch_all - Fetches multiple rows from a query into a two-dimensional
array
Description
int oci_fetch_all ( resource $statement , array &$output [, int $skip = 0
[, int $maxrows = -1 [, int $flags = OCI_FETCHSTATEMENT_BY_COLUMN +
OCI_ASSOC ]]] )
Fetches multiple rows from a query into a two-dimensional array. By
default, all rows are returned.
This function can be called only once for each query executed with
oci_execute().
Parameters
statement
A valid OCI8 statement identifier created by oci_parse() and
executed by oci_execute(), or a REF CURSOR statement identifier.
output
The variable to contain the returned rows.
LOB columns are returned as strings, where Oracle supports
conversion.
See oci_fetch_array() for more information on how data and types
are fetched.
skip
The number of initial rows to discard when fetching the result.
The default value is 0, so the first row onwards is returned.
maxrows
The number of rows to return. The default is -1 meaning return all
the rows from skip + 1 onwards.
flags
Parameter flags indicates the array structure and whether
associative arrays should be used.
oci_fetch_all() Array Structure Modes
Constant Description
OCI_FETCHSTATEMENT_BY_ROW The outer array will contain one
sub-array per query row.
The outer array will contain one
OCI_FETCHSTATEMENT_BY_COLUMN sub-array per query column. This is
the default.
Arrays can be indexed by column heading or numerically.
oci_fetch_all() Array Index Modes
Constant Description
OCI_NUM Numeric indexes are used for each column's array.
OCI_ASSOC Associative indexes are used for each column's array.
This is the default.
Use the addition operator "+" to choose a combination of array
structure and index modes.
Oracle's default, non-case sensitive column names will have
uppercase array keys. Case-sensitive column names will have array
keys using the exact column case. Use var_dump() on outputto
verify the appropriate case to use for each query.
Queries that have more than one column with the same name should
use column aliases. Otherwise only one of the columns will appear
in an associative array.
Return Values
Returns the number of rows in output, which may be 0 or more, or FALSE on
failure.
Examples
Example #1 oci_fetch_all() example
\n";
var_dump($res);
// var_dump output is:
// 2 rows fetched
// array(2) {
// ["POSTAL_CODE"]=>
// array(2) {
// [0]=>
// string(6) "00989x"
// [1]=>
// string(6) "10934x"
// }
// ["CITY"]=>
// array(2) {
// [0]=>
// string(4) "Roma"
// [1]=>
// string(6) "Venice"
// }
// }
// Pretty-print the results
echo "\n";
foreach ($res as $col) {
echo "\n";
foreach ($col as $item) {
echo " ".($item !== null ? htmlentities($item, ENT_QUOTES) : " ")." \n";
}
echo " \n";
}
echo "
\n";
oci_free_statement($stid);
oci_close($conn);
?>
Example #2 oci_fetch_all() example with OCI_FETCHSTATEMENT_BY_ROW
\n";
var_dump($res);
// Output is:
// 2 rows fetched
// array(2) {
// [0]=>
// array(2) {
// ["POSTAL_CODE"]=>
// string(6) "00989x"
// ["CITY"]=>
// string(4) "Roma"
// }
// [1]=>
// array(2) {
// ["POSTAL_CODE"]=>
// string(6) "10934x"
// ["CITY"]=>
// string(6) "Venice"
// }
// }
oci_free_statement($stid);
oci_close($conn);
?>
Example #3 oci_fetch_all() with OCI_NUM
\n";
var_dump($res);
// Output is:
// 2 rows fetched
// array(2) {
// [0]=>
// array(2) {
// [0]=>
// string(6) "00989x"
// [1]=>
// string(4) "Roma"
// }
// [1]=>
// array(2) {
// [0]=>
// string(6) "10934x"
// [1]=>
// string(6) "Venice"
// }
// }
oci_free_statement($stid);
oci_close($conn);
?>
Notes
Note:
Using skip is very inefficient. All the rows to be skipped are included
in the result set that is returned from the database to PHP. They are
then discarded. It is more efficient to use SQL to restrict the offset
and range of rows in the query. See oci_fetch_array() for an example.
Note:
Queries that return a large number of rows can be more memory efficient
if a single-row fetching function like oci_fetch_array() is used.
Note:
For queries returning a large number of rows, performance can be
significantly improved by increasing oci8.default_prefetch or using
oci_set_prefetch().
Note:
In PHP versions before 5.0.0 you must use ocifetchstatement() instead.
The old function name can still be used in current versions, however it
is deprecated and not recommended.
See Also
* oci_fetch() - Fetches the next row from a query into internal buffers
* oci_fetch_array() - Returns the next row from a query as an
associative or numeric array
* oci_fetch_assoc() - Returns the next row from a query as an
associative array
* oci_fetch_object() - Returns the next row from a query as an object
* oci_fetch_row() - Returns the next row from a query as a numeric array
* oci_set_prefetch() - Sets number of rows to be prefetched by queries
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_fetch_array
(PHP 5, PECL OCI8 >= 1.1.0)
oci_fetch_array - Returns the next row from a query as an associative or
numeric array
Description
array oci_fetch_array ( resource $statement [, int $mode ] )
Returns an array containing the next result-set row of a query. Each array
entry corresponds to a column of the row. This function is typically
called in a loop until it returns FALSE, indicating no more rows exist.
For details on the data type mapping performed by the OCI8 extension, see
the datatypes supported by the driver
Parameters
statement
A valid OCI8 statement identifier created by oci_parse() and
executed by oci_execute(), or a REF CURSOR statement identifier.
mode
An optional second parameter can be any combination of the
following constants:
oci_fetch_array() Modes
Constant Description
Returns an array with both associative and
OCI_BOTH numeric indices. This is the same as OCI_ASSOC +
OCI_NUM and is the default behavior.
OCI_ASSOC Returns an associative array.
OCI_NUM Returns a numeric array.
OCI_RETURN_NULLS Creates elements for NULL fields. The element
values will be a PHP NULL.
OCI_RETURN_LOBS Returns the contents of LOBs instead of the LOB
descriptors.
The default mode is OCI_BOTH.
Use the addition operator "+" to specify more than one mode at a
time.
Return Values
Returns an array with associative and/or numeric indices. If there are no
more rows in the statement then FALSE is returned.
By default, LOB columns are returned as LOB descriptors.
DATE columns are returned as strings formatted to the current date format.
The default format can be changed with Oracle environment variables such
as NLS_LANG or by a previously executed ALTER SESSION SET NLS_DATE_FORMAT
command.
Oracle's default, non-case sensitive column names will have uppercase
associative indices in the result array. Case-sensitive column names will
have array indices using the exact column case. Use var_dump() on the
result array to verify the appropriate case to use for each query.
Examples
Example #1 oci_fetch_array() with OCI_BOTH
\n";
echo $row[1] . " and " . $row['DEPARTMENT_NAME'] . " are the same \n";
}
oci_free_statement($stid);
oci_close($conn);
?>
Example #2 oci_fetch_array() with OCI_NUM
\n";
echo $row[1]->read(11) . " \n"; // this will output first 11 bytes from DESCRIPTION
}
// Output is:
// 1
// A very long
oci_free_statement($stid);
oci_close($conn);
?>
Example #3 oci_fetch_array() with OCI_ASSOC
\n";
echo $row['DESCRIPTION']->read(11) . " \n"; // this will output first 11 bytes from DESCRIPTION
}
// Output is:
// 1
// A very long
oci_free_statement($stid);
oci_close($conn);
?>
Example #4 oci_fetch_array() with OCI_RETURN_NULLS
string(1) "1"
}
*/
$stid = oci_parse($conn, 'SELECT 1, null FROM dual');
oci_execute($stid);
while (($row = oci_fetch_array ($stid, OCI_ASSOC+OCI_RETURN_NULLS))) { // Fetch NULLs
var_dump($row);
}
/*
The above code prints:
array(2) {
[1]=>
string(1) "1"
["NULL"]=>
NULL
}
*/
?>
Example #5 oci_fetch_array() with OCI_RETURN_LOBS
\n";
echo $row['DESCRIPTION'] . " \n"; // this contains all of DESCRIPTION
}
// Output is:
// 1
// A very long string
oci_free_statement($stid);
oci_close($conn);
?>
Example #6 oci_fetch_array() with case sensitive column names
\n"; // prints Chris
print $row['CITY'] . " \n"; // prints Melbourne
oci_free_statement($stid);
oci_close($conn);
?>
Example #7 oci_fetch_array() with columns having duplicate names
// string(9) "Australia"
// }
// To query a repeated column name, use an SQL column alias like "AS ctnm":
$sql = 'SELECT mycity.name AS ctnm, mycountry.name
FROM mycity, mycountry
WHERE mycity.id = mycountry.id';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC);
var_dump($row);
// Output now contains both columns selected:
// array(2) {
// ["CTNM"]=>
// string(9) "Melbourne"
// ["NAME"]=>
// string(9) "Australia"
// }
oci_free_statement($stid);
oci_close($conn);
?>
Example #8 oci_fetch_array() with DATE columns
\n"; // prints 1997-06-14
oci_free_statement($stid);
oci_close($conn);
?>
Example #9 oci_fetch_array() with REF CURSOR
\n";
while ($row = oci_fetch_array($refcur, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "\n";
foreach ($row as $item) {
echo " ".($item !== null ? htmlentities($item, ENT_QUOTES) : " ")." \n";
}
echo " \n";
}
echo "\n";
oci_free_statement($refcur);
oci_free_statement($stid);
oci_close($conn);
?>
Example #10 oci_fetch_array() with a LIMIT-like query
= :FIRST_ROW';
$first = 1; // start with the first row
$num = 5; // return 5 rows
$stid = oci_parse($conn, $limit_sql);
oci_bind_by_name($stid, ':FIRST_ROW', $first);
oci_bind_by_name($stid, ':NUM_ROWS', $num);
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_ASSOC))) {
echo $row['CITY'] . " " . $row['POSTAL_CODE'] . " \n";
}
// Output is:
// Beijing 190518x
// Bern 3095x
// Bombay 490231x
// Geneva 1730x
// Hiroshima 6823x
oci_free_statement($stid);
oci_close($conn);
?>
Notes
Note:
Associative array indices need to be in uppercase for standard Oracle
columns that were created with case insensitive names.
Note:
For queries returning a large number of rows, performance can be
significantly improved by increasing oci8.default_prefetch or using
oci_set_prefetch().
Note:
The function oci_fetch_array() is insignificantly slower than
oci_fetch_assoc() or oci_fetch_row(), but is more flexible.
See Also
* oci_fetch() - Fetches the next row from a query into internal buffers
* oci_fetch_all() - Fetches multiple rows from a query into a
two-dimensional array
* oci_fetch_assoc() - Returns the next row from a query as an
associative array
* oci_fetch_object() - Returns the next row from a query as an object
* oci_fetch_row() - Returns the next row from a query as a numeric array
* oci_set_prefetch() - Sets number of rows to be prefetched by queries
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_fetch_assoc
(PHP 5, PECL OCI8 >= 1.1.0)
oci_fetch_assoc - Returns the next row from a query as an associative
array
Description
array oci_fetch_assoc ( resource $statement )
Returns an associative array containing the next result-set row of a
query. Each array entry corresponds to a column of the row. This function
is typically called in a loop until it returns FALSE, indicating no more
rows exist.
Calling oci_fetch_assoc() is identical to calling oci_fetch_array() with
OCI_ASSOC + OCI_RETURN_NULLS.
Parameters
statement
A valid OCI8 statement identifier created by oci_parse() and
executed by oci_execute(), or a REF CURSOR statement identifier.
Return Values
Returns an associative array. If there are no more rows in the statement
then FALSE is returned.
Notes
Note:
See oci_fetch_array() for examples of fetching rows.
See Also
* oci_fetch() - Fetches the next row from a query into internal buffers
* oci_fetch_all() - Fetches multiple rows from a query into a
two-dimensional array
* oci_fetch_array() - Returns the next row from a query as an
associative or numeric array
* oci_fetch_object() - Returns the next row from a query as an object
* oci_fetch_row() - Returns the next row from a query as a numeric array
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_fetch_object
(PHP 5, PECL OCI8 >= 1.1.0)
oci_fetch_object - Returns the next row from a query as an object
Description
object oci_fetch_object ( resource $statement )
Returns an object containing the next result-set row of a query. Each
attribute of the object corresponds to a column of the row. This function
is typically called in a loop until it returns FALSE, indicating no more
rows exist.
For details on the data type mapping performed by the OCI8 extension, see
the datatypes supported by the driver
Parameters
statement
A valid OCI8 statement identifier created by oci_parse() and
executed by oci_execute(), or a REF CURSOR statement identifier.
Return Values
Returns an object. Each attribute of the object corresponds to a column of
the row. If there are no more rows in the statement then FALSE is
returned.
Any LOB columns are returned as LOB descriptors.
DATE columns are returned as strings formatted to the current date format.
The default format can be changed with Oracle environment variables such
as NLS_LANG or by a previously executed ALTER SESSION SET NLS_DATE_FORMAT
command.
Oracle's default, non-case sensitive column names will have uppercase
attribute names. Case-sensitive column names will have attribute names
using the exact column case. Use var_dump() on the result object to verify
the appropriate case to use for each query.
Attribute values will be NULL for any NULL data fields.
Examples
Example #1 oci_fetch_object() example
ID . " \n";
echo $row->DESCRIPTION . " \n";
}
// Output is:
// 1
// Fish and Chips
oci_free_statement($stid);
oci_close($conn);
?>
Example #2 oci_fetch_object() with case sensitive column names
ID . " \n";
// Use the exact case for the case sensitive column name
echo $row->MyDescription . " \n";
}
// Output is:
// 1
// Iced Coffee
oci_free_statement($stid);
oci_close($conn);
?>
Example #3 oci_fetch_object() with LOBs
ID . " \n";
// The following will output the first 11 bytes from DESCRIPTION
echo $row->DESCRIPTION->read(11) . " \n";
}
// Output is:
// 1
// A very long
oci_free_statement($stid);
oci_close($conn);
?>
See Also
* oci_fetch() - Fetches the next row from a query into internal buffers
* oci_fetch_all() - Fetches multiple rows from a query into a
two-dimensional array
* oci_fetch_assoc() - Returns the next row from a query as an
associative array
* oci_fetch_array() - Returns the next row from a query as an
associative or numeric array
* oci_fetch_row() - Returns the next row from a query as a numeric array
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_fetch_row
(PHP 5, PECL OCI8 >= 1.1.0)
oci_fetch_row - Returns the next row from a query as a numeric array
Description
array oci_fetch_row ( resource $statement )
Returns a numerically indexed array containing the next result-set row of
a query. Each array entry corresponds to a column of the row. This
function is typically called in a loop until it returns FALSE, indicating
no more rows exist.
Calling oci_fetch_row() is identical to calling oci_fetch_array() with
OCI_NUM + OCI_RETURN_NULLS.
Parameters
statement
A valid OCI8 statement identifier created by oci_parse() and
executed by oci_execute(), or a REF CURSOR statement identifier.
Return Values
Returns a numerically indexed array. If there are no more rows in the
statement then FALSE is returned.
Notes
Note:
See oci_fetch_array() for examples of fetching rows.
See Also
* oci_fetch() - Fetches the next row from a query into internal buffers
* oci_fetch_all() - Fetches multiple rows from a query into a
two-dimensional array
* oci_fetch_array() - Returns the next row from a query as an
associative or numeric array
* oci_fetch_assoc() - Returns the next row from a query as an
associative array
* oci_fetch_object() - Returns the next row from a query as an object
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_fetch
(PHP 5, PECL OCI8 >= 1.1.0)
oci_fetch - Fetches the next row from a query into internal buffers
Description
bool oci_fetch ( resource $statement )
Fetches the next row from a query into internal buffers accessible either
with oci_result(), or by using variables previously defined with
oci_define_by_name().
See oci_fetch_array() for general information about fetching data.
Parameters
statement
A valid OCI8 statement identifier created by oci_parse() and
executed by oci_execute(), or a REF CURSOR statement identifier.
Return Values
Returns TRUE on success or FALSE if there are no more rows in the
statement.
Examples
Example #1 oci_fetch() with defined variables
\n";
}
// Displays:
// Location id 1000 is Roma
// Location id 1100 is Venice
oci_free_statement($stid);
oci_close($conn);
?>
Example #2 oci_fetch() with oci_result()
\n";
}
// Displays:
// 1000 is Roma
// 1100 is Venice
oci_free_statement($stid);
oci_close($conn);
?>
Notes
Note:
In PHP versions before 5.0.0 use ocifetch() instead. The old function
name can still be used in current versions, however it is deprecated and
not recommended.
See Also
* oci_define_by_name() - Associates a PHP variable with a column for
query fetches
* oci_fetch_all() - Fetches multiple rows from a query into a
two-dimensional array
* oci_fetch_array() - Returns the next row from a query as an
associative or numeric array
* oci_fetch_assoc() - Returns the next row from a query as an
associative array
* oci_fetch_object() - Returns the next row from a query as an object
* oci_fetch_row() - Returns the next row from a query as a numeric array
* oci_result() - Returns field's value from the fetched row
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_field_is_null
(PHP 5, PECL OCI8 >= 1.1.0)
oci_field_is_null - Checks if the field is NULL
Description
bool oci_field_is_null ( resource $statement , mixed $field )
Checks if the given field from the statement is NULL.
Parameters
statement
A valid OCI statement identifier.
field
Can be a field's index or a field's name (uppercased).
Return Values
Returns TRUE if field is NULL, FALSE otherwise.
Notes
Note:
In PHP versions before 5.0.0 you must use ocicolumnisnull() instead.
This name still can be used, it was left as alias of oci_field_is_null()
for downwards compatability. This, however, is deprecated and not
recommended.
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_field_name
(PHP 5, PECL OCI8 >= 1.1.0)
oci_field_name - Returns the name of a field from the statement
Description
string oci_field_name ( resource $statement , int $field )
Returns the name of the field.
Parameters
statement
A valid OCI statement identifier.
field
Can be the field's index (1-based) or name.
Return Values
Returns the name as a string, or FALSE on errors.
Examples
Example #1 oci_field_name() example
";
echo "";
echo "Name ";
echo "Type ";
echo "Length ";
echo " ";
$ncols = oci_num_fields($stmt);
for ($i = 1; $i <= $ncols; $i++) {
$column_name = oci_field_name($stmt, $i);
$column_type = oci_field_type($stmt, $i);
$column_size = oci_field_size($stmt, $i);
echo "";
echo "$column_name ";
echo "$column_type ";
echo "$column_size ";
echo " ";
}
echo "\n";
oci_free_statement($stmt);
oci_close($conn);
?>
Notes
Note:
In PHP versions before 5.0.0 you must use ocicolumnname() instead. This
name still can be used, it was left as alias of oci_field_name() for
downwards compatability. This, however, is deprecated and not
recommended.
See Also
* oci_num_fields() - Returns the number of result columns in a statement
* oci_field_type() - Returns field's data type
* oci_field_size() - Returns field's size
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_field_precision
(PHP 5, PECL OCI8 >= 1.1.0)
oci_field_precision - Tell the precision of a field
Description
int oci_field_precision ( resource $statement , int $field )
Returns precision of the field.
For FLOAT columns, precision is nonzero and scale is -127. If precision is
0, then column is NUMBER. Else it's NUMBER(precision, scale).
Parameters
statement
A valid OCI statement identifier.
field
Can be the field's index (1-based) or name.
Return Values
Returns the precision as an integer, or FALSE on errors.
Notes
Note:
In PHP versions before 5.0.0 you must use ocicolumnprecision() instead.
This name still can be used, it was left as alias of
oci_field_precision() for downwards compatability. This, however, is
deprecated and not recommended.
See Also
* oci_field_scale() - Tell the scale of the field
* oci_field_type() - Returns field's data type
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_field_scale
(PHP 5, PECL OCI8 >= 1.1.0)
oci_field_scale - Tell the scale of the field
Description
int oci_field_scale ( resource $statement , int $field )
Returns the scale of the column with field index.
For FLOAT columns, precision is nonzero and scale is -127. If precision is
0, then column is NUMBER. Else it's NUMBER(precision, scale).
Parameters
statement
A valid OCI statement identifier.
field
Can be the field's index (1-based) or name.
Return Values
Returns the scale as an integer, or FALSE on errors.
Notes
Note:
In PHP versions before 5.0.0 you must use ocicolumnscale() instead. This
name still can be used, it was left as alias of oci_field_scale() for
downwards compatability. This, however, is deprecated and not
recommended.
See Also
* oci_field_precision() - Tell the precision of a field
* oci_field_type() - Returns field's data type
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_field_size
(PHP 5, PECL OCI8 >= 1.1.0)
oci_field_size - Returns field's size
Description
int oci_field_size ( resource $statement , mixed $field )
Returns the size of a field.
Parameters
statement
A valid OCI statement identifier.
field
Can be the field's index (1-based) or name.
Return Values
Returns the size of a field in bytes, or FALSE on errors.
Examples
Example #1 oci_field_size() example
";
echo "";
echo "Name ";
echo "Type ";
echo "Length ";
echo " ";
$ncols = oci_num_fields($stmt);
for ($i = 1; $i <= $ncols; $i++) {
$column_name = oci_field_name($stmt, $i);
$column_type = oci_field_type($stmt, $i);
$column_size = oci_field_size($stmt, $i);
echo "";
echo "$column_name ";
echo "$column_type ";
echo "$column_size ";
echo " ";
}
echo "";
oci_free_statement($stmt);
oci_close($conn);
?>
Notes
Note:
In PHP versions before 5.0.0 you must use ocicolumnsize() instead. This
name still can be used, it was left as alias of oci_field_size() for
downwards compatability. This, however, is deprecated and not
recommended.
See Also
* oci_num_fields() - Returns the number of result columns in a statement
* oci_field_name() - Returns the name of a field from the statement
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_field_type_raw
(PHP 5, PECL OCI8 >= 1.1.0)
oci_field_type_raw - Tell the raw Oracle data type of the field
Description
int oci_field_type_raw ( resource $statement , int $field )
Returns Oracle's raw data type of the field.
However, if you want to get field's type, then oci_field_type() will suit
you better.
Parameters
statement
A valid OCI statement identifier.
field
Can be the field's index (1-based) or name.
Return Values
Returns Oracle's raw data type as a string, or FALSE on errors.
Notes
Note:
In PHP versions before 5.0.0 you must use ocicolumntyperaw() instead.
This name still can be used, it was left as alias of
oci_field_type_raw() for downwards compatability. This, however, is
deprecated and not recommended.
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_field_type
(PHP 5, PECL OCI8 >= 1.1.0)
oci_field_type - Returns field's data type
Description
mixed oci_field_type ( resource $statement , int $field )
Returns a field's data type.
Parameters
statement
A valid OCI statement identifier.
field
Can be the field's index (1-based) or name.
Return Values
Returns the field data type as a string, or FALSE on errors.
Return Values
Example #1 oci_field_type() example
";
echo "";
echo "Name ";
echo "Type ";
echo "Length ";
echo " ";
$ncols = oci_num_fields($stmt);
for ($i = 1; $i <= $ncols; $i++) {
$column_name = oci_field_name($stmt, $i);
$column_type = oci_field_type($stmt, $i);
$column_size = oci_field_size($stmt, $i);
echo "";
echo "$column_name ";
echo "$column_type ";
echo "$column_size ";
echo " ";
}
echo "\n";
oci_free_statement($stmt);
oci_close($conn);
?>
Notes
Note:
In PHP versions before 5.0.0 you must use ocicolumntype() instead. This
name still can be used, it was left as alias of oci_field_type() for
downwards compatability. This, however, is deprecated and not
recommended.
See Also
* oci_num_fields() - Returns the number of result columns in a statement
* oci_field_name() - Returns the name of a field from the statement
* oci_field_size() - Returns field's size
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_free_statement
(PHP 5, PECL OCI8 >= 1.1.0)
oci_free_statement - Frees all resources associated with statement or
cursor
Description
bool oci_free_statement ( resource $statement )
Frees resources associated with Oracle's cursor or statement, which was
received from as a result of oci_parse() or obtained from Oracle.
Parameters
statement
A valid OCI statement identifier.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_internal_debug
(PHP 5, PECL OCI8 >= 1.1.0)
oci_internal_debug - Enables or disables internal debug output
Description
void oci_internal_debug ( bool $onoff )
Enables or disables internal debug output.
Parameters
onoff
Set this to FALSE to turn debug output off or TRUE to turn it on.
Return Values
No value is returned.
Notes
Note:
In PHP versions before 5.0.0 you must use ociinternaldebug() instead.
This name still can be used, it was left as alias of
oci_internal_debug() for downwards compatability. This, however, is
deprecated and not recommended.
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Lob->append
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Lob->append - Appends data from the large object to another large
object
Description
bool OCI-Lob::append ( OCI-Lob $lob_from )
Appends data from the large object to the end of another large object.
Writing to the large object with this method will fail if buffering was
previously enabled. You must disable buffering before appending. You may
need to flush buffers with OCI-Lob->flush before disabling buffering.
Parameters
lob_from
The copied LOB.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* OCI-Lob->flush
* OCI-Lob->setBuffering
* OCI-Lob->getBuffering
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Lob->close
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Lob->close - Closes LOB descriptor
Description
bool OCI-Lob::close ( void )
Closes descriptor of LOB or FILE. This function should be used only with
OCI-Lob->writeTemporary.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* OCI-Lob->writeTemporary
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_lob_copy
(PHP 5, PECL OCI8 >= 1.1.0)
oci_lob_copy - Copies large object
Description
bool oci_lob_copy ( OCI-Lob $lob_to , OCI-Lob $lob_from [, int $length = 0
] )
Copies a large object or a part of a large object to another large object.
Old LOB-recipient data will be overwritten.
If you need to copy a particular part of a LOB to a particular position of
a LOB, use oci_lob_seek() to move LOB internal pointers.
Parameters
lob_to
The destination LOB.
lob_from
The copied LOB.
length
Indicates the length of data to be copied.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Lob->eof
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Lob->eof - Tests for end-of-file on a large object's descriptor
Description
bool OCI-Lob::eof ( void )
Tells whether the internal pointer of large object is at the end of LOB.
Return Values
Returns TRUE if internal pointer of large object is at the end of LOB.
Otherwise returns FALSE.
See Also
* OCI-Lob->size
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Lob->erase
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Lob->erase - Erases a specified portion of the internal LOB data
Description
int OCI-Lob::erase ([ int $offset [, int $length ]] )
Erases a specified portion of the internal LOB data starting at a
specified offset. If called without parameters, it erases all LOB data.
For BLOBs, erasing means that the existing LOB value is overwritten with
zero-bytes. For CLOBs, the existing LOB value is overwritten with spaces.
Parameters
offset
length
Return Values
Returns the actual number of characters/bytes erased or FALSE on failure.
See Also
* OCI-Lob->truncate
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Lob->export
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Lob->export - Exports LOB's contents to a file
Description
bool OCI-Lob::export ( string $filename [, int $start [, int $length ]] )
Exports LOB contents to a file.
Parameters
filename
Path to the file.
start
Indicates from where to start exporting.
length
Indicates the length of data to be exported.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* OCI-Lob->import
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Lob->flush
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Lob->flush - Flushes/writes buffer of the LOB to the server
Description
bool OCI-Lob::flush ([ int $flag ] )
OCI-Lob->flush() actually writes data to the server.
Parameters
flag
By default, resources are not freed, but using flag
OCI_LOB_BUFFER_FREE you can do it explicitly. Be sure you know
what you're doing - next read/write operation to the same part of
LOB will involve a round-trip to the server and initialize new
buffer resources. It is recommended to use OCI_LOB_BUFFER_FREE
flag only when you are not going to work with the LOB anymore.
Return Values
Returns TRUE on success or FALSE on failure.
Returns FALSE if buffering was not enabled or an error occurred.
See Also
* OCI-Lob->getBuffering
* OCI-Lob->setBuffering
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Lob->free
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Lob->free - Frees resources associated with the LOB descriptor
Description
bool OCI-Lob::free ( void )
Frees resources associated with the descriptor, previously allocated with
oci_new_descriptor().
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Lob->getBuffering
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Lob->getBuffering - Returns current state of buffering for the large
object
Description
bool OCI-Lob::getBuffering ( void )
Tells whether the buffering for the large object is on or off.
Return Values
Returns FALSE if buffering for the large object is off and TRUE if
buffering is used.
See Also
* OCI-Lob->setBuffering
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Lob->import
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Lob->import - Imports file data to the LOB
Description
bool OCI-Lob::import ( string $filename )
Writes data from the filename in to the current position of large object.
Parameters
filename
Path to the file.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* OCI-Lob->export
* OCI-Lob->write
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_lob_is_equal
(PHP 5, PECL OCI8 >= 1.1.0)
oci_lob_is_equal - Compares two LOB/FILE locators for equality
Description
bool oci_lob_is_equal ( OCI-Lob $lob1 , OCI-Lob $lob2 )
Compares two LOB/FILE locators.
Parameters
lob1
A LOB identifier.
lob2
A LOB identifier.
Return Values
Returns TRUE if these objects are equal, FALSE otherwise.
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Lob->load
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Lob->load - Returns large object's contents
Description
string OCI-Lob::load ( void )
Returns large object's contents. As script execution is terminated when
the memory_limit is reached, ensure that the LOB does not exceed this
limit. In most cases it's recommended to use OCI-Lob->read instead.
Return Values
Returns the contents of the object, or FALSE on errors.
See Also
* OCI-Lob->read
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Lob->read
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Lob->read - Reads part of the large object
Description
string OCI-Lob::read ( int $length )
Reads length bytes from the current position of LOB's internal pointer.
Reading stops when length bytes have been read or end of the large object
is reached. Internal pointer of the large object will be shifted on the
amount of bytes read.
Parameters
length
The length of data to read, in bytes.
Return Values
Returns the contents as a string, or FALSE on failure.
See Also
* OCI-Lob->load
* OCI-Lob->write
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Lob->rewind
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Lob->rewind - Moves the internal pointer to the beginning of the large
object
Description
bool OCI-Lob::rewind ( void )
Sets the internal pointer to the beginning of the large object.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* OCI-Lob->seek
* OCI-Lob->tell
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Lob->save
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Lob->save - Saves data to the large object
Description
bool OCI-Lob::save ( string $data [, int $offset ] )
Saves data to the large object.
Parameters
data
The data to be saved.
offset
Can be used to indicate offset from the beginning of the large
object.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* OCI-Lob->write
* OCI-Lob->import
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Lob->saveFile
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Lob->saveFile - Alias of oci_lob_import()
Description
This function is an alias of: oci_lob_import().
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Lob->seek
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Lob->seek - Sets the internal pointer of the large object
Description
bool OCI-Lob::seek ( int $offset [, int $whence = OCI_SEEK_SET ] )
Sets the internal pointer of the large object.
Parameters
offset
Indicates the amount of bytes, on which internal pointer should be
moved from the position, pointed by whence.
whence
May be one of:
* OCI_SEEK_SET - sets the position equal to offset
* OCI_SEEK_CUR - adds offset bytes to the current position
* OCI_SEEK_END - adds offset bytes to the end of large object
(use negative value to move to a position before the end of
large object)
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* OCI-Lob->rewind
* OCI-Lob->tell
* OCI-Lob->eof
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Lob->setBuffering
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Lob->setBuffering - Changes current state of buffering for the large
object
Description
bool OCI-Lob::setBuffering ( bool $on_off )
Sets the buffering for the large object, depending on the value of the
on_off parameter.
Use of this function may provide performance improvements by buffering
small reads and writes of LOBs by reducing the number of network
round-trips and LOB versions. oci_lob_flush() should be used to flush
buffers, when you have finished working with the large object.
Parameters
on_off
TRUE for on and FALSE for off.
Return Values
Returns TRUE on success or FALSE on failure. Repeated calls to this method
with the same flag will return TRUE.
See Also
* OCI-Lob->getBuffering
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Lob->size
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Lob->size - Returns size of large object
Description
int OCI-Lob::size ( void )
Gets the size of the large object.
Return Values
Returns length of large object value or FALSE on failure. Empty objects
have zero length.
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Lob->tell
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Lob->tell - Returns the current position of internal pointer of large
object
Description
int OCI-Lob::tell ( void )
Gets the current position of a LOB's internal pointer.
Return Values
Returns current position of a LOB's internal pointer or FALSE if an error
occurred.
See Also
* OCI-Lob->rewind
* OCI-Lob->size
* OCI-Lob->eof
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Lob->truncate
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Lob->truncate - Truncates large object
Description
bool OCI-Lob::truncate ([ int $length = 0 ] )
Truncates the LOB.
Parameters
length
If provided, this method will truncate the LOB to length bytes.
Otherwise, it will completrely purge the LOB.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* OCI-Lob->erase
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Lob->write
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Lob->write - Writes data to the large object
Description
int OCI-Lob::write ( string $data [, int $length ] )
Writes data from the parameter data into the current position of LOB's
internal pointer.
Parameters
data
The data to write in the LOB.
length
If this parameter is given, writing will stop after length bytes
have been written or the end of data is reached, whichever comes
first.
Return Values
Returns the number of bytes written or FALSE on failure.
See Also
* OCI-Lob->read
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Lob->writeTemporary
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Lob->writeTemporary - Writes a temporary large object
Description
bool OCI-Lob::writeTemporary ( string $data [, int $lob_type =
OCI_TEMP_CLOB ] )
Creates a temporary large object and writes data to it.
You should use OCI-Lob->close when you are done with this object.
Parameters
data
The data to write.
lob_type
Can be one of the following:
* OCI_TEMP_BLOB is used to create temporary BLOBs
* OCI_TEMP_CLOB is used to create temporary CLOBs
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* OCI-Lob->close
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI-Lob->writeToFile
(PHP 5, PECL OCI8 >= 1.1.0)
OCI-Lob->writeToFile - Alias of oci_lob_export()
Description
This function is an alias of: oci_lob_export().
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_new_collection
(PHP 5, PECL OCI8 >= 1.1.0)
oci_new_collection - Allocates new collection object
Description
OCI-Collection oci_new_collection ( resource $connection , string $tdo [,
string $schema = NULL ] )
Allocates a new collection object.
Parameters
connection
An Oracle connection identifier, returned by oci_connect() or
oci_pconnect().
tdo
Should be a valid named type (uppercase).
schema
Should point to the scheme, where the named type was created. The
name of the current user is the default value.
Return Values
Returns a new OCICollection object or FALSE on error.
Notes
Note:
In PHP versions before 5.0.0 you must use ocinewcollection() instead.
This name still can be used, it was left as alias of
oci_new_collection() for downwards compatability. This, however, is
deprecated and not recommended.
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_new_connect
(PHP 5, PECL OCI8 >= 1.1.0)
oci_new_connect - Connect to the Oracle server using a unique connection
Description
resource oci_new_connect ( string $username , string $password [, string
$connection_string [, string $character_set [, int $session_mode ]]] )
Establishes a new connection to an Oracle server and logs on.
Unlike oci_connect() and oci_pconnect(), oci_new_connect() does not cache
connections and will always return a brand-new freshly opened connection
handle. This is useful if your application needs transactional isolation
between two sets of queries.
Parameters
username
The Oracle user name.
password
The password for username.
connection_string
Contains the Oracle instance to connect to. It can be an >> Easy
Connect string, or a Connect Name from the tnsnames.ora file, or
the name of a local Oracle instance.
If not specified, PHP uses environment variables such as TWO_TASK
(on Linux) or LOCAL (on Windows) and ORACLE_SID to determine the
Oracle instance to connect to.
To use the Easy Connect naming method, PHP must be linked with
Oracle 10g or greater Client libraries. The Easy Connect string
for Oracle 10g is of the form:
[//]host_name[:port][/service_name]. With Oracle 11g, the syntax
is:
[//]host_name[:port][/service_name][:server_type][/instance_name].
Service names can be found by running the Oracle utility lsnrctl
status on the database server machine.
The tnsnames.ora file can be in the Oracle Net search path, which
includes $ORACLE_HOME/network/admin and /etc. Alternatively set
TNS_ADMIN so that $TNS_ADMIN/tnsnames.ora is read. Make sure the
web daemon has read access to the file.
character_set
Determines the character set used by the Oracle Client libraries.
The character set does not need to match the character set used by
the database. If it doesn't match, Oracle will do its best to
convert data to and from the database character set. Depending on
the character sets this may not give usable results. Conversion
also adds some time overhead.
If not specified, the Oracle Client libraries determine a
character set from the NLS_LANG environment variable.
Passing this parameter can reduce connection time.
session_mode
This parameter is available since version PHP 5 (PECL OCI8 1.1)
and accepts the following values: OCI_DEFAULT, OCI_SYSOPER and
OCI_SYSDBA. If either OCI_SYSOPER or OCI_SYSDBA were specified,
this function will try to establish privileged connection using
external credentials. Privileged connections are disabled by
default. To enable them you need to set oci8.privileged_connect to
On.
PHP 5.3 (PECL OCI8 1.3.4) introduced the OCI_CRED_EXT mode value.
This tells Oracle to use External or OS authentication, which must
be configured in the database. The OCI_CRED_EXT flag can only be
used with username of "/" and a empty password.
oci8.privileged_connect may be On or Off.
OCI_CRED_EXT may be combined with the OCI_SYSOPER or OCI_SYSDBA
modes.
OCI_CRED_EXT is not supported on Windows for security reasons.
Return Values
Returns a connection identifier or FALSE on error.
Examples
The following demonstrates how you can separate connections.
Example #1 oci_new_connect() example
";
$db = "";
$c1 = oci_connect("scott", "tiger", $db);
$c2 = oci_new_connect("scott", "tiger", $db);
function create_table($conn)
{
$stmt = oci_parse($conn, "create table scott.hallo (test
varchar2(64))");
oci_execute($stmt);
echo $conn . " created table\n\n";
}
function drop_table($conn)
{
$stmt = oci_parse($conn, "drop table scott.hallo");
oci_execute($stmt);
echo $conn . " dropped table\n\n";
}
function insert_data($conn)
{
$stmt = oci_parse($conn, "insert into scott.hallo
values('$conn' || ' ' || to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
oci_execute($stmt, OCI_DEFAULT);
echo $conn . " inserted hallo\n\n";
}
function delete_data($conn)
{
$stmt = oci_parse($conn, "delete from scott.hallo");
oci_execute($stmt, OCI_DEFAULT);
echo $conn . " deleted hallo\n\n";
}
function commit($conn)
{
oci_commit($conn);
echo $conn . " committed\n\n";
}
function rollback($conn)
{
oci_rollback($conn);
echo $conn . " rollback\n\n";
}
function select_data($conn)
{
$stmt = oci_parse($conn, "select * from scott.hallo");
oci_execute($stmt, OCI_DEFAULT);
echo $conn . "----selecting\n\n";
while (oci_fetch($stmt)) {
echo $conn . " <" . oci_result($stmt, "TEST") . ">\n\n";
}
echo $conn . "----done\n\n";
}
create_table($c1);
insert_data($c1);
select_data($c1);
select_data($c2);
rollback($c1);
select_data($c1);
select_data($c2);
insert_data($c2);
commit($c2);
select_data($c1);
delete_data($c1);
select_data($c1);
select_data($c2);
commit($c1);
select_data($c1);
select_data($c2);
drop_table($c1);
echo " ";
?>
Notes
Note:
In PHP versions before 5.0.0 you must use ocinlogon() instead. The old
function name can still be used in current versions, however it is
deprecated and not recommended.
See Also
* oci_connect() - Connect to an Oracle database
* oci_pconnect() - Connect to an Oracle database using a persistent
connection
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_new_cursor
(PHP 5, PECL OCI8 >= 1.1.0)
oci_new_cursor - Allocates and returns a new cursor (statement handle)
Description
resource oci_new_cursor ( resource $connection )
Allocates a new statement handle on the specified connection.
Parameters
connection
An Oracle connection identifier, returned by oci_connect() or
oci_pconnect().
Return Values
Returns a new statement handle, or FALSE on error.
Examples
Example #1 Using REF CURSOR in an Oracle's stored procedure
Example #2 Using REF CURSOR in an Oracle's select statement
";
$conn = oci_connect("scott", "tiger");
$count_cursor = "CURSOR(select count(empno) num_emps from emp " .
"where emp.deptno = dept.deptno) as EMPCNT from dept";
$stmt = oci_parse($conn, "select deptno,dname,$count_cursor");
oci_execute($stmt);
echo "";
echo "";
echo "DEPT NAME ";
echo "DEPT # ";
echo "# EMPLOYEES ";
echo " ";
while ($data = oci_fetch_assoc($stmt)) {
echo "";
$dname = $data["DNAME"];
$deptno = $data["DEPTNO"];
echo "$dname ";
echo "$deptno ";
oci_execute($data["EMPCNT"]);
while ($subdata = oci_fetch_assoc($data["EMPCNT"])) {
$num_emps = $subdata["NUM_EMPS"];
echo "$num_emps ";
}
echo " ";
}
echo "
";
echo "";
oci_free_statement($stmt);
oci_close($conn);
?>
Notes
Note:
In PHP versions before 5.0.0 you must use ocinewcursor() instead. This
name still can be used, it was left as alias of oci_new_cursor() for
downwards compatability. This, however, is deprecated and not
recommended.
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_new_descriptor
(PHP 5, PECL OCI8 >= 1.1.0)
oci_new_descriptor - Initializes a new empty LOB or FILE descriptor
Description
OCI-Lob oci_new_descriptor ( resource $connection [, int $type =
OCI_DTYPE_LOB ] )
Allocates resources to hold descriptor or LOB locator.
Parameters
connection
An Oracle connection identifier, returned by oci_connect() or
oci_pconnect().
type
Valid values for type are: OCI_DTYPE_FILE, OCI_DTYPE_LOB and
OCI_DTYPE_ROWID.
Return Values
Returns a new LOB or FILE descriptor on success, FALSE on error.
Examples
Example #1 oci_new_descriptor() example
*
* ...
*/
if (!isset($lob_upload) || $lob_upload == 'none'){
?>
savefile($lob_upload)){
oci_commit($conn);
echo "Blob successfully uploaded\n";
}else{
echo "Couldn't upload Blob\n";
}
oci_free_descriptor($lob);
oci_free_statement($stmt);
oci_close($conn);
}
?>
Example #2 oci_new_descriptor() example
= 4.0.6).
* Example PL/SQL stored procedure signature is:
*
* PROCEDURE save_data
* Argument Name Type In/Out Default?
* ------------------------------ ----------------------- ------ --------
* KEY NUMBER(38) IN
* DATA CLOB IN
*
*/
$conn = oci_connect($user, $password);
$stmt = oci_parse($conn, "begin save_data(:key, :data); end;");
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stmt, ':key', $key);
oci_bind_by_name($stmt, ':data', $clob, -1, OCI_B_CLOB);
$clob->write($data);
oci_execute($stmt, OCI_DEFAULT);
oci_commit($conn);
$clob->free();
oci_free_statement($stmt);
?>
Notes
Note:
In PHP versions before 5.0.0 you must use ocinewdescriptor() instead.
This name still can be used, it was left as alias of
oci_new_descriptor() for downwards compatability. This, however, is
deprecated and not recommended.
See Also
* oci_bind_by_name() - Binds a PHP variable to an Oracle placeholder
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_num_fields
(PHP 5, PECL OCI8 >= 1.1.0)
oci_num_fields - Returns the number of result columns in a statement
Description
int oci_num_fields ( resource $statement )
Gets the number of columns in the given statement.
Parameters
statement
A valid OCI statement identifier.
Return Values
Returns the number of columns as an integer, or FALSE on errors.
Examples
Example #1 oci_num_fields() example
Notes
Note:
In PHP versions before 5.0.0 you must use ocinumcols() instead. This
name still can be used, it was left as alias of oci_num_fields() for
downwards compatability. This, however, is deprecated and not
recommended.
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_num_rows
(PHP 5, PECL OCI8 >= 1.1.0)
oci_num_rows - Returns number of rows affected during statement execution
Description
int oci_num_rows ( resource $statement )
Gets the number of rows affected during statement execution.
Parameters
statement
A valid OCI statement identifier.
Return Values
Returns the number of rows affected as an integer, or FALSE on errors.
Examples
Example #1 oci_num_rows() example
";
oci_free_statement($stmt);
$stmt = oci_parse($conn, "delete from emp2");
oci_execute($stmt, OCI_DEFAULT);
echo oci_num_rows($stmt) . " rows deleted. ";
oci_commit($conn);
oci_free_statement($stmt);
$stmt = oci_parse($conn, "drop table emp2");
oci_execute($stmt);
oci_free_statement($stmt);
oci_close($conn);
?>
Notes
Note:
This function does not return number of rows selected! For SELECT
statements this function will return the number of rows, that were
fetched to the buffer with oci_fetch*() functions.
Note:
In PHP versions before 5.0.0 you must use ocirowcount() instead. This
name still can be used, it was left as alias of oci_num_rows() for
downwards compatability. This, however, is deprecated and not
recommended.
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_parse
(PHP 5, PECL OCI8 >= 1.1.0)
oci_parse - Prepares an Oracle statement for execution
Description
resource oci_parse ( resource $connection , string $sql_text )
Prepares sql_text using connection and returns the statement identifier,
which can be used with oci_bind_by_name(), oci_execute() and other
functions.
Statement identifiers can be freed with oci_free_statement() or by setting
the variable to null.
Parameters
connection
An Oracle connection identifier, returned by oci_connect(),
oci_pconnect(), or oci_new_connect().
sql_text
The SQL or PL/SQL statement.
SQL statements should not end with a semi-colon (";"). PL/SQL
statements should end with a semi-colon (";").
Return Values
Returns a statement handle on success, or FALSE on error.
Examples
Example #1 oci_parse() example for SQL statements
\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "\n";
foreach ($row as $item) {
echo " " . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . " \n";
}
echo " \n";
}
echo "\n";
?>
Example #2 oci_parse() example for PL/SQL statements
Notes
Note:
This function does not validate sql_text. The only way to find out if
sql_text is a valid SQL or PL/SQL statement is to execute it.
Note:
In PHP versions before 5.0.0 use ociparse() instead. The old function
name can still be used in current versions, however it is deprecated and
not recommended.
See Also
* oci_execute() - Executes a statement
* oci_free_statement() - Frees all resources associated with statement
or cursor
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_password_change
(PHP 5, PECL OCI8 >= 1.1.0)
oci_password_change - Changes password of Oracle's user
Description
bool oci_password_change ( resource $connection , string $username ,
string $old_password , string $new_password )
resource oci_password_change ( string $dbname , string $username , string
$old_password , string $new_password )
Changes password for user with username.
The oci_password_change() function is most useful for PHP command-line
scripts, or when non-persistent connections are used throughout the PHP
application.
Parameters
connection
An Oracle connection identifier, returned by oci_connect() or
oci_pconnect().
username
The Oracle user name.
old_password
The old password.
new_password
The new password to be set.
dbname
The database name.
Return Values
Returns TRUE on success or FALSE on failure.
Notes
Note:
Changing the password either with this function or directly in Oracle
should be done carefully. This is because PHP applications may continue
to successfully reuse persistent connections by authenticating with the
old password. The best practice is to restart all web servers whenever
the user password is changed.
Note: The second oci_password_change() syntax is available since OCI8
version 1.1.
Note:
In PHP versions before 5.0.0 you must use ocipasswordchange() instead.
This name still can be used, it was left as alias of
oci_password_change() for downwards compatability. This, however, is
deprecated and not recommended.
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_pconnect
(PHP 5, PECL OCI8 >= 1.1.0)
oci_pconnect - Connect to an Oracle database using a persistent connection
Description
resource oci_pconnect ( string $username , string $password [, string
$connection_string [, string $character_set [, int $session_mode ]]] )
Creates a persistent connection to an Oracle server and logs on.
Persistent connections are cached and re-used between requests, resulting
in reduced overhead on each page load; a typical PHP application will have
a single persistent connection open against an Oracle server per Apache
child process (or PHP FastCGI/CGI process). See the Persistent Database
Connections section for more information.
Parameters
username
The Oracle user name.
password
The password for username.
connection_string
Contains the Oracle instance to connect to. It can be an >> Easy
Connect string, or a Connect Name from the tnsnames.ora file, or
the name of a local Oracle instance.
If not specified, PHP uses environment variables such as TWO_TASK
(on Linux) or LOCAL (on Windows) and ORACLE_SID to determine the
Oracle instance to connect to.
To use the Easy Connect naming method, PHP must be linked with
Oracle 10g or greater Client libraries. The Easy Connect string
for Oracle 10g is of the form:
[//]host_name[:port][/service_name]. With Oracle 11g, the syntax
is:
[//]host_name[:port][/service_name][:server_type][/instance_name].
Service names can be found by running the Oracle utility lsnrctl
status on the database server machine.
The tnsnames.ora file can be in the Oracle Net search path, which
includes $ORACLE_HOME/network/admin and /etc. Alternatively set
TNS_ADMIN so that $TNS_ADMIN/tnsnames.ora is read. Make sure the
web daemon has read access to the file.
character_set
Determines the character set used by the Oracle Client libraries.
The character set does not need to match the character set used by
the database. If it doesn't match, Oracle will do its best to
convert data to and from the database character set. Depending on
the character sets this may not give usable results. Conversion
also adds some time overhead.
If not specified, the Oracle Client libraries determine a
character set from the NLS_LANG environment variable.
Passing this parameter can reduce connection time.
session_mode
This parameter is available since version PHP 5 (PECL OCI8 1.1)
and accepts the following values: OCI_DEFAULT, OCI_SYSOPER and
OCI_SYSDBA. If either OCI_SYSOPER or OCI_SYSDBA were specified,
this function will try to establish privileged connection using
external credentials. Privileged connections are disabled by
default. To enable them you need to set oci8.privileged_connect to
On.
PHP 5.3 (PECL OCI8 1.3.4) introduced the OCI_CRED_EXT mode value.
This tells Oracle to use External or OS authentication, which must
be configured in the database. The OCI_CRED_EXT flag can only be
used with username of "/" and a empty password.
oci8.privileged_connect may be On or Off.
OCI_CRED_EXT may be combined with the OCI_SYSOPER or OCI_SYSDBA
modes.
OCI_CRED_EXT is not supported on Windows for security reasons.
Return Values
Returns a connection identifier or FALSE on error.
Notes
Note: Starting with PHP 5.1.2 and PECL oci8 1.1, the lifetime and
maximum number of persistent Oracle connections can be tuned by setting
the following configuration values: oci8.persistent_timeout,
oci8.ping_interval and oci8.max_persistent.
Note:
In PHP versions before 5.0.0 you must use ociplogon() instead. The old
function name can still be used in current versions, however it is
deprecated and not recommended.
See Also
* oci_connect() - Connect to an Oracle database
* oci_new_connect() - Connect to the Oracle server using a unique
connection
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_result
(PHP 5, PECL OCI8 >= 1.1.0)
oci_result - Returns field's value from the fetched row
Description
mixed oci_result ( resource $statement , mixed $field )
Returns the data from field in the current row, fetched by oci_fetch().
For details on the data type mapping performed by the OCI8 extension, see
the datatypes supported by the driver
Parameters
statement
field
Can be either use the column number (1-based) or the column name
(in uppercase).
Return Values
Returns everything as strings except for abstract types (ROWIDs, LOBs and
FILEs). Returns FALSE on error.
Notes
Note:
In PHP versions before 5.0.0 you must use ociresult() instead. This name
still can be used, it was left as alias of oci_result() for downwards
compatability. This, however, is deprecated and not recommended.
See Also
* oci_fetch_array() - Returns the next row from a query as an
associative or numeric array
* oci_fetch_assoc() - Returns the next row from a query as an
associative array
* oci_fetch_object() - Returns the next row from a query as an object
* oci_fetch_row() - Returns the next row from a query as a numeric array
* oci_fetch_all() - Fetches multiple rows from a query into a
two-dimensional array
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_rollback
(PHP 5, PECL OCI8 >= 1.1.0)
oci_rollback - Rolls back the outstanding database transaction
Description
bool oci_rollback ( resource $connection )
Reverts all uncommitted changes for the Oracle connection and ends the
transaction. It releases all locks held. All Oracle SAVEPOINTS are erased.
A transaction begins when the first SQL statement that changes data is
executed with oci_execute() using the OCI_NO_AUTO_COMMIT flag. Further
data changes made by other statements become part of the same transaction.
Data changes made in a transaction are temporary until the transaction is
committed or rolled back. Other users of the database will not see the
changes until they are committed.
When inserting or updating data, using transactions is recommended for
relational data consistency and for performance reasons.
Parameters
connection
An Oracle connection identifier, returned by oci_connect(),
oci_pconnect() or oci_new_connect().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 oci_rollback() example
Example #2 Rolling back to a SAVEPOINT example
Notes
Note:
Transactions are automatically rolled back when you close the
connection, or when the script ends, whichever is soonest. You need to
explicitly call oci_commit() to commit the transaction.
Any call to oci_execute() that uses OCI_COMMIT_ON_SUCCESS mode
explicitly or by default will commit any previous uncommitted
transaction.
Any Oracle DDL statement such as CREATE or DROP will automatically
commit any uncommitted transaction.
Note:
In PHP versions before 5.0.0 you must use ocirollback() instead. The old
function name can still be used in current versions, however it is
deprecated and not recommended.
See Also
* oci_commit() - Commits the outstanding database transaction
* oci_execute() - Executes a statement
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_server_version
(PHP 5, PECL OCI8 >= 1.1.0)
oci_server_version - Returns the Oracle Database version
Description
string oci_server_version ( resource $connection )
Returns a string with the Oracle Database version and available options
Parameters
connection
Return Values
Returns the version information as a string or FALSE on error.
Examples
Example #1 oci_server_version() example
Notes
Note:
In PHP versions before 5.0.0 you must use ociserverversion() instead.
This old name still can be used. However it is deprecated and not
recommended.
See Also
* oci_client_version() - Returns the Oracle client library version
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_set_action
(PHP 5.3.2, PECL OCI8 >= 1.4.0)
oci_set_action - Sets the action name
Description
bool oci_set_action ( resource $connection , string $action_name )
Sets the action name for Oracle tracing.
The action name is registered with the database when the next 'roundtrip'
from PHP to the database occurs, typically when an SQL statement is
executed.
The action name can subsequently be queried from database administration
views such as V$SESSION. It can be used for tracing and monitoring such as
with V$SQLAREA and DBMS_MONITOR.SERV_MOD_ACT_STAT_ENABLE.
The value may be retained across persistent connections.
Parameters
connection
An Oracle connection identifier, returned by oci_connect(),
oci_pconnect(), or oci_new_connect().
action_name
User chosen string up to 32 bytes long.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Setting the action
// While the script is running, the administrator can see the actions
// being performed:
sqlplus system/welcome
SQL> select action from v$session;
Notes
Note: Oracle version requirement
This function is available when PHP is linked with Oracle Database
libraries from version 10g onwards.
Tip
Performance
With older versions of OCI8 or the Oracle Database, the client information
can be set using the Oracle DBMS_APPLICATION_INFO package. This is less
efficient than using oci_set_client_info().
Caution
Roundtrip Gotcha
Some but not all OCI8 functions cause roundtrips. Roundtrips to the
database may not occur with queries when result caching is enabled.
See Also
* oci_set_module_name() - Sets the module name
* oci_set_client_info() - Sets the client information
* oci_set_client_identifier() - Sets the client identifier
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_set_client_identifier
(PHP 5.3.2, PECL OCI8 >= 1.4.0)
oci_set_client_identifier - Sets the client identifier
Description
bool oci_set_client_identifier ( resource $connection , string
$client_identifier )
Sets the client identifier used by various database components to identify
lightweight application users who authenticate as the same database user.
The client identifier is registered with the database when the next
'roundtrip' from PHP to the database occurs, typically when an SQL
statement is executed.
The identifier can subsequently be queried from database administration
views such as V$SESSION. It can be used with
DBMS_MONITOR.CLIENT_ID_TRACE_ENABLE for tracing. It can be used for
auditing.
The value may be retained across persistent connections.
Parameters
connection
An Oracle connection identifier, returned by oci_connect(),
oci_pconnect(), or oci_new_connect().
client_identifier
User chosen string up to 64 bytes long.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Setting the client identifier to the application user
Notes
Caution
Roundtrip Gotcha
Some but not all OCI8 functions cause roundtrips. Roundtrips to the
database may not occur with queries when result caching is enabled.
See Also
* oci_set_module_name() - Sets the module name
* oci_set_action() - Sets the action name
* oci_set_client_info() - Sets the client information
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_set_client_info
(PHP 5.3.2, PECL OCI8 >= 1.4.0)
oci_set_client_info - Sets the client information
Description
bool oci_set_client_info ( resource $connection , string $client_info )
Sets the client information for Oracle tracing.
The client information is registered with the database when the next
'roundtrip' from PHP to the database occurs, typically when an SQL
statement is executed.
The client information can subsequently be queried from database
administration views such as V$SESSION.
The value may be retained across persistent connections.
Parameters
An Oracle connection identifier, returned by oci_connect(),
oci_pconnect(), or oci_new_connect().
User chosen string up to 64 bytes long.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Setting the client information
// While the script is running, the administrator can see the client
// information:
sqlplus system/welcome
SQL> select client_info from v$session;
Notes
Note: Oracle version requirement
This function is available when PHP is linked with Oracle Database
libraries from version 10g onwards.
Tip
Performance
With older versions of OCI8 or the Oracle Database, the client information
can be set using the Oracle DBMS_APPLICATION_INFO package. This is less
efficient than using oci_set_client_info().
Caution
Roundtrip Gotcha
Some but not all OCI8 functions cause roundtrips. Roundtrips to the
database may not occur with queries when result caching is enabled.
See Also
* oci_set_module_name() - Sets the module name
* oci_set_action() - Sets the action name
* oci_set_client_identifier() - Sets the client identifier
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_set_edition
(PHP 5.3.2, PECL OCI8 >= 1.4.0)
oci_set_edition - Sets the database edition
Description
bool oci_set_edition ( string $edition )
Sets the database "edition" of objects to be used by a subsequent
connections.
Oracle Editions allow concurrent versions of applications to run using the
same schema and object names. This is useful for upgrading live systems.
Call oci_set_edition() before calling oci_connect(), oci_pconnect() or
oci_new_connect().
If an edition is set that is not valid in the database, connection will
fail even if oci_set_edition() returns success.
When using persistent connections, if a connection with the requested
edition setting already exists, it is reused. Otherwise, a different
persistent connection is created
Parameters
edition
Oracle Database edition name previously created with the SQL
"CREATE EDITION" command.
Notes
Note: Oracle version requirement
This function is available from Oracle 11gR2 onwards.
Caution
Persistent connections
To avoid inconsistencies and unexpected errors, do not use ALTER SESSION
SET EDITION to change the edition on persistent connections.
Caution
DRCP Connection Pooling
To avoid inconsistencies and unexpected errors when using editions and
DRCP with Oracle 11.2.0.1, keep a one-to-one correspondence between the
oci8.connection_class and the edition name used by applications. Each
pooled server of a given connection class should only be used with one
edition. This restriction has been removed with Oracle 11.2.0.2.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Two scripts can use different versions of myfunc() at the same
time
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_set_module_name
(PHP 5.3.2, PECL OCI8 >= 1.4.0)
oci_set_module_name - Sets the module name
Description
bool oci_set_module_name ( resource $connection , string $module_name )
Sets the module name for Oracle tracing.
The module name is registered with the database when the next 'roundtrip'
from PHP to the database occurs, typically when an SQL statement is
executed.
The name can subsequently be queried from database administration views
such as V$SESSION. It can be used for tracing and monitoring such as with
V$SQLAREA and DBMS_MONITOR.SERV_MOD_ACT_STAT_ENABLE.
The value may be retained across persistent connections.
Parameters
connection
An Oracle connection identifier, returned by oci_connect(),
oci_pconnect(), or oci_new_connect().
module_name
User chosen string up to 48 bytes long.
Return Values
Returns TRUE on success or FALSE on failure.
Notes
Note: Oracle version requirement
This function is available when PHP is linked with Oracle Database
libraries from version 10g onwards.
Tip
Performance
With older versions of OCI8 or the Oracle Database, the client information
can be set using the Oracle DBMS_APPLICATION_INFO package. This is less
efficient than using oci_set_client_info().
Caution
Roundtrip Gotcha
Some but not all OCI8 functions cause roundtrips. Roundtrips to the
database may not occur with queries when result caching is enabled.
Examples
Example #1 Setting the module name
// While the script is running, the administrator can see the
// modules in use:
sqlplus system/welcome
SQL> select module from v$session;
See Also
* oci_set_action() - Sets the action name
* oci_set_client_info() - Sets the client information
* oci_set_client_identifier() - Sets the client identifier
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_set_prefetch
(PHP 5, PECL OCI8 >= 1.1.0)
oci_set_prefetch - Sets number of rows to be prefetched by queries
Description
bool oci_set_prefetch ( resource $statement , int $rows )
Sets the number of rows to be buffered by the Oracle Client libraries
after a successful query call to oci_execute() and for each subsequent
internal fetch request to the database. For queries returning a large
number of rows, performance can be significantly improved by increasing
the prefetch count above the default oci8.default_prefetch value.
Prefetching is Oracle's efficient way of returning more than one data row
from the database in each network request. This can result in better
network and CPU utilization. The buffering of rows is internal to OCI8 and
the behavior of OCI8 fetching functions is unchanged regardless of the
prefetch count. For example, oci_fetch_row() will always return one row.
The prefetch buffer is per-statement and is not used by re-executed
statements or by other connections.
Call oci_set_prefetch() before calling oci_execute().
A tuning goal is to set the prefetch value to a reasonable size for the
network and database to handle. For queries returning a very large number
of rows, overall system efficiency might be better if rows are retrieved
from the database in several chunks (i.e set the prefetch value smaller
than the number of rows). This allows the database to handle other users'
statements while the PHP script is processing the current set of rows.
Query prefetching was introduced in Oracle 8i. REF CURSOR prefetching was
introduced in Oracle 11gR2 and occurs when PHP is linked with Oracle 11gR2
Client libraries and connected to 11gR2 or previous versions of the
database. Nested cursor prefetching was introduced in Oracle 11gR2 and
requires both the Oracle Client libraries and the database to be version
11gR2.
Prefetching is not supported when queries contain LONG or LOB columns. The
prefetch value is ignored and single-row fetches will be used in all the
situations when prefetching is not supported.
Parameters
statement
A valid OCI8 statement identifier created by oci_parse() and
executed by oci_execute(), or a REF CURSOR statement identifier.
rows
The number of rows to be prefetched, >= 0
Return Values
Returns TRUE on success or FALSE on failure.
Changelog
Version Description
PHP 5.3.2 (PECL OCI8 Before this release, rows must be >= 1.
1.4)
PHP 5.3 (PECL OCI8 Before this release, prefetching was limited to the
1.3.4) lesser of rows rows and 1024 * rows bytes. The byte
size restriction has now been removed.
Examples
Example #1 Changing the default prefetch value for a query
\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "\n";
foreach ($row as $item) {
echo " ".($item !== null ? htmlentities($item, ENT_QUOTES) : " ")." \n";
}
echo " \n";
}
echo "\n";
oci_free_statement($stid);
oci_close($conn);
?>
Example #2 Changing the default prefetch for a REF CURSOR fetch
\n";
while ($row = oci_fetch_array($refcur, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "\n";
foreach ($row as $item) {
echo " ".($item !== null ? htmlentities($item, ENT_QUOTES) : " ")." \n";
}
echo " \n";
}
echo "\n";
oci_free_statement($refcur);
oci_free_statement($stid);
oci_close($conn);
?>
If PHP OCI8 fetches from a REF CURSOR and then passes the REF CURSOR back
to a second PL/SQL procedure for further processing, then set the REF
CURSOR prefetch count to 0 to avoid rows being "lost" from the result set.
The prefetch value is the number of extra rows fetched in each OCI8
internal request to the database, so setting it to 0 means only fetch one
row at a time.
Example #3 Setting the prefetch value when passing a REF CURSOR back to
Oracle
Notes
Note:
In PHP versions before 5.0.0 use ocisetprefetch() instead. The old
function name can still be used in current versions, however it is
deprecated and not recommended.
See Also
* oci8.default_prefetch ini option
----------------------------------------------------------------------
----------------------------------------------------------------------
oci_statement_type
(PHP 5, PECL OCI8 >= 1.1.0)
oci_statement_type - Returns the type of a statement
Description
string oci_statement_type ( resource $statement )
Returns a keyword identifying the type of the OCI8 statement.
Parameters
statement
A valid OCI8 statement identifier from oci_parse().
Return Values
Returns the type of statement as one of the following strings.
Statement type
Return String Notes
ALTER
BEGIN
CALL Introduced in PHP 5.2.1 (PECL OCI8 1.2.3)
CREATE
DECLARE
DELETE
DROP
INSERT
SELECT
UPDATE
UNKNOWN
Returns FALSE on error.
Examples
Example #1 oci_statement_type() example
Notes
Note:
In PHP versions before 5.0.0 you must use ocistatementtype() instead.
The old function name can still be used in current versions, however it
is deprecated and not recommended.
----------------------------------------------------------------------
Table of Contents
* oci_bind_array_by_name - Binds a PHP array to an Oracle PL/SQL array
parameter
* oci_bind_by_name - Binds a PHP variable to an Oracle placeholder
* oci_cancel - Cancels reading from cursor
* oci_client_version - Returns the Oracle client library version
* oci_close - Closes an Oracle connection
* OCI-Collection->append - Appends element to the collection
* OCI-Collection->assign - Assigns a value to the collection from
another existing collection
* OCI-Collection->assignElem - Assigns a value to the element of the
collection
* OCI-Collection->free - Frees the resources associated with the
collection object
* OCI-Collection->getElem - Returns value of the element
* OCI-Collection->max - Returns the maximum number of elements in the
collection
* OCI-Collection->size - Returns size of the collection
* OCI-Collection->trim - Trims elements from the end of the collection
* oci_commit - Commits the outstanding database transaction
* oci_connect - Connect to an Oracle database
* oci_define_by_name - Associates a PHP variable with a column for query
fetches
* oci_error - Returns the last error found
* oci_execute - Executes a statement
* oci_fetch_all - Fetches multiple rows from a query into a
two-dimensional array
* oci_fetch_array - Returns the next row from a query as an associative
or numeric array
* oci_fetch_assoc - Returns the next row from a query as an associative
array
* oci_fetch_object - Returns the next row from a query as an object
* oci_fetch_row - Returns the next row from a query as a numeric array
* oci_fetch - Fetches the next row from a query into internal buffers
* oci_field_is_null - Checks if the field is NULL
* oci_field_name - Returns the name of a field from the statement
* oci_field_precision - Tell the precision of a field
* oci_field_scale - Tell the scale of the field
* oci_field_size - Returns field's size
* oci_field_type_raw - Tell the raw Oracle data type of the field
* oci_field_type - Returns field's data type
* oci_free_statement - Frees all resources associated with statement or
cursor
* oci_internal_debug - Enables or disables internal debug output
* OCI-Lob->append - Appends data from the large object to another large
object
* OCI-Lob->close - Closes LOB descriptor
* oci_lob_copy - Copies large object
* OCI-Lob->eof - Tests for end-of-file on a large object's descriptor
* OCI-Lob->erase - Erases a specified portion of the internal LOB data
* OCI-Lob->export - Exports LOB's contents to a file
* OCI-Lob->flush - Flushes/writes buffer of the LOB to the server
* OCI-Lob->free - Frees resources associated with the LOB descriptor
* OCI-Lob->getBuffering - Returns current state of buffering for the
large object
* OCI-Lob->import - Imports file data to the LOB
* oci_lob_is_equal - Compares two LOB/FILE locators for equality
* OCI-Lob->load - Returns large object's contents
* OCI-Lob->read - Reads part of the large object
* OCI-Lob->rewind - Moves the internal pointer to the beginning of the
large object
* OCI-Lob->save - Saves data to the large object
* OCI-Lob->saveFile - Alias of oci_lob_import
* OCI-Lob->seek - Sets the internal pointer of the large object
* OCI-Lob->setBuffering - Changes current state of buffering for the
large object
* OCI-Lob->size - Returns size of large object
* OCI-Lob->tell - Returns the current position of internal pointer of
large object
* OCI-Lob->truncate - Truncates large object
* OCI-Lob->write - Writes data to the large object
* OCI-Lob->writeTemporary - Writes a temporary large object
* OCI-Lob->writeToFile - Alias of oci_lob_export
* oci_new_collection - Allocates new collection object
* oci_new_connect - Connect to the Oracle server using a unique
connection
* oci_new_cursor - Allocates and returns a new cursor (statement handle)
* oci_new_descriptor - Initializes a new empty LOB or FILE descriptor
* oci_num_fields - Returns the number of result columns in a statement
* oci_num_rows - Returns number of rows affected during statement
execution
* oci_parse - Prepares an Oracle statement for execution
* oci_password_change - Changes password of Oracle's user
* oci_pconnect - Connect to an Oracle database using a persistent
connection
* oci_result - Returns field's value from the fetched row
* oci_rollback - Rolls back the outstanding database transaction
* oci_server_version - Returns the Oracle Database version
* oci_set_action - Sets the action name
* oci_set_client_identifier - Sets the client identifier
* oci_set_client_info - Sets the client information
* oci_set_edition - Sets the database edition
* oci_set_module_name - Sets the module name
* oci_set_prefetch - Sets number of rows to be prefetched by queries
* oci_statement_type - Returns the type of a statement
----------------------------------------------------------------------
----------------------------------------------------------------------
OCI8 Obsolete Aliases and Functions
----------------------------------------------------------------------
ocibindbyname
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocibindbyname - Alias of oci_bind_by_name()
Description
This function is an alias of: oci_bind_by_name().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocicancel
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocicancel - Alias of oci_cancel()
Description
This function is an alias of: oci_cancel().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocicloselob
(PHP 4 >= 4.0.6, PECL OCI8 1.0)
ocicloselob - Alias of oci_lob_close()
Description
This function is an alias of: oci_lob_close().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocicollappend
(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)
ocicollappend - Alias of oci_collection_append()
Description
This function is an alias of: oci_collection_append().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocicollassign
(PHP 4 >= 4.0.6, PECL OCI8 1.0)
ocicollassign - Alias of oci_collection_assign()
Description
This function is an alias of: oci_collection_assign().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocicollassignelem
(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)
ocicollassignelem - Alias of oci_collection_element_assign()
Description
This function is an alias of: oci_collection_element_assign().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocicollgetelem
(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)
ocicollgetelem - Alias of oci_collection_element_get()
Description
This function is an alias of: oci_collection_element_get().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocicollmax
(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)
ocicollmax - Alias of oci_collection_max()
Description
This function is an alias of: oci_collection_max().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocicollsize
(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)
ocicollsize - Alias of oci_collection_size()
Description
This function is an alias of: oci_collection_size().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocicolltrim
(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)
ocicolltrim - Alias of oci_collection_trim()
Description
This function is an alias of: oci_collection_trim().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocicolumnisnull
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocicolumnisnull - Alias of oci_field_is_null()
Description
This function is an alias of: oci_field_is_null().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocicolumnname
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocicolumnname - Alias of oci_field_name()
Description
This function is an alias of: oci_field_name().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocicolumnprecision
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocicolumnprecision - Alias of oci_field_precision()
Description
This function is an alias of: oci_field_precision().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocicolumnscale
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocicolumnscale - Alias of oci_field_scale()
Description
This function is an alias of: oci_field_scale().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocicolumnsize
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocicolumnsize - Alias of oci_field_size()
Description
This function is an alias of: oci_field_size().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocicolumntype
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocicolumntype - Alias of oci_field_type()
Description
This function is an alias of: oci_field_type().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocicolumntyperaw
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocicolumntyperaw - Alias of oci_field_type_raw()
Description
This function is an alias of: oci_field_type_raw().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocicommit
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocicommit - Alias of oci_commit()
Description
This function is an alias of: oci_commit().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocidefinebyname
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocidefinebyname - Alias of oci_define_by_name()
Description
This function is an alias of: oci_define_by_name().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocierror
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocierror - Alias of oci_error()
Description
This function is an alias of: oci_error().
----------------------------------------------------------------------
----------------------------------------------------------------------
ociexecute
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ociexecute - Alias of oci_execute()
Description
This function is an alias of: oci_execute().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocifetch
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocifetch - Alias of oci_fetch()
Description
This function is an alias of: oci_fetch().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocifetchinto
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocifetchinto - Fetches the next row into an array (deprecated)
Description
int ocifetchinto ( resource $statement , array &$result [, int $mode =
OCI_ASSOC + OCI_NUM ] )
This function is deprecated. Recommended alternatives: oci_fetch_array(),
oci_fetch_object(), oci_fetch_assoc() and oci_fetch_row().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocifetchstatement
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocifetchstatement - Alias of oci_fetch_all()
Description
This function is an alias of: oci_fetch_all().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocifreecollection
(PHP 4 >= 4.0.7, PHP 5, PECL OCI8 >= 1.0.0)
ocifreecollection - Alias of oci_collection_free()
Description
This function is an alias of: oci_collection_free().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocifreecursor
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocifreecursor - Alias of oci_free_statement()
Description
This function is an alias of: oci_free_statement().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocifreedesc
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocifreedesc - Alias of oci_lob_free()
Description
This function is an alias of: oci_lob_free().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocifreestatement
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocifreestatement - Alias of oci_free_statement()
Description
This function is an alias of: oci_free_statement().
----------------------------------------------------------------------
----------------------------------------------------------------------
ociinternaldebug
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ociinternaldebug - Alias of oci_internal_debug()
Description
This function is an alias of: oci_internal_debug().
----------------------------------------------------------------------
----------------------------------------------------------------------
ociloadlob
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ociloadlob - Alias of oci_lob_load()
Description
This function is an alias of: oci_lob_load().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocilogoff
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocilogoff - Alias of oci_close()
Description
This function is an alias of: oci_close().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocilogon
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocilogon - Alias of oci_connect()
Description
This function is an alias of: oci_connect().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocinewcollection
(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)
ocinewcollection - Alias of oci_new_collection()
Description
This function is an alias of: oci_new_collection().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocinewcursor
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocinewcursor - Alias of oci_new_cursor()
Description
This function is an alias of: oci_new_cursor().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocinewdescriptor
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocinewdescriptor - Alias of oci_new_descriptor()
Description
This function is an alias of: oci_new_descriptor().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocinlogon
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocinlogon - Alias of oci_new_connect()
Description
This function is an alias of: oci_new_connect().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocinumcols
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocinumcols - Alias of oci_num_fields()
Description
This function is an alias of: oci_num_fields().
----------------------------------------------------------------------
----------------------------------------------------------------------
ociparse
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ociparse - Alias of oci_parse()
Description
This function is an alias of: oci_parse().
----------------------------------------------------------------------
----------------------------------------------------------------------
ociplogon
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ociplogon - Alias of oci_pconnect()
Description
This function is an alias of: oci_pconnect().
----------------------------------------------------------------------
----------------------------------------------------------------------
ociresult
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ociresult - Alias of oci_result()
Description
This function is an alias of: oci_result().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocirollback
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocirollback - Alias of oci_rollback()
Description
This function is an alias of: oci_rollback().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocirowcount
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocirowcount - Alias of oci_num_rows()
Description
This function is an alias of: oci_num_rows().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocisavelob
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocisavelob - Alias of oci_lob_save()
Description
This function is an alias of: oci_lob_save().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocisavelobfile
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocisavelobfile - Alias of oci_lob_import()
Description
This function is an alias of: oci_lob_import().
----------------------------------------------------------------------
----------------------------------------------------------------------
ociserverversion
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ociserverversion - Alias of oci_server_version()
Description
This function is an alias of: oci_server_version().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocisetprefetch
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocisetprefetch - Alias of oci_set_prefetch()
Description
This function is an alias of: oci_set_prefetch().
----------------------------------------------------------------------
----------------------------------------------------------------------
ocistatementtype
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ocistatementtype - Alias of oci_statement_type()
Description
This function is an alias of: oci_statement_type().
----------------------------------------------------------------------
----------------------------------------------------------------------
ociwritelobtofile
(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)
ociwritelobtofile - Alias of oci_lob_export()
Description
This function is an alias of: oci_lob_export().
----------------------------------------------------------------------
----------------------------------------------------------------------
ociwritetemporarylob
(PHP 4 >= 4.0.6, PECL OCI8 1.0)
ociwritetemporarylob - Alias of oci_lob_writetemporary()
Description
This function is an alias of: oci_lob_writetemporary().
----------------------------------------------------------------------
Table of Contents
* ocibindbyname - Alias of oci_bind_by_name
* ocicancel - Alias of oci_cancel
* ocicloselob - Alias of oci_lob_close
* ocicollappend - Alias of oci_collection_append
* ocicollassign - Alias of oci_collection_assign
* ocicollassignelem - Alias of oci_collection_element_assign
* ocicollgetelem - Alias of oci_collection_element_get
* ocicollmax - Alias of oci_collection_max
* ocicollsize - Alias of oci_collection_size
* ocicolltrim - Alias of oci_collection_trim
* ocicolumnisnull - Alias of oci_field_is_null
* ocicolumnname - Alias of oci_field_name
* ocicolumnprecision - Alias of oci_field_precision
* ocicolumnscale - Alias of oci_field_scale
* ocicolumnsize - Alias of oci_field_size
* ocicolumntype - Alias of oci_field_type
* ocicolumntyperaw - Alias of oci_field_type_raw
* ocicommit - Alias of oci_commit
* ocidefinebyname - Alias of oci_define_by_name
* ocierror - Alias of oci_error
* ociexecute - Alias of oci_execute
* ocifetch - Alias of oci_fetch
* ocifetchinto - Fetches the next row into an array (deprecated)
* ocifetchstatement - Alias of oci_fetch_all
* ocifreecollection - Alias of oci_collection_free
* ocifreecursor - Alias of oci_free_statement
* ocifreedesc - Alias of oci_lob_free
* ocifreestatement - Alias of oci_free_statement
* ociinternaldebug - Alias of oci_internal_debug
* ociloadlob - Alias of oci_lob_load
* ocilogoff - Alias of oci_close
* ocilogon - Alias of oci_connect
* ocinewcollection - Alias of oci_new_collection
* ocinewcursor - Alias of oci_new_cursor
* ocinewdescriptor - Alias of oci_new_descriptor
* ocinlogon - Alias of oci_new_connect
* ocinumcols - Alias of oci_num_fields
* ociparse - Alias of oci_parse
* ociplogon - Alias of oci_pconnect
* ociresult - Alias of oci_result
* ocirollback - Alias of oci_rollback
* ocirowcount - Alias of oci_num_rows
* ocisavelob - Alias of oci_lob_save
* ocisavelobfile - Alias of oci_lob_import
* ociserverversion - Alias of oci_server_version
* ocisetprefetch - Alias of oci_set_prefetch
* ocistatementtype - Alias of oci_statement_type
* ociwritelobtofile - Alias of oci_lob_export
* ociwritetemporarylob - Alias of oci_lob_writetemporary
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Testing
* Runtime Configuration
* Predefined Constants
* Examples
* Connection Handling
* Supported Datatypes
* OCI8 Functions
* oci_bind_array_by_name - Binds a PHP array to an Oracle PL/SQL
array parameter
* oci_bind_by_name - Binds a PHP variable to an Oracle placeholder
* oci_cancel - Cancels reading from cursor
* oci_client_version - Returns the Oracle client library version
* oci_close - Closes an Oracle connection
* OCI-Collection->append - Appends element to the collection
* OCI-Collection->assign - Assigns a value to the collection from
another existing collection
* OCI-Collection->assignElem - Assigns a value to the element of
the collection
* OCI-Collection->free - Frees the resources associated with the
collection object
* OCI-Collection->getElem - Returns value of the element
* OCI-Collection->max - Returns the maximum number of elements in
the collection
* OCI-Collection->size - Returns size of the collection
* OCI-Collection->trim - Trims elements from the end of the
collection
* oci_commit - Commits the outstanding database transaction
* oci_connect - Connect to an Oracle database
* oci_define_by_name - Associates a PHP variable with a column for
query fetches
* oci_error - Returns the last error found
* oci_execute - Executes a statement
* oci_fetch_all - Fetches multiple rows from a query into a
two-dimensional array
* oci_fetch_array - Returns the next row from a query as an
associative or numeric array
* oci_fetch_assoc - Returns the next row from a query as an
associative array
* oci_fetch_object - Returns the next row from a query as an object
* oci_fetch_row - Returns the next row from a query as a numeric
array
* oci_fetch - Fetches the next row from a query into internal
buffers
* oci_field_is_null - Checks if the field is NULL
* oci_field_name - Returns the name of a field from the statement
* oci_field_precision - Tell the precision of a field
* oci_field_scale - Tell the scale of the field
* oci_field_size - Returns field's size
* oci_field_type_raw - Tell the raw Oracle data type of the field
* oci_field_type - Returns field's data type
* oci_free_statement - Frees all resources associated with
statement or cursor
* oci_internal_debug - Enables or disables internal debug output
* OCI-Lob->append - Appends data from the large object to another
large object
* OCI-Lob->close - Closes LOB descriptor
* oci_lob_copy - Copies large object
* OCI-Lob->eof - Tests for end-of-file on a large object's
descriptor
* OCI-Lob->erase - Erases a specified portion of the internal LOB
data
* OCI-Lob->export - Exports LOB's contents to a file
* OCI-Lob->flush - Flushes/writes buffer of the LOB to the server
* OCI-Lob->free - Frees resources associated with the LOB
descriptor
* OCI-Lob->getBuffering - Returns current state of buffering for
the large object
* OCI-Lob->import - Imports file data to the LOB
* oci_lob_is_equal - Compares two LOB/FILE locators for equality
* OCI-Lob->load - Returns large object's contents
* OCI-Lob->read - Reads part of the large object
* OCI-Lob->rewind - Moves the internal pointer to the beginning of
the large object
* OCI-Lob->save - Saves data to the large object
* OCI-Lob->saveFile - Alias of oci_lob_import
* OCI-Lob->seek - Sets the internal pointer of the large object
* OCI-Lob->setBuffering - Changes current state of buffering for
the large object
* OCI-Lob->size - Returns size of large object
* OCI-Lob->tell - Returns the current position of internal pointer
of large object
* OCI-Lob->truncate - Truncates large object
* OCI-Lob->write - Writes data to the large object
* OCI-Lob->writeTemporary - Writes a temporary large object
* OCI-Lob->writeToFile - Alias of oci_lob_export
* oci_new_collection - Allocates new collection object
* oci_new_connect - Connect to the Oracle server using a unique
connection
* oci_new_cursor - Allocates and returns a new cursor (statement
handle)
* oci_new_descriptor - Initializes a new empty LOB or FILE
descriptor
* oci_num_fields - Returns the number of result columns in a
statement
* oci_num_rows - Returns number of rows affected during statement
execution
* oci_parse - Prepares an Oracle statement for execution
* oci_password_change - Changes password of Oracle's user
* oci_pconnect - Connect to an Oracle database using a persistent
connection
* oci_result - Returns field's value from the fetched row
* oci_rollback - Rolls back the outstanding database transaction
* oci_server_version - Returns the Oracle Database version
* oci_set_action - Sets the action name
* oci_set_client_identifier - Sets the client identifier
* oci_set_client_info - Sets the client information
* oci_set_edition - Sets the database edition
* oci_set_module_name - Sets the module name
* oci_set_prefetch - Sets number of rows to be prefetched by
queries
* oci_statement_type - Returns the type of a statement
* OCI8 Obsolete Aliases and Functions
* ocibindbyname - Alias of oci_bind_by_name
* ocicancel - Alias of oci_cancel
* ocicloselob - Alias of oci_lob_close
* ocicollappend - Alias of oci_collection_append
* ocicollassign - Alias of oci_collection_assign
* ocicollassignelem - Alias of oci_collection_element_assign
* ocicollgetelem - Alias of oci_collection_element_get
* ocicollmax - Alias of oci_collection_max
* ocicollsize - Alias of oci_collection_size
* ocicolltrim - Alias of oci_collection_trim
* ocicolumnisnull - Alias of oci_field_is_null
* ocicolumnname - Alias of oci_field_name
* ocicolumnprecision - Alias of oci_field_precision
* ocicolumnscale - Alias of oci_field_scale
* ocicolumnsize - Alias of oci_field_size
* ocicolumntype - Alias of oci_field_type
* ocicolumntyperaw - Alias of oci_field_type_raw
* ocicommit - Alias of oci_commit
* ocidefinebyname - Alias of oci_define_by_name
* ocierror - Alias of oci_error
* ociexecute - Alias of oci_execute
* ocifetch - Alias of oci_fetch
* ocifetchinto - Fetches the next row into an array (deprecated)
* ocifetchstatement - Alias of oci_fetch_all
* ocifreecollection - Alias of oci_collection_free
* ocifreecursor - Alias of oci_free_statement
* ocifreedesc - Alias of oci_lob_free
* ocifreestatement - Alias of oci_free_statement
* ociinternaldebug - Alias of oci_internal_debug
* ociloadlob - Alias of oci_lob_load
* ocilogoff - Alias of oci_close
* ocilogon - Alias of oci_connect
* ocinewcollection - Alias of oci_new_collection
* ocinewcursor - Alias of oci_new_cursor
* ocinewdescriptor - Alias of oci_new_descriptor
* ocinlogon - Alias of oci_new_connect
* ocinumcols - Alias of oci_num_fields
* ociparse - Alias of oci_parse
* ociplogon - Alias of oci_pconnect
* ociresult - Alias of oci_result
* ocirollback - Alias of oci_rollback
* ocirowcount - Alias of oci_num_rows
* ocisavelob - Alias of oci_lob_save
* ocisavelobfile - Alias of oci_lob_import
* ociserverversion - Alias of oci_server_version
* ocisetprefetch - Alias of oci_set_prefetch
* ocistatementtype - Alias of oci_statement_type
* ociwritelobtofile - Alias of oci_lob_export
* ociwritetemporarylob - Alias of oci_lob_writetemporary
----------------------------------------------------------------------
----------------------------------------------------------------------
Ovrimos SQL
----------------------------------------------------------------------
Introduction
Ovrimos SQL Server, is a client/server, transactional RDBMS combined with
Web capabilities and fast transactions.
Note:
This extension has been moved to the >> PECL repository and is no longer
bundled with PHP as of PHP 4.4.5 and PHP 5.1.0.
Note: This extension is not available on Windows platforms.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
You'll need to install the sqlcli library available in the Ovrimos SQL
Server distribution.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
To enable Ovrimos support in PHP just compile PHP with the
--with-ovrimos[=DIR] parameter to your configure line. DIR is the Ovrimos'
libsqlcli install directory.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
This extension has no constants defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Table of Contents
* Basic usage
----------------------------------------------------------------------
Basic usage
Example #1 Connect to Ovrimos SQL Server and select from a system table
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Ovrimos SQL Functions
----------------------------------------------------------------------
ovrimos_close
(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)
ovrimos_close - Closes the connection to ovrimos
Description
void ovrimos_close ( int $connection )
Closes the specified connection to Ovrimos. This has the effect of rolling
back uncommitted transactions.
Parameters
connection
The Ovrimos connection identifier, returned by ovrimos_connect().
Return Values
No value is returned.
See Also
* ovrimos_connect() - Connect to the specified database
----------------------------------------------------------------------
----------------------------------------------------------------------
ovrimos_commit
(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)
ovrimos_commit - Commits the transaction
Description
bool ovrimos_commit ( int $connection_id )
Commits the transaction.
Parameters
connection_id
The Ovrimos connection identifier, returned by ovrimos_connect().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ovrimos_rollback() - Rolls back the transaction
----------------------------------------------------------------------
----------------------------------------------------------------------
ovrimos_connect
(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)
ovrimos_connect - Connect to the specified database
Description
int ovrimos_connect ( string $host , string $dborport , string $user ,
string $password )
Connects to the specified database.
Parameters
host
A host name or IP address.
dborport
Either a database name, or the port number to connect to.
user
The user name.
password
Password associated with user.
Return Values
Returns a connection identifier (greater than 0) on success, or 0 on
failure.
Examples
Example #1 ovrimos_connect() Example
See Also
* ovrimos_close() - Closes the connection to ovrimos
----------------------------------------------------------------------
----------------------------------------------------------------------
ovrimos_cursor
(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)
ovrimos_cursor - Returns the name of the cursor
Description
string ovrimos_cursor ( int $result_id )
Gets the name of the cursor. Useful when wishing to perform positioned
updates or deletes.
Parameters
result_id
A result identifier, returned by ovrimos_execute() or
ovrimos_exec().
Return Values
Returns the name as a string, or FALSE on error.
----------------------------------------------------------------------
----------------------------------------------------------------------
ovrimos_exec
(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)
ovrimos_exec - Executes an SQL statement
Description
int ovrimos_exec ( int $connection_id , string $query )
Executes an SQL statement (query or update) and returns a result
identifier.
Parameters
connection_id
The Ovrimos connection identifier, returned by ovrimos_connect().
query
The SQL statement. Evidently, it should not contain parameters.
Use ovrimos_prepare() for prepared statements.
Return Values
Returns the result identifier as an integer, or FALSE on error.
See Also
* ovrimos_execute() - Executes a prepared SQL statement
* ovrimos_prepare() - Prepares an SQL statement
----------------------------------------------------------------------
----------------------------------------------------------------------
ovrimos_execute
(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)
ovrimos_execute - Executes a prepared SQL statement
Description
bool ovrimos_execute ( int $result_id [, array $parameters_array ] )
Executes a prepared statement.
Parameters
result_id
An Ovrimos result identifier prepared with ovrimos_prepare().
parameters_array
If the prepared statement contained parameters (question marks in
the statement), the correct number of parameters should be passed
in an array.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ovrimos_prepare() - Prepares an SQL statement
----------------------------------------------------------------------
----------------------------------------------------------------------
ovrimos_fetch_into
(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)
ovrimos_fetch_into - Fetches a row from the result set
Description
bool ovrimos_fetch_into ( int $result_id , array &$result_array [, string
$how [, int $rownumber ]] )
Fetches a row from the given result set, into result_array.
Parameters
result_id
A result identifier, returned by ovrimos_execute() or
ovrimos_exec().
result_array
You must provide an array by reference. It will be filled with the
fetched values.
how
Determines how the rows are fetched. This can be one of the
following strings (case is not significant):
Option Notes
Next Forward direction from current position. This is the
default value.
Prev Backward direction from current position.
First Forward direction from the start.
Last Backward direction from the end.
Absolute Absolute position from the start. Requires rownumber.
rownumber
The row number, first one is 0. Only needed when how is set to
Absolute.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 A fetch into example
See Also
* ovrimos_fetch_row() - Fetches a row from the result set
----------------------------------------------------------------------
----------------------------------------------------------------------
ovrimos_fetch_row
(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)
ovrimos_fetch_row - Fetches a row from the result set
Description
bool ovrimos_fetch_row ( int $result_id [, int $how [, int $row_number ]]
)
Fetches a row from the result set. Column values should be retrieved with
other calls.
Parameters
result_id
A result identifier, returned by ovrimos_execute() or
ovrimos_exec().
how
Determines how the rows are fetched. This can be one of the
following strings (case is not significant):
Option Notes
Next Forward direction from current position. This is the
default value.
Prev Backward direction from current position.
First Forward direction from the start.
Last Backward direction from the end.
Absolute Absolute position from the start. Requires rownumber.
rownumber
The row number, first one is 0. Only needed when how is set to
Absolute.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 A fetch row example
This will fetch a row and print the result.
See Also
* ovrimos_fetch_into() - Fetches a row from the result set
----------------------------------------------------------------------
----------------------------------------------------------------------
ovrimos_field_len
(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)
ovrimos_field_len - Returns the length of the output column
Description
int ovrimos_field_len ( int $result_id , int $field_number )
Gets the length of the specified output column.
Parameters
result_id
A result identifier, returned by ovrimos_execute() or
ovrimos_exec().
field_number
The field number. Starts at 1.
Return Values
Returns the length as an integer, or FALSE on error.
See Also
* ovrimos_field_name() - Returns the output column name
* ovrimos_field_num() - Returns the (1-based) index of the output column
* ovrimos_field_type() - Returns the type of the output column
----------------------------------------------------------------------
----------------------------------------------------------------------
ovrimos_field_name
(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)
ovrimos_field_name - Returns the output column name
Description
string ovrimos_field_name ( int $result_id , int $field_number )
Returns the output column name at the index specified.
Parameters
result_id
A result identifier, returned by ovrimos_execute() or
ovrimos_exec().
field_number
The field number. Starts at 1.
Return Values
Returns the field name as a string, or FALSE on error.
See Also
* ovrimos_field_len() - Returns the length of the output column
* ovrimos_field_num() - Returns the (1-based) index of the output column
* ovrimos_field_type() - Returns the type of the output column
----------------------------------------------------------------------
----------------------------------------------------------------------
ovrimos_field_num
(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)
ovrimos_field_num - Returns the (1-based) index of the output column
Description
int ovrimos_field_num ( int $result_id , string $field_name )
Returns the 1-based index of the specified output column.
Parameters
result_id
A result identifier, returned by ovrimos_execute() or
ovrimos_exec().
field_name
The field name.
Return Values
Returns the index, starting at 1, or FALSE on error.
See Also
* ovrimos_field_len() - Returns the length of the output column
* ovrimos_field_name() - Returns the output column name
* ovrimos_field_type() - Returns the type of the output column
----------------------------------------------------------------------
----------------------------------------------------------------------
ovrimos_field_type
(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)
ovrimos_field_type - Returns the type of the output column
Description
int ovrimos_field_type ( int $result_id , int $field_number )
Returns the type of the output column
Parameters
result_id
A result identifier, returned by ovrimos_execute() or
ovrimos_exec().
field_number
A 1-based index.
Return Values
Returns the field type as an integer, or FALSE on error.
See Also
* ovrimos_field_len() - Returns the length of the output column
* ovrimos_field_name() - Returns the output column name
* ovrimos_field_num() - Returns the (1-based) index of the output column
----------------------------------------------------------------------
----------------------------------------------------------------------
ovrimos_free_result
(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)
ovrimos_free_result - Frees the specified result_id
Description
bool ovrimos_free_result ( int $result_id )
Frees the specified result identifier.
Parameters
result_id
A result identifier, returned by ovrimos_execute() or
ovrimos_exec().
Return Values
Returns TRUE.
----------------------------------------------------------------------
----------------------------------------------------------------------
ovrimos_longreadlen
(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)
ovrimos_longreadlen - Specifies how many bytes are to be retrieved from
long datatypes
Description
bool ovrimos_longreadlen ( int $result_id , int $length )
Specifies how many bytes are to be retrieved from long datatypes (long
varchar and long varbinary).
Parameters
result_id
A result identifier, returned by ovrimos_execute() or
ovrimos_exec().
length
The number of bytes to retrieve. Default is zero.
Return Values
Returns TRUE.
----------------------------------------------------------------------
----------------------------------------------------------------------
ovrimos_num_fields
(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)
ovrimos_num_fields - Returns the number of columns
Description
int ovrimos_num_fields ( int $result_id )
Returns the number of columns in the specified result identifier.
Parameters
result_id
A result identifier, returned by ovrimos_execute() or
ovrimos_exec().
Return Values
Returns the number of columns as an integer, or FALSE on error.
See Also
* ovrimos_num_rows() - Returns the number of rows affected by update
operations
----------------------------------------------------------------------
----------------------------------------------------------------------
ovrimos_num_rows
(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)
ovrimos_num_rows - Returns the number of rows affected by update
operations
Description
int ovrimos_num_rows ( int $result_id )
Gets the number of rows affected by update operations.
Parameters
result_id
A result identifier, returned by ovrimos_execute() or
ovrimos_exec().
Return Values
Returns the number of rows as an integer, or FALSE on error.
See Also
* ovrimos_num_fields() - Returns the number of columns
----------------------------------------------------------------------
----------------------------------------------------------------------
ovrimos_prepare
(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)
ovrimos_prepare - Prepares an SQL statement
Description
int ovrimos_prepare ( int $connection_id , string $query )
Prepares an SQL statement.
Parameters
connection_id
The Ovrimos connection identifier, returned by ovrimos_connect().
query
The SQL statement.
Return Values
Returns a result identifier on success, or FALSE on error.
Examples
Example #1 ovrimos_prepare() Example
----------------------------------------------------------------------
----------------------------------------------------------------------
ovrimos_result_all
(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)
ovrimos_result_all - Prints the whole result set as an HTML table
Description
int ovrimos_result_all ( int $result_id [, string $format ] )
Prints the whole result set as an HTML table.
Parameters
result_id
A result identifier, returned by ovrimos_execute() or
ovrimos_exec().
format
Optional HTML attributes for the generated table element.
Return Values
Returns the number of rows in the generated table.
Examples
This will execute an SQL statement and print the result in an HTML table.
Example #1 Prepare a statement, execute, and view the result
Example #2 ovrimos_result_all() with meta-information
----------------------------------------------------------------------
----------------------------------------------------------------------
ovrimos_result
(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)
ovrimos_result - Retrieves the output column
Description
string ovrimos_result ( int $result_id , mixed $field )
Retrieves the output column specified by field.
Parameters
result_id
A result identifier, returned by ovrimos_execute() or
ovrimos_exec().
field
Either as a string with the field name or as an 1-based index.
Return Values
Returns the column as a string, FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
ovrimos_rollback
(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)
ovrimos_rollback - Rolls back the transaction
Description
bool ovrimos_rollback ( int $connection_id )
Rolls back the transaction.
Parameters
connection_id
The Ovrimos connection identifier, returned by ovrimos_connect().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* ovrimos_commit() - Commits the transaction
----------------------------------------------------------------------
Table of Contents
* ovrimos_close - Closes the connection to ovrimos
* ovrimos_commit - Commits the transaction
* ovrimos_connect - Connect to the specified database
* ovrimos_cursor - Returns the name of the cursor
* ovrimos_exec - Executes an SQL statement
* ovrimos_execute - Executes a prepared SQL statement
* ovrimos_fetch_into - Fetches a row from the result set
* ovrimos_fetch_row - Fetches a row from the result set
* ovrimos_field_len - Returns the length of the output column
* ovrimos_field_name - Returns the output column name
* ovrimos_field_num - Returns the (1-based) index of the output column
* ovrimos_field_type - Returns the type of the output column
* ovrimos_free_result - Frees the specified result_id
* ovrimos_longreadlen - Specifies how many bytes are to be retrieved
from long datatypes
* ovrimos_num_fields - Returns the number of columns
* ovrimos_num_rows - Returns the number of rows affected by update
operations
* ovrimos_prepare - Prepares an SQL statement
* ovrimos_result_all - Prints the whole result set as an HTML table
* ovrimos_result - Retrieves the output column
* ovrimos_rollback - Rolls back the transaction
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* Basic usage
* Ovrimos SQL Functions
* ovrimos_close - Closes the connection to ovrimos
* ovrimos_commit - Commits the transaction
* ovrimos_connect - Connect to the specified database
* ovrimos_cursor - Returns the name of the cursor
* ovrimos_exec - Executes an SQL statement
* ovrimos_execute - Executes a prepared SQL statement
* ovrimos_fetch_into - Fetches a row from the result set
* ovrimos_fetch_row - Fetches a row from the result set
* ovrimos_field_len - Returns the length of the output column
* ovrimos_field_name - Returns the output column name
* ovrimos_field_num - Returns the (1-based) index of the output
column
* ovrimos_field_type - Returns the type of the output column
* ovrimos_free_result - Frees the specified result_id
* ovrimos_longreadlen - Specifies how many bytes are to be
retrieved from long datatypes
* ovrimos_num_fields - Returns the number of columns
* ovrimos_num_rows - Returns the number of rows affected by update
operations
* ovrimos_prepare - Prepares an SQL statement
* ovrimos_result_all - Prints the whole result set as an HTML table
* ovrimos_result - Retrieves the output column
* ovrimos_rollback - Rolls back the transaction
----------------------------------------------------------------------
----------------------------------------------------------------------
Paradox File Access
----------------------------------------------------------------------
Introduction
This module allows to read and write Paradox databases, primary index
files and blob files. Write support has been proven to be quite reliable,
though due to lack of documentation the produced files may not in any case
be readable by other applications. Encrypted databases can be read without
specifying a password if pxlib >= 0.5.0 is used.
Note:
This module is also in development and may change, though major changes
to the API are not expected.
Warning
This extension is EXPERIMENTAL. The behaviour of this extension including
the names of its functions and any other documentation surrounding this
extension may change without notice in a future release of PHP. This
extension should be used at your own risk.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
You need at least PHP 5.0.0 and pxlib >= 0.4.4 for the basic set of
functions. Some newer functions are only available with pxlib >= 0.6.0.
Reading and writing of encrypted databases requires at least pxlib >=
0.5.0. The paradox library (pxlib) is available at
>> http://pxlib.sourceforge.net.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here: >> http://pecl.php.net/package/paradox
Make sure you have pxlib installed before. If you install pxlib from an
rpm or debian package, do not forget to install the development package as
well.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
px_new() creates a new Paradox object required by all Paradox functions.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
The following two tables lists all constants defined by the paradox
extension.
Contants for field types
Name Meaning
PX_FIELD_ALPHA Character data with fixed length
PX_FIELD_DATE Date, number of days since 1.1.0000
PX_FIELD_SHORT Short integer (2 Bytes)
PX_FIELD_LONG Long integer (4 Bytes)
PX_FIELD_CURRENCY same as PX_FIELD_NUMBER
PX_FIELD_NUMBER Double
PX_FIELD_LOGICAL Boolean
PX_FIELD_MEMOBLOB Binary large object
PX_FIELD_BLOB Binary large object (not supported)
PX_FIELD_FMTMEMOBLOB Binary large object
PX_FIELD_OLE OLE object (basically a blob, not supported)
PX_FIELD_GRAPHIC Graphic (basically a blob, not supported)
PX_FIELD_TIME time, number of milli seconds since midnight
PX_FIELD_TIMESTAMP timestamp, number of milli seconds since 1.1.0000
PX_FIELD_AUTOINC Auto incrementing interger (like PX_FIELD_LONG)
PX_FIELD_BCD Decimal number stored in bcd format (not supported)
PX_FIELD_BYTES Array of Bytes with not more than 255 bytes (not
supported)
PX_KEYTOLOWER Turn all field names into lower case
PX_KEYTOUPPER Turn all field names into upper case
Contants for file types
Name Meaning
PX_FILE_INDEX_DB Indexed database
PX_FILE_PRIM_INDEX Primary index
PX_FILE_NON_INDEX_DB None indexed database
PX_FILE_NON_INC_SEC_INDEX None incremental secondary index
PX_FILE_SEC_INDEX Secondary index
PX_FILE_INC_SEC_INDEX Incremental secondary index
PX_FILE_NON_INC_SEC_INDEX_G Non incremental secondary index
PX_FILE_SEC_INDEX_G Secondary index
PX_FILE_INC_SEC_INDEX_G Non incremental secondary index
----------------------------------------------------------------------
----------------------------------------------------------------------
Paradox Functions
Object oriented API
The paradox extension provides also an object oriented API. It consists of
only one class called paradox_db. Its methods only differ from the
functions in its name and of course the missing first parameter. The
following table will list all methods and its equivalent functions.
Methods of class paradox_db
Name of method Equivalent function
Constructor px_new()
Destructor px_delete()
open_fp() px_open_fp()
create_fp() px_create_fp()
close() px_close()
numrecords() px_numrecords()
numfields() px_numfields()
get_record() px_get_record()
put_record() px_put_record()
retrieve_record() px_retrieve_record()
delete_record() px_delete_record()
insert_record() px_insert_record()
update_record() px_update_record()
get_field() px_get_field()
get_schema() px_get_schema()
get_info() px_get_info()
set_parameter() px_set_parameter()
get_parameter() px_get_parameter()
set_value() px_set_value()
get_value() px_get_value()
get_info() px_get_info()
set_targetencoding() px_set_targetencoding()
set_tablename() px_set_tablename()
set_blob_file() px_set_blob_file()
date2string() px_date2string()
timestamp2string() px_timestamp2string()
----------------------------------------------------------------------
px_close
(PECL paradox >= 1.0.0)
px_close - Closes a paradox database
Description
bool px_close ( resource $pxdoc )
Closes the paradox database. This function will not close the file. You
will have to call fclose() afterwards.
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* px_open_fp() - Open paradox database
* The example at px_new() - Create a new paradox object
----------------------------------------------------------------------
----------------------------------------------------------------------
px_create_fp
(PECL paradox >= 1.0.0)
px_create_fp - Create a new paradox database
Description
bool px_create_fp ( resource $pxdoc , resource $file , array $fielddesc )
Create a new paradox database file. The actual file has to be opened
before with fopen(). Make sure the file is writable.
Note:
Calling this functions issues a warning about an empty tablename which
can be safely ignored. Just set the tablename afterwards with
px_set_parameter().
Note:
This function is highly experimental, due to insufficient documentation
of the paradox file format. Database files created with this function
can be opened by px_open_fp() and has been successfully opened by the
Paradox software, but your milage may vary.
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
file
File handle as returned by fopen().
fielddesc
fielddesc is an array containing one element for each field
specification. A field specification is an array itself with
either two or three elements.The first element is always a string
value used as the name of the field. It may not be larger than ten
characters. The second element contains the field type which is
one of the constants listed in the table Constants for field
types. In the case of a character field or bcd field, you will
have to provide a third element specifying the length respectively
the precesion of the field. If your field specification contains
blob fields, you will have to make sure to either make the field
large enough for all field values to fit or specify a blob file
with px_set_blob_file() for storing the blobs. If this is not done
the field data is truncated.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Creating a Paradox database with two fields
See Also
* px_new() - Create a new paradox object
* px_put_record() - Stores record into paradox database
* fopen() - Opens file or URL
----------------------------------------------------------------------
----------------------------------------------------------------------
px_date2string
(PECL paradox >= 1.4.0)
px_date2string - Converts a date into a string.
Description
string px_date2string ( resource $pxdoc , int $value , string $format )
Turns a date as it stored in the paradox file into human readable format.
Paradox dates are the number of days since 1.1.0000. This function is just
for convenience. It can be easily replaced by some math and the calendar
functions as demonstrated in the example below.
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
value
Value as stored in paradox database field of type PX_FIELD_DATE.
format
String format similar to the format used by date(). The
placeholders support by this function is a subset of those
supported by date() (Y, y, m, n, d, j, L).
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Turn a paradox date into a human readable form
The above example will output:
7/15/1917
7/15/1917
See Also
* px_timestamp2string() - Converts the timestamp into a string.
* jdtogregorian() - Converts Julian Day Count to Gregorian date
----------------------------------------------------------------------
----------------------------------------------------------------------
px_delete_record
(PECL paradox >= 1.4.0)
px_delete_record - Deletes record from paradox database
Description
bool px_delete_record ( resource $pxdoc , int $num )
This function deletes a record from the database. It does not free the
space in the database file but just marks it as deleted. Inserting a new
record afterwards will reuse the space.
Note:
This function is only available if pxlib >= 0.6.0 is used.
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
num
The record number is an artificial number counting records in the
order as they are stored in the database. The first record has
number 0.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
px_delete
(PECL paradox >= 1.0.0)
px_delete - Deletes resource of paradox database
Description
bool px_delete ( resource $pxdoc )
Deletes the resource of the paradox file and frees all memory.
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
px_get_field
(PECL paradox >= 1.0.0)
px_get_field - Returns the specification of a single field
Description
array px_get_field ( resource $pxdoc , int $fieldno )
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
fieldno
Number of the field. The first field has number 0. Specifying a
field number less than 0 and greater or equal the number of fields
will trigger an error.
Return Values
Returns the specification of the fieldno 'th database field as an
associated array. The array contains three fields named name, type, and
size.
----------------------------------------------------------------------
----------------------------------------------------------------------
px_get_info
(PECL paradox >= 1.0.0)
px_get_info - Return lots of information about a paradox file
Description
array px_get_info ( resource $pxdoc )
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
Return Values
Returns an associated array with lots of information about a paradox file.
This array is likely to be extended in the future.
fileversion
Version of file multiplied by 10, e.g. 70.
tablename
Name of table as stored in the file. If the database was created
by pxlib, then this will be the name of the file without the
extension.
numrecords
Number of records in this table.
numfields
Number of fields in this table.
headersize
Number of bytes used for the header. This is usually 0x800.
recordsize
Number of bytes used for each record. This is the sum of all field
sizes (available since version 1.4.2).
maxtablesize
This value multiplied by 0x400 is the size of a data block in
bytes. The maximum number of records in a datablock is the integer
part of (maxtablesize * 0x400 - 8) / recordsize.
numdatablocks
The number of data blocks in the file. Each data block contains a
certain number of records which depends on the record size and the
data block size (maxtablesize). Data blocks may not necessarily be
completely filled.
numindexfields
Number of fields used for the primary index. The fields do always
start with field number 1.
codepage
The DOS codepage which was used for encoding fields with character
data. If the target encoding is not set with
px_set_targetencoding() this will be the encoding for character
fields when records are being accessed with px_get_record() or
px_retrieve_record().
See Also
* px_numfields() - Returns number of fields in a database
* px_numrecords() - Returns number of records in a database
----------------------------------------------------------------------
----------------------------------------------------------------------
px_get_parameter
(PECL paradox >= 1.1.0)
px_get_parameter - Gets a parameter
Description
string px_get_parameter ( resource $pxdoc , string $name )
Gets various parameters.
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
name
The name can be one of the following:
tablename
The name of the table as it will be stored in the
database header.
targetencoding
The encoding for the output. Data which is being read
from character fields with px_get_record() or
px_retrieve_record() is recoded into the
targetencoding. If it is not set, then the data will
be delivered as stored in the database file.
inputencoding
The encoding of the input data which is to be stored
into the database. When storing data of character
fields in the database, the data is expected to be
delivered in this encoding.
Return Values
Returns the value of the parameter or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
px_get_record
(PECL paradox >= 1.0.0)
px_get_record - Returns record of paradox database
Description
array px_get_record ( resource $pxdoc , int $num [, int $mode = 0 ] )
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
num
The record number is an artificial number counting records in the
order as they are stored in the database. The first record has
number 0.
mode
The optional mode can be PX_KEYTOLOWER or PX_KEYTOUPPER in order
to convert the keys of the returned array into lower or upper
case. If mode is not passed or is 0, then the key will be exactly
like the field name. The element values will contain the field
values. NULL values will be retained and are different from 0.0, 0
or the empty string. Fields of type PX_FIELD_TIME will be returned
as an integer counting the number of milliseconds starting at
midnight. A timestamp (PX_FIELD_TIMESTAMP) and date
(PX_FIELD_DATE) are floating point respectively int values
counting milliseconds respectively days starting at the beginning
of julian calendar. Use the functions px-timestamp2string() and
px-date2string() to convert them into a character representation.
Return Values
Returns the num'th record from the paradox database. The record is
returned as an associated array with its keys being the field names.
See Also
* px_retrieve_record() - Returns record of paradox database
----------------------------------------------------------------------
----------------------------------------------------------------------
px_get_schema
(PECL paradox >= 1.0.0)
px_get_schema - Returns the database schema
Description
array px_get_schema ( resource $pxdoc [, int $mode = 0 ] )
px_get_schema() returns the database schema.
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
mode
If the optional mode is PX_KEYTOLOWER or PX_KEYTOUPPER the keys of
the returned array will be converted to lower or upper case. If
mode is 0 or not passed at all, then the key name will be
identical to the field name.
Return Values
Returns the schema of a database file as an associated array. The key name
is equal to the field name. Each array element is itself an associated
array containing the two fields type and size. type is one of the
constants in table Constants for field types. size is the number of bytes
this field consumes in the record. The total of all field sizes is equal
to the record size as it can be retrieved with px-get-info().
----------------------------------------------------------------------
----------------------------------------------------------------------
px_get_value
(PECL paradox >= 1.1.0)
px_get_value - Gets a value
Description
float px_get_value ( resource $pxdoc , string $name )
Gets various values.
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
name
name can be one of the following.
numprimkeys
The number of primary keys. Paradox databases always
use the first numprimkeys fields for the primary
index.
Return Values
Returns the value of the parameter or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
px_insert_record
(PECL paradox >= 1.4.0)
px_insert_record - Inserts record into paradox database
Description
int px_insert_record ( resource $pxdoc , array $data )
Inserts a new record into the database. The record is not necessarily
inserted at the end of the database, but may be inserted at any position
depending on where the first free slot is found.
The record data is passed as an array of field values. The elements in the
array must correspond to the fields in the database. If the array has less
elements than fields in the database, the remaining fields will be set to
null.
Most field values can be passed as its equivalent php type e.g. a long
value is used for fields of type PX_FIELD_LONG, PX_FIELD_SHORT and
PX_FIELD_AUTOINC, a double values is used for fields of type
PX_FIELD_CURRENCY and PX_FIELD_NUMBER. Field values for blob and alpha
fields are passed as strings.
Fields of type PX_FIELD_TIME and PX_FIELD_DATE both require a long value.
In the first case this is the number of milliseconds since midnight. In
the second case this is the number of days since 1.1.0000. Below there are
two examples to convert the current date or timestamp into a value
suitable for one of paradox's date/time fields.
Note:
This function is only available if pxlib >= 0.6.0 is used.
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
data
Associated or indexed array containing the field values as e.g.
returned by px_retrieve_record().
Return Values
Returns FALSE on failure or the record number in case of success.
Examples
Example #1 Set the date/time fields in a paradox database to the current
date/time
The above example will output:
2/21/2006 21:42:30
2/21/2006
2/21/2006 20:42:30
2/21/2006
The Julian day count as passed to jdtogregorian() has a different base of
1.1.4714 b.c. and must therefore be calculated by adding 1721425 to the
day count used in the paradox file. Turning the day count into a timestamp
is easily done by multiplying with 86400000.0 to obtain milli seconds.
See Also
px_update_record() - Updates record in paradox database
----------------------------------------------------------------------
----------------------------------------------------------------------
px_new
(PECL paradox >= 1.0.0)
px_new - Create a new paradox object
Description
resource px_new ( void )
Create a new paradox object. You will have to call this function before
any further functions. px_new() does not create any file on the disk, it
just creates an instance of a paradox object. This function must not be
called if the object oriented interface is used. Use new paradox_db()
instead.
Return Values
Returns FALSE on failure.
Examples
Example #1 Opening a Paradox database
If you prefer the object oriented API, then the above example will look
like the following.
Example #2 Opening a Paradox database
open_fp($fp)) {
/* Error handling */
}
// ...
$pxdoc->close();
fclose($fp);
?>
See Also
* px_delete() - Deletes resource of paradox database
* px_open_fp() - Open paradox database
----------------------------------------------------------------------
----------------------------------------------------------------------
px_numfields
(PECL paradox >= 1.0.0)
px_numfields - Returns number of fields in a database
Description
int px_numfields ( resource $pxdoc )
Get the number of fields in a database file.
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
Return Values
Returns the number of fields in a database file. The return value of this
function is identical to the element numfields in the array returned by
px_get_info().
----------------------------------------------------------------------
----------------------------------------------------------------------
px_numrecords
(PECL paradox >= 1.0.0)
px_numrecords - Returns number of records in a database
Description
int px_numrecords ( resource $pxdoc )
Get the number of records in a database file.
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
Return Values
Returns the number of records in a database file. The return value of this
function is identical to the element numrecords in the array returned by
px_get_info().
----------------------------------------------------------------------
----------------------------------------------------------------------
px_open_fp
(PECL paradox >= 1.0.0)
px_open_fp - Open paradox database
Description
bool px_open_fp ( resource $pxdoc , resource $file )
Open an existing paradox database file. The actual file has to be opened
before with fopen(). This function can also be used to open primary index
files and tread them like a paradox database. This is supported for those
who would like to investigate a primary index. It cannot be used to
accelerate access to a database file.
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
file
file is the return value from fopen() with the actual database
file as parameter. Make sure the database is writable if you plan
to update or insert records.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* fopen() - Opens file or URL
* The example at px_new() - Create a new paradox object
----------------------------------------------------------------------
----------------------------------------------------------------------
px_put_record
(PECL paradox >= 1.0.0)
px_put_record - Stores record into paradox database
Description
bool px_put_record ( resource $pxdoc , array $record [, int $recpos = -1 ]
)
Stores a record into a paradox database. The record is always added at the
end of the database, regardless of any free slots. Use px_insert_record()
to add a new record into the first free slot found in the database.
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
record
Associated or indexed array containing the field values as e.g.
returned by px_retrieve_record().
recpos
This optional parameter may be used to specify a record number
greater than the current number of records in the database. The
function will add as many empty records as needed. There is hardly
any need for this parameter.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
px_retrieve_record
(PECL paradox >= 1.4.0)
px_retrieve_record - Returns record of paradox database
Description
array px_retrieve_record ( resource $pxdoc , int $num [, int $mode = 0 ] )
This function is very similar to px_get_record() but uses internally a
different approach to retrieve the data. It relies on pxlib for reading
each single field value, which usually results in support for more field
types.
Note:
This function is only available if pxlib >= 0.6.0 is used.
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
num
The record number is an artificial number counting records in the
order as they are stored in the database. The first record has
number 0.
mode
The optional mode can be PX_KEYTOLOWER or PX_KEYTOUPPER in order
to convert the keys into lower or upper case. If mode is not
passed or is 0, then the key will be exactly like the field name.
The element values will contain the field values. NULL values will
be retained and are different from 0.0, 0 or the empty string.
Fields of type PX_FIELD_TIME will be returned as an integer
counting the number of milliseconds starting at midnight. A
timestamp is a floating point value also counting milliseconds
starting at the beginning of julian calendar.
Return Values
Returns the num'th record from the paradox database. The record is
returned as an associated array with its keys being the field names.
See Also
* px_get_record() - Returns record of paradox database
----------------------------------------------------------------------
----------------------------------------------------------------------
px_set_blob_file
(PECL paradox >= 1.3.0)
px_set_blob_file - Sets the file where blobs are read from
Description
bool px_set_blob_file ( resource $pxdoc , string $filename )
Sets the name of the file where blobs are going to be read from or written
into. Without calling this function, px_get_record() or
px_retrieve_record() will only return data in blob fields if the data is
part of the record and not stored in the blob file. Blob data is stored in
the record if it is small enough to fit in the size of the blob field.
Calling px_put_record(), px_insert_record(), or px_update_record() without
calling px_set_blob_file() will result in truncated blob fields unless the
data fits into the database file.
Calling this function twice will close the first blob file and open the
new one.
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
filename
The name of the file. Its extension should be .MB.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
px_set_parameter
(PECL paradox >= 1.1.0)
px_set_parameter - Sets a parameter
Description
bool px_set_parameter ( resource $pxdoc , string $name , string $value )
Sets various parameters.
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
name
Depending on the parameter you want to set, name can be one of the
following.
tablename
The name of the table as it will be stored in the
database header.
targetencoding
The encoding for the output. Data which is being read
from character fields is recoded into the
targetencoding.
inputencoding
The encoding of the input data which is to be stored
into the database.
value
The value of parameter to set. For inputencoding and
targetencoding this must be the name of the encoding as understood
by iconv or recode, e.g. iso-8859-1, utf-8, cp850.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* px_get_info() - Return lots of information about a paradox file to
determine the DOS code page.
----------------------------------------------------------------------
----------------------------------------------------------------------
px_set_tablename
(PECL paradox >= 1.0.0)
px_set_tablename - Sets the name of a table (deprecated)
Description
void px_set_tablename ( resource $pxdoc , string $name )
Sets the table name of a paradox database, which was created with
px_create_fp(). This function is deprecated use px_set_parameter()
instead.
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
tablename
The name of the table. If it is not set explicitly it will be set
to the name of the database file.
Return Values
Returns NULL on success or FALSE on failure.
See Also
px_set_parameter() - Sets a parameter
----------------------------------------------------------------------
----------------------------------------------------------------------
px_set_targetencoding
(PECL paradox >= 1.0.0)
px_set_targetencoding - Sets the encoding for character fields
(deprecated)
Description
bool px_set_targetencoding ( resource $pxdoc , string $encoding )
Set the encoding for data retrieved from a character field. All character
fields will be recoded to the encoding set by this function. If the
encoding is not set, the character data will be returned in the DOS code
page encoding as specified in the database file. The encoding can be any
string identifier known to iconv or recode. On Unix systems run iconv -l
for a list of available encodings.
This function is deprecated and should be replaced by calling
px_set_parameter().
See also px_get_info() to determine the DOS code page as stored in the
database file.
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
encoding
The encoding for the output. Data which is being read from
character fields is recoded into the targetencoding.
Return Values
Returns FALSE if the encoding could not be set, e.g. the encoding is
unknown, or pxlib does not support recoding at all. In the second case a
warning will be issued.
See Also
px_set_parameter() - Sets a parameter
----------------------------------------------------------------------
----------------------------------------------------------------------
px_set_value
(PECL paradox >= 1.1.0)
px_set_value - Sets a value
Description
bool px_set_value ( resource $pxdoc , string $name , float $value )
Sets various values.
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
name
name can be one of the following.
numprimkeys
The number of primary keys. Paradox databases always
use the first numprimkeys fields for the primary
index.
value
Return Values
Returns TRUE on success or FALSE on failure.
See Also
px_set_parameter() - Sets a parameter
----------------------------------------------------------------------
----------------------------------------------------------------------
px_timestamp2string
(PECL paradox >= 1.4.0)
px_timestamp2string - Converts the timestamp into a string.
Description
string px_timestamp2string ( resource $pxdoc , float $value , string
$format )
Turns a timestamp as it stored in the paradox file into human readable
format. Paradox timestamps are the number of miliseconds since 0001-01-02.
This function is just for convenience. It can be easily replaced by some
math and the calendar functions as demonstrated in the following example.
Parameters
pxdoc
Resource identifier of the paradox database.
value
Value as stored in paradox database field of type PX_FIELD_TIME,
or PX_FIELD_TIMESTAMP.
format
String format similar to the format used by date(). The
placeholders support by this function is a subset of those
supported by date() (Y, y, m, n, d, j, H, h, G, g, i, s, A, a, L).
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Turn a paradox timestamp into a human readable form
The above example will output:
7/15/1917
7/15/1917 01:00:00
The Julian day count as passed to jdtogregorian() has a different base of
1.1.4714 b.c. and must therefore be calculated by adding 1721425 to the
day count used in the paradox file. Turning the day count into a timestamp
is easily done by multiplying with 86400000.0 to obtain miliseconds.
See Also
* px_date2string() - Converts a date into a string.
* jdtogregorian() - Converts Julian Day Count to Gregorian date
----------------------------------------------------------------------
----------------------------------------------------------------------
px_update_record
(PECL paradox >= 1.4.0)
px_update_record - Updates record in paradox database
Description
bool px_update_record ( resource $pxdoc , array $data , int $num )
Updates an exiting record in the database. The record starts at 0.
The record data is passed as an array of field values. The elements in the
array must correspond to the fields in the database. If the array has less
elements than fields in the database, the remaining fields will be set to
null.
Note:
This function is only available if pxlib >= 0.6.0 is used.
Parameters
pxdoc
Resource identifier of the paradox database as returned by
px_new().
data
Associated array containing the field values as returned by
px_retrieve_record().
num
The record number is an artificial number counting records in the
order as they are stored in the database. The first record has
number 0.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
px_insert_record() - Inserts record into paradox database
----------------------------------------------------------------------
Table of Contents
* px_close - Closes a paradox database
* px_create_fp - Create a new paradox database
* px_date2string - Converts a date into a string.
* px_delete_record - Deletes record from paradox database
* px_delete - Deletes resource of paradox database
* px_get_field - Returns the specification of a single field
* px_get_info - Return lots of information about a paradox file
* px_get_parameter - Gets a parameter
* px_get_record - Returns record of paradox database
* px_get_schema - Returns the database schema
* px_get_value - Gets a value
* px_insert_record - Inserts record into paradox database
* px_new - Create a new paradox object
* px_numfields - Returns number of fields in a database
* px_numrecords - Returns number of records in a database
* px_open_fp - Open paradox database
* px_put_record - Stores record into paradox database
* px_retrieve_record - Returns record of paradox database
* px_set_blob_file - Sets the file where blobs are read from
* px_set_parameter - Sets a parameter
* px_set_tablename - Sets the name of a table (deprecated)
* px_set_targetencoding - Sets the encoding for character fields
(deprecated)
* px_set_value - Sets a value
* px_timestamp2string - Converts the timestamp into a string.
* px_update_record - Updates record in paradox database
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Paradox Functions
* px_close - Closes a paradox database
* px_create_fp - Create a new paradox database
* px_date2string - Converts a date into a string.
* px_delete_record - Deletes record from paradox database
* px_delete - Deletes resource of paradox database
* px_get_field - Returns the specification of a single field
* px_get_info - Return lots of information about a paradox file
* px_get_parameter - Gets a parameter
* px_get_record - Returns record of paradox database
* px_get_schema - Returns the database schema
* px_get_value - Gets a value
* px_insert_record - Inserts record into paradox database
* px_new - Create a new paradox object
* px_numfields - Returns number of fields in a database
* px_numrecords - Returns number of records in a database
* px_open_fp - Open paradox database
* px_put_record - Stores record into paradox database
* px_retrieve_record - Returns record of paradox database
* px_set_blob_file - Sets the file where blobs are read from
* px_set_parameter - Sets a parameter
* px_set_tablename - Sets the name of a table (deprecated)
* px_set_targetencoding - Sets the encoding for character fields
(deprecated)
* px_set_value - Sets a value
* px_timestamp2string - Converts the timestamp into a string.
* px_update_record - Updates record in paradox database
----------------------------------------------------------------------
----------------------------------------------------------------------
PostgreSQL
----------------------------------------------------------------------
Introduction
PostgreSQL database is Open Source product and available without cost.
Postgres, developed originally in the UC Berkeley Computer Science
Department, pioneered many of the object-relational concepts now becoming
available in some commercial databases. It provides SQL92/SQL99 language
support, transactions, referential integrity, stored procedures and type
extensibility. PostgreSQL is an open source descendant of this original
Berkeley code.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
To use PostgreSQL support, you need PostgreSQL 6.5 or later, PostgreSQL
8.0 or later to enable all PostgreSQL module features. PostgreSQL supports
many character encodings including multibyte character encoding. The
current version and more information about PostgreSQL is available at
>> http://www.postgresql.org/ and the >> PostgreSQL Documentation.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
In order to enable PostgreSQL support, --with-pgsql[=DIR] is required when
you compile PHP. DIR is the PostgreSQL base install directory, defaults to
/usr/local/pgsql. If shared object module is available, PostgreSQL module
may be loaded using extension directive in php.ini or dl() function.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
PostgreSQL configuration options
Name Default Changeable Changelog
pgsql.allow_persistent "1" PHP_INI_SYSTEM
pgsql.max_persistent "-1" PHP_INI_SYSTEM
pgsql.max_links "-1" PHP_INI_SYSTEM
pgsql.auto_reset_persistent "0" PHP_INI_SYSTEM Available since PHP
4.2.0.
pgsql.ignore_notice "0" PHP_INI_ALL Available since PHP
4.3.0.
pgsql.log_notice "0" PHP_INI_ALL Available since PHP
4.3.0.
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
pgsql.allow_persistent boolean
Whether to allow persistent Postgres connections.
pgsql.max_persistent integer
The maximum number of persistent Postgres connections per process.
pgsql.max_links integer
The maximum number of Postgres connections per process, including
persistent connections.
pgsql.auto_reset_persistent integer
Detect broken persistent links with pg_pconnect(). Needs a little
overhead.
pgsql.ignore_notice integer
Whether or not to ignore PostgreSQL backend notices.
pgsql.log_notice integer
Whether or not to log PostgreSQL backends notice messages. The PHP
directive pgsql.ignore_notice must be off in order to log notice
messages.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
There are two resource types used in the PostgreSQL module. The first one
is the link identifier for a database connection, the second a resource
which holds the result of a query.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
PGSQL_ASSOC (integer)
Passed to pg_fetch_array(). Return an associative array of field
names and values.
PGSQL_NUM (integer)
Passed to pg_fetch_array(). Return a numerically indexed array of
field numbers and values.
PGSQL_BOTH (integer)
Passed to pg_fetch_array(). Return an array of field values that
is both numerically indexed (by field number) and associated (by
field name).
PGSQL_CONNECT_FORCE_NEW (integer)
Passed to pg_connect() to force the creation of a new connection,
rather than re-using an existing identical connection.
PGSQL_CONNECTION_BAD (integer)
Returned by pg_connection_status() indicating that the database
connection is in an invalid state.
PGSQL_CONNECTION_OK (integer)
Returned by pg_connection_status() indicating that the database
connection is in a valid state.
PGSQL_SEEK_SET (integer)
Passed to pg_lo_seek(). Seek operation is to begin from the start
of the object.
PGSQL_SEEK_CUR (integer)
Passed to pg_lo_seek(). Seek operation is to begin from the
current position.
PGSQL_SEEK_END (integer)
Passed to pg_lo_seek(). Seek operation is to begin from the end of
the object.
PGSQL_EMPTY_QUERY (integer)
Returned by pg_result_status(). The string sent to the server was
empty.
PGSQL_COMMAND_OK (integer)
Returned by pg_result_status(). Successful completion of a command
returning no data.
PGSQL_TUPLES_OK (integer)
Returned by pg_result_status(). Successful completion of a command
returning data (such as a SELECT or SHOW).
PGSQL_COPY_OUT (integer)
Returned by pg_result_status(). Copy Out (from server) data
transfer started.
PGSQL_COPY_IN (integer)
Returned by pg_result_status(). Copy In (to server) data transfer
started.
PGSQL_BAD_RESPONSE (integer)
Returned by pg_result_status(). The server's response was not
understood.
PGSQL_NONFATAL_ERROR (integer)
Returned by pg_result_status(). A nonfatal error (a notice or
warning) occurred.
PGSQL_FATAL_ERROR (integer)
Returned by pg_result_status(). A fatal error occurred.
PGSQL_TRANSACTION_IDLE (integer)
Returned by pg_transaction_status(). Connection is currently idle,
not in a transaction.
PGSQL_TRANSACTION_ACTIVE (integer)
Returned by pg_transaction_status(). A command is in progress on
the connection. A query has been sent via the connection and not
yet completed.
PGSQL_TRANSACTION_INTRANS (integer)
Returned by pg_transaction_status(). The connection is idle, in a
transaction block.
PGSQL_TRANSACTION_INERROR (integer)
Returned by pg_transaction_status(). The connection is idle, in a
failed transaction block.
PGSQL_TRANSACTION_UNKNOWN (integer)
Returned by pg_transaction_status(). The connection is bad.
PGSQL_DIAG_SEVERITY (integer)
Passed to pg_result_error_field(). The severity; the field
contents are ERROR, FATAL, or PANIC (in an error message), or
WARNING, NOTICE, DEBUG, INFO, or LOG (in a notice message), or a
localized translation of one of these. Always present.
PGSQL_DIAG_SQLSTATE (integer)
Passed to pg_result_error_field(). The SQLSTATE code for the
error. The SQLSTATE code identifies the type of error that has
occurred; it can be used by front-end applications to perform
specific operations (such as error handling) in response to a
particular database error. This field is not localizable, and is
always present.
PGSQL_DIAG_MESSAGE_PRIMARY (integer)
Passed to pg_result_error_field(). The primary human-readable
error message (typically one line). Always present.
PGSQL_DIAG_MESSAGE_DETAIL (integer)
Passed to pg_result_error_field(). Detail: an optional secondary
error message carrying more detail about the problem. May run to
multiple lines.
PGSQL_DIAG_MESSAGE_HINT (integer)
Passed to pg_result_error_field(). Hint: an optional suggestion
what to do about the problem. This is intended to differ from
detail in that it offers advice (potentially inappropriate) rather
than hard facts. May run to multiple lines.
PGSQL_DIAG_STATEMENT_POSITION (integer)
Passed to pg_result_error_field(). A string containing a decimal
integer indicating an error cursor position as an index into the
original statement string. The first character has index 1, and
positions are measured in characters not bytes.
PGSQL_DIAG_INTERNAL_POSITION (integer)
Passed to pg_result_error_field(). This is defined the same as the
PG_DIAG_STATEMENT_POSITION field, but it is used when the cursor
position refers to an internally generated command rather than the
one submitted by the client. The PG_DIAG_INTERNAL_QUERY field will
always appear when this field appears.
PGSQL_DIAG_INTERNAL_QUERY (integer)
Passed to pg_result_error_field(). The text of a failed
internally-generated command. This could be, for example, a SQL
query issued by a PL/pgSQL function.
PGSQL_DIAG_CONTEXT (integer)
Passed to pg_result_error_field(). An indication of the context in
which the error occurred. Presently this includes a call stack
traceback of active procedural language functions and
internally-generated queries. The trace is one entry per line,
most recent first.
PGSQL_DIAG_SOURCE_FILE (integer)
Passed to pg_result_error_field(). The file name of the PostgreSQL
source-code location where the error was reported.
PGSQL_DIAG_SOURCE_LINE (integer)
Passed to pg_result_error_field(). The line number of the
PostgreSQL source-code location where the error was reported.
PGSQL_DIAG_SOURCE_FUNCTION (integer)
Passed to pg_result_error_field(). The name of the PostgreSQL
source-code function reporting the error.
PGSQL_ERRORS_TERSE (integer)
Passed to pg_set_error_verbosity(). Specified that returned
messages include severity, primary text, and position only; this
will normally fit on a single line.
PGSQL_ERRORS_DEFAULT (integer)
Passed to pg_set_error_verbosity(). The default mode produces
messages that include the above plus any detail, hint, or context
fields (these may span multiple lines).
PGSQL_ERRORS_VERBOSE (integer)
Passed to pg_set_error_verbosity(). The verbose mode includes all
available fields.
PGSQL_STATUS_LONG (integer)
Passed to pg_result_status(). Indicates that numerical result code
is desired.
PGSQL_STATUS_STRING (integer)
Passed to pg_result_status(). Indicates that textual result
command tag is desired.
PGSQL_CONV_IGNORE_DEFAULT (integer)
Passed to pg_convert(). Ignore default values in the table during
conversion.
PGSQL_CONV_FORCE_NULL (integer)
Passed to pg_convert(). Use SQL NULL in place of an empty string.
PGSQL_CONV_IGNORE_DEFAULT (integer)
Passed to pg_convert(). Ignore conversion of NULL into SQL NOT
NULL columns.
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Table of Contents
* Basic usage
----------------------------------------------------------------------
Basic usage
This simple example shows how to connect, execute a query, print resulting
rows and disconnect from a PostgreSQL database.
Example #1 PostgreSQL extension overview example
\n";
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
echo "\t\n";
foreach ($line as $col_value) {
echo "\t\t$col_value \n";
}
echo "\t \n";
}
echo "\n";
// Free resultset
pg_free_result($result);
// Closing connection
pg_close($dbconn);
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
PostgreSQL Functions
Notes
Note:
Not all functions are supported by all builds. It depends on your libpq
(The PostgreSQL C client library) version and how libpq is compiled. If
PHP PostgreSQL extensions are missing, then it is because your libpq
version does not support them.
Note:
Most PostgreSQL functions accept connection as the first optional
parameter. If it is not provided, the last opened connection is used. If
it doesn't exist, functions return FALSE.
Note:
PostgreSQL automatically folds all identifiers (e.g. table/column names)
to lower-case values at object creation time and at query time. To force
the use of mixed or upper case identifiers, you must escape the
identifier using double quotes ("").
Note:
PostgreSQL does not have special commands for fetching database schema
information (eg. all the tables in the current database). Instead, there
is a standard schema named information_schema in PostgreSQL 7.4 and
above containing system views with all the necessary information, in an
easily queryable form. See the >> PostgreSQL Documentation for full
details.
----------------------------------------------------------------------
pg_affected_rows
(PHP 4 >= 4.2.0, PHP 5)
pg_affected_rows - Returns number of affected records (tuples)
Description
int pg_affected_rows ( resource $result )
pg_affected_rows() returns the number of tuples (instances/records/rows)
affected by INSERT, UPDATE, and DELETE queries.
Note:
This function used to be called pg_cmdtuples().
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
Return Values
The number of rows affected by the query. If no tuple is affected, it will
return 0.
Examples
Example #1 pg_affected_rows() example
The above example will output:
1 tuples are affected.
See Also
* pg_query() - Execute a query
* pg_query_params() - Submits a command to the server and waits for the
result, with the ability to pass parameters separately from the SQL
command text.
* pg_execute() - Sends a request to execute a prepared statement with
given parameters, and waits for the result.
* pg_num_rows() - Returns the number of rows in a result
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_cancel_query
(PHP 4 >= 4.2.0, PHP 5)
pg_cancel_query - Cancel an asynchronous query
Description
bool pg_cancel_query ( resource $connection )
pg_cancel_query() cancels an asynchronous query sent with pg_send_query(),
pg_send_query_params() or pg_send_execute(). You cannot cancel a query
executed using pg_query().
Parameters
connection
PostgreSQL database connection resource.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 pg_cancel_query() example
The above example will output:
First call to pg_get_result(): Resource id #3
Resource id #3 has 3 records
See Also
* pg_send_query() - Sends asynchronous query
* pg_connection_busy() - Get connection is busy or not
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_client_encoding
(PHP 4 >= 4.0.3, PHP 5)
pg_client_encoding - Gets the client encoding
Description
string pg_client_encoding ([ resource $connection ] )
PostgreSQL supports automatic character set conversion between server and
client for certain character sets. pg_client_encoding() returns the client
encoding as a string. The returned string will be one of the standard
PostgreSQL encoding identifiers.
Note:
This function requires PHP 4.0.3 or higher and PostgreSQL 7.0 or higher.
If libpq is compiled without multibyte encoding support,
pg_client_encoding() always returns SQL_ASCII. Supported encoding
depends on PostgreSQL version. Refer to the PostgreSQL Documentation
supported encodings.
The function used to be called pg_clientencoding().
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
Return Values
The client encoding, or FALSE on error.
Examples
Example #1 pg_client_encoding() example
The above example will output:
Client encoding is: ISO-8859-1
See Also
* pg_set_client_encoding() - Set the client encoding
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_close
(PHP 4, PHP 5)
pg_close - Closes a PostgreSQL connection
Description
bool pg_close ([ resource $connection ] )
pg_close() closes the non-persistent connection to a PostgreSQL database
associated with the given connection resource.
Note:
Using pg_close() is not usually necessary, as non-persistent open
connections are automatically closed at the end of the script.
If there is open large object resource on the connection, do not close the
connection before closing all large object resources.
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 pg_close() example
The above example will output:
Connected successfully
See Also
* pg_connect() - Open a PostgreSQL connection
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_connect
(PHP 4, PHP 5)
pg_connect - Open a PostgreSQL connection
Description
resource pg_connect ( string $connection_string [, int $connect_type ] )
pg_connect() opens a connection to a PostgreSQL database specified by the
connection_string.
If a second call is made to pg_connect() with the same connection_string
as an existing connection, the existing connection will be returned unless
you pass PGSQL_CONNECT_FORCE_NEW as connect_type.
The old syntax with multiple parameters $conn = pg_connect("host", "port",
"options", "tty", "dbname") has been deprecated.
Parameters
connection_string
The connection_string can be empty to use all default parameters,
or it can contain one or more parameter settings separated by
whitespace. Each parameter setting is in the form keyword = value.
Spaces around the equal sign are optional. To write an empty value
or a value containing spaces, surround it with single quotes,
e.g., keyword = 'a value'. Single quotes and backslashes within
the value must be escaped with a backslash, i.e., \' and \\.
The currently recognized parameter keywords are: host, hostaddr,
port, dbname (defaults to value of user), user, password,
connect_timeout, options, tty (ignored), sslmode, requiressl
(deprecated in favor of sslmode), and service. Which of these
arguments exist depends on your PostgreSQL version.
The options parameter can be used to set command line parameters
to be invoked by the server.
connect_type
If PGSQL_CONNECT_FORCE_NEW is passed, then a new connection is
created, even if the connection_string is identical to an existing
connection.
Return Values
PostgreSQL connection resource on success, FALSE on failure.
Examples
Example #1 Using pg_connect()
See Also
* pg_pconnect() - Open a persistent PostgreSQL connection
* pg_close() - Closes a PostgreSQL connection
* pg_host() - Returns the host name associated with the connection
* pg_port() - Return the port number associated with the connection
* pg_tty() - Return the TTY name associated with the connection
* pg_options() - Get the options associated with the connection
* pg_dbname() - Get the database name
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_connection_busy
(PHP 4 >= 4.2.0, PHP 5)
pg_connection_busy - Get connection is busy or not
Description
bool pg_connection_busy ( resource $connection )
pg_connection_busy() determines whether or not a connection is busy. If it
is busy, a previous query is still executing. If pg_get_result() is used
on the connection, it will be blocked.
Parameters
connection
PostgreSQL database connection resource.
Return Values
Returns TRUE if the connection is busy, FALSE otherwise.
Examples
Example #1 pg_connection_busy() example
See Also
* pg_connection_status() - Get connection status
* pg_get_result() - Get asynchronous query result
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_connection_reset
(PHP 4 >= 4.2.0, PHP 5)
pg_connection_reset - Reset connection (reconnect)
Description
bool pg_connection_reset ( resource $connection )
pg_connection_reset() resets the connection. It is useful for error
recovery.
Parameters
connection
PostgreSQL database connection resource.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 pg_connection_reset() example
See Also
* pg_connect() - Open a PostgreSQL connection
* pg_pconnect() - Open a persistent PostgreSQL connection
* pg_connection_status() - Get connection status
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_connection_status
(PHP 4 >= 4.2.0, PHP 5)
pg_connection_status - Get connection status
Description
int pg_connection_status ( resource $connection )
pg_connection_status() returns the status of the specified connection.
Parameters
connection
PostgreSQL database connection resource.
Return Values
PGSQL_CONNECTION_OK or PGSQL_CONNECTION_BAD.
Examples
Example #1 pg_connection_status() example
See Also
* pg_connection_busy() - Get connection is busy or not
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_convert
(PHP 4 >= 4.3.0, PHP 5)
pg_convert - Convert associative array values into suitable for SQL
statement
Description
array pg_convert ( resource $connection , string $table_name , array
$assoc_array [, int $options = 0 ] )
pg_convert() checks and converts the values in assoc_array into suitable
values for use in an SQL statement. Precondition for pg_convert() is the
existence of a table table_name which has at least as many columns as
assoc_array has elements. The fieldnames in table_name must match the
indices in assoc_array and the corresponding datatypes must be compatible.
Returns an array with the converted values on success, FALSE otherwise.
Note:
If there are boolean fields in table_name don't use the constant TRUE in
assoc_array. It will be converted to the string 'TRUE' which is no valid
entry for boolean fields in PostgreSQL. Use one of t, true, 1, y, yes
instead.
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Parameters
connection
PostgreSQL database connection resource.
table_name
Name of the table against which to convert types.
assoc_array
Data to be converted.
options
Any number of PGSQL_CONV_IGNORE_DEFAULT, PGSQL_CONV_FORCE_NULL or
PGSQL_CONV_IGNORE_NOT_NULL, combined.
Return Values
An array of converted values, or FALSE on error.
Examples
Example #1 pg_convert() example
'Joe Thackery',
'year' => 2005,
'title' => 'My Life, by Joe Thackery'
);
$vals = pg_convert($dbconn, 'authors', $tmp);
?>
See Also
* pg_meta_data() - Get meta data for table
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_copy_from
(PHP 4 >= 4.2.0, PHP 5)
pg_copy_from - Insert records into a table from an array
Description
bool pg_copy_from ( resource $connection , string $table_name , array
$rows [, string $delimiter [, string $null_as ]] )
pg_copy_from() inserts records into a table from rows. It issues a COPY
FROM SQL command internally to insert records.
Parameters
connection
PostgreSQL database connection resource.
table_name
Name of the table into which to copy the rows.
rows
An array of data to be copied into table_name. Each value in rows
becomes a row in table_name. Each value in rows should be a
delimited string of the values to insert into each field. Values
should be linefeed terminated.
delimiter
The token that separates values for each field in each element of
rows. Default is TAB.
null_as
How SQL NULL values are represented in the rows. Default is \N
("\\N").
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 pg_copy_from() example
See Also
* pg_copy_to() - Copy a table to an array
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_copy_to
(PHP 4 >= 4.2.0, PHP 5)
pg_copy_to - Copy a table to an array
Description
array pg_copy_to ( resource $connection , string $table_name [, string
$delimiter [, string $null_as ]] )
pg_copy_to() copies a table to an array. It issues COPY TO SQL command
internally to retrieve records.
Parameters
connection
PostgreSQL database connection resource.
table_name
Name of the table from which to copy the data into rows.
delimiter
The token that separates values for each field in each element of
rows. Default is TAB.
null_as
How SQL NULL values are represented in the rows. Default is \N
("\\N").
Return Values
An array with one element for each line of COPY data. It returns FALSE on
failure.
Examples
Example #1 pg_copy_to() example
See Also
* pg_copy_from() - Insert records into a table from an array
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_dbname
(PHP 4, PHP 5)
pg_dbname - Get the database name
Description
string pg_dbname ([ resource $connection ] )
pg_dbname() returns the name of the database that the given PostgreSQL
connection resource.
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
Return Values
A string containing the name of the database the connection is to, or
FALSE on error.
Examples
Example #1 pg_dbname() example
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_delete
(PHP 4 >= 4.3.0, PHP 5)
pg_delete - Deletes records
Description
mixed pg_delete ( resource $connection , string $table_name , array
$assoc_array [, int $options = PGSQL_DML_EXEC ] )
pg_delete() deletes records from a table specified by the keys and values
in assoc_array. If options is specified, pg_convert() is applied to
assoc_array with the specified options.
Parameters
connection
PostgreSQL database connection resource.
table_name
Name of the table from which to delete rows.
assoc_array
An array whose keys are field names in the table table_name, and
whose values are the values of those fields that are to be
deleted.
options
Any number of PGSQL_CONV_FORCE_NULL, PGSQL_DML_NO_CONV,
PGSQL_DML_EXEC or PGSQL_DML_STRING combined. If PGSQL_DML_STRING
is part of the options then query string is returned.
Return Values
Returns TRUE on success or FALSE on failure. Returns string if
PGSQL_DML_STRING is passed via options.
Examples
Example #1 pg_delete() example
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
See Also
* pg_convert() - Convert associative array values into suitable for SQL
statement
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_end_copy
(PHP 4 >= 4.0.3, PHP 5)
pg_end_copy - Sync with PostgreSQL backend
Description
bool pg_end_copy ([ resource $connection ] )
pg_end_copy() syncs the PostgreSQL frontend (usually a web server process)
with the PostgreSQL server after doing a copy operation performed by
pg_put_line(). pg_end_copy() must be issued, otherwise the PostgreSQL
server may get out of sync with the frontend and will report an error.
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 pg_end_copy() example
See Also
* pg_put_line() - Send a NULL-terminated string to PostgreSQL backend
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_escape_bytea
(PHP 4 >= 4.2.0, PHP 5)
pg_escape_bytea - Escape a string for insertion into a bytea field
Description
string pg_escape_bytea ([ resource $connection ], string $data )
pg_escape_bytea() escapes string for bytea datatype. It returns escaped
string.
Note:
When you SELECT a bytea type, PostgreSQL returns octal byte values
prefixed with '\' (e.g. \032). Users are supposed to convert back to
binary format manually.
This function requires PostgreSQL 7.2 or later. With PostgreSQL 7.2.0
and 7.2.1, bytea values must be cast when you enable multi-byte support.
i.e. INSERT INTO test_table (image) VALUES ('$image_escaped'::bytea);
PostgreSQL 7.2.2 or later does not need a cast. The exception is when
the client and backend character encoding does not match, and there may
be multi-byte stream error. User must then cast to bytea to avoid this
error.
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
data
A string containing text or binary data to be inserted into a
bytea column.
Return Values
A string containing the escaped data.
Changelog
Version Description
5.2.0 connection added
Examples
Example #1 pg_escape_bytea() example
See Also
* pg_unescape_bytea() - Unescape binary for bytea type
* pg_escape_string() - Escape a string for insertion into a text field
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_escape_string
(PHP 4 >= 4.2.0, PHP 5)
pg_escape_string - Escape a string for insertion into a text field
Description
string pg_escape_string ([ resource $connection ], string $data )
pg_escape_string() escapes a string for insertion into the database. It
returns an escaped string in the PostgreSQL format. Use of this function
is recommended instead of addslashes(). If the type of the column is
bytea, pg_escape_bytea() must be used instead.
Note:
This function requires PostgreSQL 7.2 or later.
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
data
A string containing text to be escaped.
Return Values
A string containing the escaped data.
Changelog
Version Description
5.2.0 connection added
Examples
Example #1 pg_escape_string() example
See Also
* pg_escape_bytea() - Escape a string for insertion into a bytea field
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_execute
(PHP 5 >= 5.1.0)
pg_execute - Sends a request to execute a prepared statement with given
parameters, and waits for the result.
Description
resource pg_execute ([ resource $connection ], string $stmtname , array
$params )
Sends a request to execute a prepared statement with given parameters, and
waits for the result.
pg_execute() is like pg_query_params(), but the command to be executed is
specified by naming a previously-prepared statement, instead of giving a
query string. This feature allows commands that will be used repeatedly to
be parsed and planned just once, rather than each time they are executed.
The statement must have been prepared previously in the current session.
pg_execute() is supported only against PostgreSQL 7.4 or higher
connections; it will fail when using earlier versions.
The parameters are identical to pg_query_params(), except that the name of
a prepared statement is given instead of a query string.
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
stmtname
The name of the prepared statement to execute. if "" is specified,
then the unnamed statement is executed. The name must have been
previously prepared using pg_prepare(), pg_send_prepare() or a
PREPARE SQL command.
params
An array of parameter values to substitute for the $1, $2, etc.
placeholders in the original prepared query string. The number of
elements in the array must match the number of placeholders.
Warning
Elements are converted to strings by calling this function.
Return Values
A query result resource on success or FALSE on failure.
Examples
Example #1 Using pg_execute()
See Also
* pg_prepare() - Submits a request to create a prepared statement with
the given parameters, and waits for completion.
* pg_send_prepare() - Sends a request to create a prepared statement
with the given parameters, without waiting for completion.
* pg_query_params() - Submits a command to the server and waits for the
result, with the ability to pass parameters separately from the SQL
command text.
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_fetch_all_columns
(PHP 5 >= 5.1.0)
pg_fetch_all_columns - Fetches all rows in a particular result column as
an array
Description
array pg_fetch_all_columns ( resource $result [, int $column = 0 ] )
pg_fetch_all_columns() returns an array that contains all rows (records)
in a particular column of the result resource.
Note: This function sets NULL fields to the PHP NULL value.
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
column
Column number, zero-based, to be retrieved from the result
resource. Defaults to the first column if not specified.
Return Values
An array with all values in the result column.
FALSE is returned if column is larger than the number of columns in the
result, or on any other error.
Examples
Example #1 pg_fetch_all_columns() example
See Also
* pg_fetch_all() - Fetches all rows from a result as an array
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_fetch_all
(PHP 4 >= 4.3.0, PHP 5)
pg_fetch_all - Fetches all rows from a result as an array
Description
array pg_fetch_all ( resource $result )
pg_fetch_all() returns an array that contains all rows (records) in the
result resource.
Note: This function sets NULL fields to the PHP NULL value.
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
Return Values
An array with all rows in the result. Each row is an array of field values
indexed by field name.
FALSE is returned if there are no rows in the result, or on any other
error.
Examples
Example #1 PostgreSQL fetch all
The above example will output something similar to:
Array
(
[0] => Array
(
[id] => 1
[name] => Fred
)
[1] => Array
(
[id] => 2
[name] => Bob
)
)
See Also
* pg_fetch_row() - Get a row as an enumerated array
* pg_fetch_array() - Fetch a row as an array
* pg_fetch_object() - Fetch a row as an object
* pg_fetch_result() - Returns values from a result resource
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_fetch_array
(PHP 4, PHP 5)
pg_fetch_array - Fetch a row as an array
Description
array pg_fetch_array ( resource $result [, int $row [, int $result_type =
PGSQL_BOTH ]] )
pg_fetch_array() returns an array that corresponds to the fetched row
(record).
pg_fetch_array() is an extended version of pg_fetch_row(). In addition to
storing the data in the numeric indices (field number) to the result
array, it can also store the data using associative indices (field name).
It stores both indicies by default.
Note: This function sets NULL fields to the PHP NULL value.
pg_fetch_array() is NOT significantly slower than using pg_fetch_row(),
and is significantly easier to use.
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
row
Row number in result to fetch. Rows are numbered from 0 upwards.
If omitted or NULL, the next row is fetched.
result_type
An optional parameter that controls how the returned array is
indexed. result_type is a constant and can take the following
values: PGSQL_ASSOC, PGSQL_NUM and PGSQL_BOTH. Using PGSQL_NUM,
pg_fetch_array() will return an array with numerical indices,
using PGSQL_ASSOC it will return only associative indices while
PGSQL_BOTH, the default, will return both numerical and
associative indices.
Return Values
An array indexed numerically (beginning with 0) or associatively (indexed
by field name), or both. Each value in the array is represented as a
string. Database NULL values are returned as NULL.
FALSE is returned if row exceeds the number of rows in the set, there are
no more rows, or on any other error.
Changelog
Version Description
4.1.0 The row parameter became optional.
Examples
Example #1 pg_fetch_array() example
See Also
* pg_fetch_row() - Get a row as an enumerated array
* pg_fetch_object() - Fetch a row as an object
* pg_fetch_result() - Returns values from a result resource
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_fetch_assoc
(PHP 4 >= 4.3.0, PHP 5)
pg_fetch_assoc - Fetch a row as an associative array
Description
array pg_fetch_assoc ( resource $result [, int $row ] )
pg_fetch_assoc() returns an associative array that corresponds to the
fetched row (records).
pg_fetch_assoc() is equivalent to calling pg_fetch_array() with
PGSQL_ASSOC as the optional third parameter. It only returns an
associative array. If you need the numeric indices, use pg_fetch_row().
Note: This function sets NULL fields to the PHP NULL value.
pg_fetch_assoc() is NOT significantly slower than using pg_fetch_row(),
and is significantly easier to use.
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
row
Row number in result to fetch. Rows are numbered from 0 upwards.
If omitted or NULL, the next row is fetched.
Return Values
An array indexed associatively (by field name). Each value in the array is
represented as a string. Database NULL values are returned as NULL.
FALSE is returned if row exceeds the number of rows in the set, there are
no more rows, or on any other error.
Changelog
Version Description
4.1.0 The parameter row became optional.
Examples
Example #1 pg_fetch_assoc() example
See Also
* pg_fetch_row() - Get a row as an enumerated array
* pg_fetch_array() - Fetch a row as an array
* pg_fetch_object() - Fetch a row as an object
* pg_fetch_result() - Returns values from a result resource
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_fetch_object
(PHP 4, PHP 5)
pg_fetch_object - Fetch a row as an object
Description
object pg_fetch_object ( resource $result [, int $row [, int $result_type
= PGSQL_ASSOC ]] )
object pg_fetch_object ( resource $result [, int $row [, string
$class_name [, array $params ]]] )
pg_fetch_object() returns an object with properties that correspond to the
fetched row's field names. It can optionally instantiate an object of a
specific class, and pass parameters to that class's constructor.
Note: This function sets NULL fields to the PHP NULL value.
Speed-wise, the function is identical to pg_fetch_array(), and almost as
fast as pg_fetch_row() (the difference is insignificant).
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
row
Row number in result to fetch. Rows are numbered from 0 upwards.
If omitted or NULL, the next row is fetched.
result_type
Ignored and deprecated.
class_name
The name of the class to instantiate, set the properties of and
return. If not specified, a stdClass object is returned.
params
An optional array of parameters to pass to the constructor for
class_name objects.
Return Values
An object with one attribute for each field name in the result. Database
NULL values are returned as NULL.
FALSE is returned if row exceeds the number of rows in the set, there are
no more rows, or on any other error.
Changelog
Version Description
5.0.0 class_name and params were added. The old form with result_type
still exists for backwards compatibility.
4.3.0 result_type default changed from PGSQL_BOTH to PGSQL_ASSOC, since
the numeric index was illegal.
4.1.0 The parameter row became optional.
Examples
Example #1 pg_fetch_object() example
author . " (";
echo $data->year . "): ";
echo $data->title . " ";
}
pg_free_result($qu);
pg_close($db_conn);
?>
See Also
* pg_query() - Execute a query
* pg_fetch_array() - Fetch a row as an array
* pg_fetch_assoc() - Fetch a row as an associative array
* pg_fetch_row() - Get a row as an enumerated array
* pg_fetch_result() - Returns values from a result resource
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_fetch_result
(PHP 4 >= 4.2.0, PHP 5)
pg_fetch_result - Returns values from a result resource
Description
string pg_fetch_result ( resource $result , int $row , mixed $field )
string pg_fetch_result ( resource $result , mixed $field )
pg_fetch_result() returns the value of a particular row and field (column)
in a PostgreSQL result resource.
Note:
This function used to be called pg_result().
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
row
Row number in result to fetch. Rows are numbered from 0 upwards.
If omitted, next row is fetched.
field
A string representing the name of the field (column) to fetch,
otherwise an int representing the field number to fetch. Fields
are numbered from 0 upwards.
Return Values
Boolean is returned as "t" or "f". All other types, including arrays are
returned as strings formatted in the same default PostgreSQL manner that
you would see in the psql program. Database NULL values are returned as
NULL.
FALSE is returned if row exceeds the number of rows in the set, or on any
other error.
Examples
Example #1 pg_fetch_result() example
The above example will output:
First field in the second row is: 2
See Also
* pg_query() - Execute a query
* pg_fetch_array() - Fetch a row as an array
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_fetch_row
(PHP 4, PHP 5)
pg_fetch_row - Get a row as an enumerated array
Description
array pg_fetch_row ( resource $result [, int $row ] )
pg_fetch_row() fetches one row of data from the result associated with the
specified result resource.
Note: This function sets NULL fields to the PHP NULL value.
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
row
Row number in result to fetch. Rows are numbered from 0 upwards.
If omitted or NULL, the next row is fetched.
Return Values
An array, indexed from 0 upwards, with each value represented as a string.
Database NULL values are returned as NULL.
FALSE is returned if row exceeds the number of rows in the set, there are
no more rows, or on any other error.
Changelog
Version Description
4.1.0 The parameter row became optional.
Examples
Example #1 pg_fetch_row() example
\n";
}
?>
See Also
* pg_query() - Execute a query
* pg_fetch_array() - Fetch a row as an array
* pg_fetch_object() - Fetch a row as an object
* pg_fetch_result() - Returns values from a result resource
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_field_is_null
(PHP 4 >= 4.2.0, PHP 5)
pg_field_is_null - Test if a field is SQL NULL
Description
int pg_field_is_null ( resource $result , int $row , mixed $field )
int pg_field_is_null ( resource $result , mixed $field )
pg_field_is_null() tests if a field in a PostgreSQL result resource is SQL
NULL or not.
Note:
This function used to be called pg_fieldisnull().
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
row
Row number in result to fetch. Rows are numbered from 0 upwards.
If omitted, current row is fetched.
field
Field number (starting from 0) as an integer or the field name as
a string.
Return Values
Returns 1 if the field in the given row is SQL NULL, 0 if not. FALSE is
returned if the row is out of range, or upon any other error.
Examples
Example #1 pg_field_is_null() example
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_field_name
(PHP 4 >= 4.2.0, PHP 5)
pg_field_name - Returns the name of a field
Description
string pg_field_name ( resource $result , int $field_number )
pg_field_name() returns the name of the field occupying the given
field_number in the given PostgreSQL result resource. Field numbering
starts from 0.
Note:
This function used to be called pg_fieldname().
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
field_number
Field number, starting from 0.
Return Values
The field name, or FALSE on error.
Examples
Example #1 Getting information about fields
The above example will output:
column 0
fieldname: author
printed length: 6 characters
storage length: -1 bytes
field type: varchar
column 1
fieldname: year
printed length: 4 characters
storage length: 2 bytes
field type: int2
column 2
fieldname: title
printed length: 24 characters
storage length: -1 bytes
field type: varchar
See Also
* pg_field_num() - Returns the field number of the named field
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_field_num
(PHP 4 >= 4.2.0, PHP 5)
pg_field_num - Returns the field number of the named field
Description
int pg_field_num ( resource $result , string $field_name )
pg_field_num() will return the number of the field number that corresponds
to the field_name in the given PostgreSQL result resource.
Note:
This function used to be called pg_fieldnum().
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
field_name
The name of the field.
Return Values
The field number (numbered from 0), or -1 on error.
Examples
Example #1 Getting information about fields
The above example will output:
Column 'title' is field number: 2
See Also
* pg_field_name() - Returns the name of a field
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_field_prtlen
(PHP 4 >= 4.2.0, PHP 5)
pg_field_prtlen - Returns the printed length
Description
int pg_field_prtlen ( resource $result , int $row_number , mixed
$field_name_or_number )
int pg_field_prtlen ( resource $result , mixed $field_name_or_number )
pg_field_prtlen() returns the actual printed length (number of characters)
of a specific value in a PostgreSQL result. Row numbering starts at 0.
This function will return -1 on an error.
field_name_or_number can be passed either as an integer or as a string. If
it is passed as an integer, PHP recognises it as the field number,
otherwise as field name.
See the example given at the pg_field_name() page.
Note:
This function used to be called pg_fieldprtlen().
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
row
Row number in result. Rows are numbered from 0 upwards. If
omitted, current row is fetched.
Return Values
The field printed length, or FALSE on error.
Examples
Example #1 Getting information about fields
The above example will output:
column 0
fieldname: author
printed length: 6 characters
storage length: -1 bytes
field type: varchar
column 1
fieldname: year
printed length: 4 characters
storage length: 2 bytes
field type: int2
column 2
fieldname: title
printed length: 24 characters
storage length: -1 bytes
field type: varchar
See Also
* pg_field_size() - Returns the internal storage size of the named field
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_field_size
(PHP 4 >= 4.2.0, PHP 5)
pg_field_size - Returns the internal storage size of the named field
Description
int pg_field_size ( resource $result , int $field_number )
pg_field_size() returns the internal storage size (in bytes) of the field
number in the given PostgreSQL result.
Note:
This function used to be called pg_fieldsize().
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
field_number
Field number, starting from 0.
Return Values
The internal field storage size (in bytes). -1 indicates a variable length
field. FALSE is returned on error.
Examples
Example #1 Getting information about fields
The above example will output:
column 0
fieldname: author
printed length: 6 characters
storage length: -1 bytes
field type: varchar
column 1
fieldname: year
printed length: 4 characters
storage length: 2 bytes
field type: int2
column 2
fieldname: title
printed length: 24 characters
storage length: -1 bytes
field type: varchar
See Also
* pg_field_prtlen() - Returns the printed length
* pg_field_type() - Returns the type name for the corresponding field
number
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_field_table
(PHP 5 >= 5.2.0)
pg_field_table - Returns the name or oid of the tables field
Description
mixed pg_field_table ( resource $result , int $field_number [, bool
$oid_only = false ] )
pg_field_table() returns the name of the table that field belongs to, or
the table's oid if oid_only is TRUE.
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
field_number
Field number, starting from 0.
oid_only
By default the tables name that field belongs to is returned but
if oid_only is set to TRUE, then the oid will instead be returned.
Return Values
On success either the fields table name or oid. Or, FALSE on failure.
Examples
Example #1 Getting table information about a field
The above example will output something similar to:
foo
14379580
bool(false)
Notes
Note:
Returning the oid is much faster than returning the table name because
fetching the table name requires a query to the database system table.
See Also
* pg_field_name() - Returns the name of a field
* pg_field_type() - Returns the type name for the corresponding field
number
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_field_type_oid
(PHP 5 >= 5.1.0)
pg_field_type_oid - Returns the type ID (OID) for the corresponding field
number
Description
int pg_field_type_oid ( resource $result , int $field_number )
pg_field_type_oid() returns an integer containing the OID of the base type
of the given field_number in the given PostgreSQL result resource.
You can get more information about the field type by querying PostgreSQL's
pg_type system table using the OID obtained with this function. The
PostgreSQL format_type() function will convert a type OID into an SQL
standard type name.
Note:
If the field uses a PostgreSQL domain (rather than a basic type), it is
the OID of the domain's underlying type that is returned, rather than
the OID of the domain itself.
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
field_number
Field number, starting from 0.
Return Values
The OID of the field's base type. FALSE is returned on error.
Examples
Example #1 Getting information about fields
The above example will output:
Title field type OID: 1043
See Also
* pg_field_type() - Returns the type name for the corresponding field
number
* pg_field_prtlen() - Returns the printed length
* pg_field_name() - Returns the name of a field
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_field_type
(PHP 4 >= 4.2.0, PHP 5)
pg_field_type - Returns the type name for the corresponding field number
Description
string pg_field_type ( resource $result , int $field_number )
pg_field_type() returns a string containing the base type name of the
given field_number in the given PostgreSQL result resource.
Note:
If the field uses a PostgreSQL domain (rather than a basic type), it is
the name of the domain's underlying type that is returned, rather than
the name of the domain itself.
Note:
This function used to be called pg_fieldtype().
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
field_number
Field number, starting from 0.
Return Values
A string containing the base name of the field's type, or FALSE on error.
Examples
Example #1 Getting information about fields
The above example will output:
Title field type: varchar
See Also
* pg_field_prtlen() - Returns the printed length
* pg_field_name() - Returns the name of a field
* pg_field_type_oid() - Returns the type ID (OID) for the corresponding
field number
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_free_result
(PHP 4 >= 4.2.0, PHP 5)
pg_free_result - Free result memory
Description
bool pg_free_result ( resource $result )
pg_free_result() frees the memory and data associated with the specified
PostgreSQL query result resource.
This function need only be called if memory consumption during script
execution is a problem. Otherwise, all result memory will be automatically
freed when the script ends.
Note:
This function used to be called pg_freeresult().
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 pg_free_result() example
The above example will output:
First field in the second row is: 2
See Also
* pg_query() - Execute a query
* pg_query_params() - Submits a command to the server and waits for the
result, with the ability to pass parameters separately from the SQL
command text.
* pg_execute() - Sends a request to execute a prepared statement with
given parameters, and waits for the result.
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_get_notify
(PHP 4 >= 4.3.0, PHP 5)
pg_get_notify - Gets SQL NOTIFY message
Description
array pg_get_notify ( resource $connection [, int $result_type ] )
pg_get_notify() gets notifications generated by a NOTIFY SQL command. To
receive notifications, the LISTEN SQL command must be issued.
Parameters
connection
PostgreSQL database connection resource.
result_type
An optional parameter that controls how the returned array is
indexed. result_type is a constant and can take the following
values: PGSQL_ASSOC, PGSQL_NUM and PGSQL_BOTH. Using PGSQL_NUM,
pg_get_notify() will return an array with numerical indices, using
PGSQL_ASSOC it will return only associative indices while
PGSQL_BOTH, the default, will return both numerical and
associative indices.
Return Values
An array containing the NOTIFY message name and backend PID. Otherwise if
no NOTIFY is waiting, then FALSE is returned.
Examples
Example #1 PostgreSQL NOTIFY message
See Also
* pg_get_pid() - Gets the backend's process ID
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_get_pid
(PHP 4 >= 4.3.0, PHP 5)
pg_get_pid - Gets the backend's process ID
Description
int pg_get_pid ( resource $connection )
pg_get_pid() gets the backend's (database server process) PID. The PID is
useful to determine whether or not a NOTIFY message received via
pg_get_notify() is sent from another process or not.
Parameters
connection
PostgreSQL database connection resource.
Return Values
The backend database process ID.
Examples
Example #1 PostgreSQL backend PID
See Also
* pg_get_notify() - Gets SQL NOTIFY message
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_get_result
(PHP 4 >= 4.2.0, PHP 5)
pg_get_result - Get asynchronous query result
Description
resource pg_get_result ([ resource $connection ] )
pg_get_result() gets the result resource from an asynchronous query
executed by pg_send_query(), pg_send_query_params() or pg_send_execute().
pg_send_query() and the other asynchronous query functions can send
multiple queries to a PostgreSQL server and pg_get_result() is used to get
each query's results, one by one.
Parameters
connection
PostgreSQL database connection resource.
Return Values
The result resource, or FALSE if no more results are available.
Examples
Example #1 pg_get_result() example
The above example will output:
First call to pg_get_result(): Resource id #3
Resource id #3 has 3 records
Second call to pg_get_result(): Resource id #4
Resource id #4 has 1 records
See Also
* pg_send_query() - Sends asynchronous query
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_host
(PHP 4, PHP 5)
pg_host - Returns the host name associated with the connection
Description
string pg_host ([ resource $connection ] )
pg_host() returns the host name of the given PostgreSQL connection
resource is connected to.
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
Return Values
A string containing the name of the host the connection is to, or FALSE on
error.
Examples
Example #1 pg_host() example
\n";
} else {
print pg_last_error($pgsql_conn);
exit;
}
?>
See Also
* pg_connect() - Open a PostgreSQL connection
* pg_pconnect() - Open a persistent PostgreSQL connection
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_insert
(PHP 4 >= 4.3.0, PHP 5)
pg_insert - Insert array into table
Description
mixed pg_insert ( resource $connection , string $table_name , array
$assoc_array [, int $options = PGSQL_DML_EXEC ] )
pg_insert() inserts the values of assoc_array into the table specified by
table_name. If options is specified, pg_convert() is applied to
assoc_array with the specified options.
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Parameters
connection
PostgreSQL database connection resource.
table_name
Name of the table into which to insert rows. The table table_name
must at least have as many columns as assoc_array has elements.
assoc_array
An array whose keys are field names in the table table_name, and
whose values are the values of those fields that are to be
inserted.
options
Any number of PGSQL_CONV_OPTS, PGSQL_DML_NO_CONV, PGSQL_DML_EXEC,
PGSQL_DML_ASYNC or PGSQL_DML_STRING combined. If PGSQL_DML_STRING
is part of the options then query string is returned.
Return Values
Returns TRUE on success or FALSE on failure. Returns string if
PGSQL_DML_STRING is passed via options.
Examples
Example #1 pg_insert() example
See Also
* pg_convert() - Convert associative array values into suitable for SQL
statement
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_last_error
(PHP 4 >= 4.2.0, PHP 5)
pg_last_error - Get the last error message string of a connection
Description
string pg_last_error ([ resource $connection ] )
pg_last_error() returns the last error message for a given connection.
Error messages may be overwritten by internal PostgreSQL (libpq) function
calls. It may not return an appropriate error message if multiple errors
occur inside a PostgreSQL module function.
Use pg_result_error(), pg_result_error_field(), pg_result_status() and
pg_connection_status() for better error handling.
Note:
This function used to be called pg_errormessage().
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
Return Values
A string containing the last error message on the given connection, or
FALSE on error.
Examples
Example #1 pg_last_error() example
See Also
* pg_result_error() - Get error message associated with result
* pg_result_error_field() - Returns an individual field of an error
report.
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_last_notice
(PHP 4 >= 4.0.6, PHP 5)
pg_last_notice - Returns the last notice message from PostgreSQL server
Description
string pg_last_notice ( resource $connection )
pg_last_notice() returns the last notice message from the PostgreSQL
server on the specified connection. The PostgreSQL server sends notice
messages in several cases, for instance when creating a SERIAL column in a
table.
With pg_last_notice(), you can avoid issuing useless queries by checking
whether or not the notice is related to your transaction.
Notice message tracking can be set to optional by setting 1 for
pgsql.ignore_notice in php.ini.
Notice message logging can be set to optional by setting 0 for
pgsql.log_notice in php.ini. Unless pgsql.ignore_notice is set to 0,
notice message cannot be logged.
Parameters
connection
PostgreSQL database connection resource.
Return Values
A string containing the last notice on the given connection, or FALSE on
error.
Changelog
Version Description
4.3.0 This function is now fully implemented. Earlier versions ignores
database connection parameter.
4.3.0 The pgsql.ignore_notice and pgsql.log_notice php.ini directives
were added.
PHP 4.0.6 has problem with notice message handling. Use of the
4.0.6 PostgreSQL module with PHP 4.0.6 is not recommended even if you
are not using pg_last_notice().
Examples
Example #1 pg_last_notice() example
The above example will output:
CREATE TABLE will create implicit sequence "test_id_seq" for "serial" column "test.id"
See Also
* pg_query() - Execute a query
* pg_last_error() - Get the last error message string of a connection
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_last_oid
(PHP 4 >= 4.2.0, PHP 5)
pg_last_oid - Returns the last row's OID
Description
string pg_last_oid ( resource $result )
pg_last_oid() is used to retrieve the OID assigned to an inserted row.
OID field became an optional field from PostgreSQL 7.2 and will not be
present by default in PostgreSQL 8.1. When the OID field is not present in
a table, the programmer must use pg_result_status() to check for
successful insertion.
To get the value of a SERIAL field in an inserted row, it is necessary to
use the PostgreSQL CURRVAL function, naming the sequence whose last value
is required. If the name of the sequence is unknown, the
pg_get_serial_sequence PostgreSQL 8.0 function is necessary.
PostgreSQL 8.1 has a function LASTVAL that returns the value of the most
recently used sequence in the session. This avoids the need for naming the
sequence, table or column altogether.
Note:
This function used to be called pg_getlastoid().
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
Return Values
A string containing the OID assigned to the most recently inserted row in
the specified connection, or FALSE on error or no available OID.
Examples
Example #1 pg_last_oid() example
See Also
* pg_query() - Execute a query
* pg_result_status() - Get status of query result
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_lo_close
(PHP 4 >= 4.2.0, PHP 5)
pg_lo_close - Close a large object
Description
bool pg_lo_close ( resource $large_object )
pg_lo_close() closes a large object. large_object is a resource for the
large object from pg_lo_open().
To use the large object interface, it is necessary to enclose it within a
transaction block.
Note:
This function used to be called pg_loclose().
Parameters
result
PostgreSQL large object (LOB) resource, returned by pg_lo_open().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 pg_lo_close() example
See Also
* pg_lo_open() - Open a large object
* pg_lo_create() - Create a large object
* pg_lo_import() - Import a large object from file
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_lo_create
(PHP 4 >= 4.2.0, PHP 5)
pg_lo_create - Create a large object
Description
int pg_lo_create ([ resource $connection [, mixed $object_id ]] )
int pg_lo_create ( mixed $object_id )
pg_lo_create() creates a large object and returns the OID of the large
object. PostgreSQL access modes INV_READ, INV_WRITE, and INV_ARCHIVE are
not supported, the object is created always with both read and write
access. INV_ARCHIVE has been removed from PostgreSQL itself (version 6.3
and above).
To use the large object interface, it is necessary to enclose it within a
transaction block.
Instead of using the large object interface (which has no access controls
and is cumbersome to use), try PostgreSQL's bytea column type and
pg_escape_bytea().
Note:
This function used to be called pg_locreate().
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
object_id
If an object_id is given the function will try to create a large
object with this id, else a free object id is assigned by the
server. The parameter was added in PHP 5.3 and relies on
functionality that first appeared in PostgreSQL 8.1.
Return Values
A large object OID or FALSE on error.
Changelog
Version Description
5.3.0 The optional object_id was added.
Examples
Example #1 pg_lo_create() example
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_lo_export
(PHP 4 >= 4.2.0, PHP 5)
pg_lo_export - Export a large object to file
Description
bool pg_lo_export ([ resource $connection ], int $oid , string $pathname )
pg_lo_export() takes a large object in a PostgreSQL database and saves its
contents to a file on the local filesystem.
To use the large object interface, it is necessary to enclose it within a
transaction block.
Note:
This function used to be called pg_loexport().
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
oid
The OID of the large object in the database.
pathname
The full path and file name of the file in which to write the
large object on the client filesystem.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 pg_lo_export() example
See Also
* pg_lo_import() - Import a large object from file
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_lo_import
(PHP 4 >= 4.2.0, PHP 5)
pg_lo_import - Import a large object from file
Description
int pg_lo_import ([ resource $connection ], string $pathname [, mixed
$object_id ] )
pg_lo_import() creates a new large object in the database using a file on
the filesystem as its data source.
To use the large object interface, it is necessary to enclose it within a
transaction block.
Note: When safe mode is enabled, PHP checks whether the files or
directories being operated upon have the same UID (owner) as the script
that is being executed.
Note:
This function used to be called pg_loimport().
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
pathname
The full path and file name of the file on the client filesystem
from which to read the large object data.
object_id
If an object_id is given the function will try to create a large
object with this id, else a free object id is assigned by the
server. The parameter was added in PHP 5.3 and relies on
functionality that first appeared in PostgreSQL 8.1.
Return Values
The OID of the newly created large object, or FALSE on failure.
Changelog
Version Description
5.3.0 The optional object_id was added.
4.2.0 The syntax of this function changed. It used to be:
int pg_lo_import ( string $pathname [, resource $connection ] )
Examples
Example #1 pg_lo_import() example
See Also
* pg_lo_export() - Export a large object to file
* pg_lo_open() - Open a large object
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_lo_open
(PHP 4 >= 4.2.0, PHP 5)
pg_lo_open - Open a large object
Description
resource pg_lo_open ( resource $connection , int $oid , string $mode )
pg_lo_open() opens a large object in the database and returns large object
resource so that it can be manipulated.
Warning
Do not close the database connection before closing the large object
resource.
To use the large object interface, it is necessary to enclose it within a
transaction block.
Note:
This function used to be called pg_loopen().
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
oid
The OID of the large object in the database.
mode
Can be either "r" for read-only, "w" for write only or "rw" for
read and write.
Return Values
A large object resource or FALSE on error.
Examples
Example #1 pg_lo_open() example
See Also
* pg_lo_close() - Close a large object
* pg_lo_create() - Create a large object
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_lo_read_all
(PHP 4 >= 4.2.0, PHP 5)
pg_lo_read_all - Reads an entire large object and send straight to browser
Description
int pg_lo_read_all ( resource $large_object )
pg_lo_read_all() reads a large object and passes it straight through to
the browser after sending all pending headers. Mainly intended for sending
binary data like images or sound.
To use the large object interface, it is necessary to enclose it within a
transaction block.
Note:
This function used to be called pg_loreadall().
Parameters
large_object
PostgreSQL large object (LOB) resource, returned by pg_lo_open().
Return Values
Number of bytes read or FALSE on error.
Examples
Example #1 pg_lo_read_all() example
See Also
* pg_lo_read() - Read a large object
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_lo_read
(PHP 4 >= 4.2.0, PHP 5)
pg_lo_read - Read a large object
Description
string pg_lo_read ( resource $large_object [, int $len = 8192 ] )
pg_lo_read() reads at most len bytes from a large object and returns it as
a string.
To use the large object interface, it is necessary to enclose it within a
transaction block.
Note:
This function used to be called pg_loread().
Parameters
large_object
PostgreSQL large object (LOB) resource, returned by pg_lo_open().
len
An optional maximum number of bytes to return.
Return Values
A string containing len bytes from the large object, or FALSE on error.
Examples
Example #1 pg_lo_read() example
See Also
* pg_lo_read_all() - Reads an entire large object and send straight to
browser
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_lo_seek
(PHP 4 >= 4.2.0, PHP 5)
pg_lo_seek - Seeks position within a large object
Description
bool pg_lo_seek ( resource $large_object , int $offset [, int $whence =
PGSQL_SEEK_CUR ] )
pg_lo_seek() seeks a position within a large object resource.
To use the large object interface, it is necessary to enclose it within a
transaction block.
Parameters
large_object
PostgreSQL large object (LOB) resource, returned by pg_lo_open().
offset
The number of bytes to seek.
whence
One of the constants PGSQL_SEEK_SET (seek from object start),
PGSQL_SEEK_CUR (seek from current position) or PGSQL_SEEK_END
(seek from object end) .
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 pg_lo_seek() example
See Also
* pg_lo_tell() - Returns current seek position a of large object
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_lo_tell
(PHP 4 >= 4.2.0, PHP 5)
pg_lo_tell - Returns current seek position a of large object
Description
int pg_lo_tell ( resource $large_object )
pg_lo_tell() returns the current position (offset from the beginning) of a
large object.
To use the large object interface, it is necessary to enclose it within a
transaction block.
Parameters
large_object
PostgreSQL large object (LOB) resource, returned by pg_lo_open().
Return Values
The current seek offset (in number of bytes) from the beginning of the
large object. If there is an error, the return value is negative.
Examples
Example #1 pg_lo_tell() example
The above example will output:
Seek position is: 50000
See Also
* pg_lo_seek() - Seeks position within a large object
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_lo_unlink
(PHP 4 >= 4.2.0, PHP 5)
pg_lo_unlink - Delete a large object
Description
bool pg_lo_unlink ( resource $connection , int $oid )
pg_lo_unlink() deletes a large object with the oid. Returns TRUE on
success or FALSE on failure.
To use the large object interface, it is necessary to enclose it within a
transaction block.
Note:
This function used to be called pg_lounlink().
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
oid
The OID of the large object in the database.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 pg_lo_unlink() example
See Also
* pg_lo_create() - Create a large object
* pg_lo_import() - Import a large object from file
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_lo_write
(PHP 4 >= 4.2.0, PHP 5)
pg_lo_write - Write to a large object
Description
int pg_lo_write ( resource $large_object , string $data [, int $len ] )
pg_lo_write() writes data into a large object at the current seek
position.
To use the large object interface, it is necessary to enclose it within a
transaction block.
Note:
This function used to be called pg_lowrite().
Parameters
large_object
PostgreSQL large object (LOB) resource, returned by pg_lo_open().
data
The data to be written to the large object. If len is specified
and is less than the length of data, only len bytes will be
written.
len
An optional maximum number of bytes to write. Must be greater than
zero and no greater than the length of data. Defaults to the
length of data.
Return Values
The number of bytes written to the large object, or FALSE on error.
Examples
Example #1 pg_lo_write() example
See Also
* pg_lo_create() - Create a large object
* pg_lo_open() - Open a large object
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_meta_data
(PHP 4 >= 4.3.0, PHP 5)
pg_meta_data - Get meta data for table
Description
array pg_meta_data ( resource $connection , string $table_name )
pg_meta_data() returns table definition for table_name as an array.
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Parameters
connection
PostgreSQL database connection resource.
table_name
The name of the table.
Return Values
An array of the table definition, or FALSE on error.
Examples
Example #1 Getting table metadata
';
var_dump($meta);
echo '';
}
?>
The above example will output:
array(3) {
["author"]=>
array(5) {
["num"]=>
int(1)
["type"]=>
string(7) "varchar"
["len"]=>
int(-1)
["not null"]=>
bool(false)
["has default"]=>
bool(false)
}
["year"]=>
array(5) {
["num"]=>
int(2)
["type"]=>
string(4) "int2"
["len"]=>
int(2)
["not null"]=>
bool(false)
["has default"]=>
bool(false)
}
["title"]=>
array(5) {
["num"]=>
int(3)
["type"]=>
string(7) "varchar"
["len"]=>
int(-1)
["not null"]=>
bool(false)
["has default"]=>
bool(false)
}
}
See Also
* pg_convert() - Convert associative array values into suitable for SQL
statement
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_num_fields
(PHP 4 >= 4.2.0, PHP 5)
pg_num_fields - Returns the number of fields in a result
Description
int pg_num_fields ( resource $result )
pg_num_fields() returns the number of fields (columns) in a PostgreSQL
result resource.
Note:
This function used to be called pg_numfields().
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
Return Values
The number of fields (columns) in the result. On error, -1 is returned.
Examples
Example #1 pg_num_fields() example
The above example will output:
2 field(s) returned.
See Also
* pg_num_rows() - Returns the number of rows in a result
* pg_affected_rows() - Returns number of affected records (tuples)
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_num_rows
(PHP 4 >= 4.2.0, PHP 5)
pg_num_rows - Returns the number of rows in a result
Description
int pg_num_rows ( resource $result )
pg_num_rows() will return the number of rows in a PostgreSQL result
resource.
Note:
This function used to be called pg_numrows().
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
Return Values
The number of rows in the result. On error, -1 is returned.
Examples
Example #1 pg_num_rows() example
The above example will output:
1 row(s) returned.
See Also
* pg_num_fields() - Returns the number of fields in a result
* pg_affected_rows() - Returns number of affected records (tuples)
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_options
(PHP 4, PHP 5)
pg_options - Get the options associated with the connection
Description
string pg_options ([ resource $connection ] )
pg_options() will return a string containing the options specified on the
given PostgreSQL connection resource.
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
Return Values
A string containing the connection options, or FALSE on error.
Examples
Example #1 pg_options() example
See Also
* pg_connect() - Open a PostgreSQL connection
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_parameter_status
(PHP 5)
pg_parameter_status - Looks up a current parameter setting of the server.
Description
string pg_parameter_status ([ resource $connection ], string $param_name )
Looks up a current parameter setting of the server.
Certain parameter values are reported by the server automatically at
connection startup or whenever their values change. pg_parameter_status()
can be used to interrogate these settings. It returns the current value of
a parameter if known, or FALSE if the parameter is not known.
Parameters reported as of PostgreSQL 8.0 include server_version,
server_encoding, client_encoding, is_superuser, session_authorization,
DateStyle, TimeZone, and integer_datetimes. (server_encoding, TimeZone,
and integer_datetimes were not reported by releases before 8.0.) Note that
server_version, server_encoding and integer_datetimes cannot change after
PostgreSQL startup.
PostgreSQL 7.3 or lower servers do not report parameter settings,
pg_parameter_status() includes logic to obtain values for server_version
and client_encoding anyway. Applications are encouraged to use
pg_parameter_status() rather than ad hoc code to determine these values.
Caution
On a pre-7.4 PostgreSQL server, changing client_encoding via SET after
connection startup will not be reflected by pg_parameter_status().
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
param_name
Possible param_name values include server_version,
server_encoding, client_encoding, is_superuser,
session_authorization, DateStyle, TimeZone, and integer_datetimes.
Return Values
A string containing the value of the parameter, FALSE on failure or
invalid param_name.
Examples
Example #1 pg_parameter_status() example
The above example will output:
Server encoding: SQL_ASCII
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_pconnect
(PHP 4, PHP 5)
pg_pconnect - Open a persistent PostgreSQL connection
Description
resource pg_pconnect ( string $connection_string [, int $connect_type ] )
pg_pconnect() opens a connection to a PostgreSQL database. It returns a
connection resource that is needed by other PostgreSQL functions.
If a second call is made to pg_pconnect() with the same connection_string
as an existing connection, the existing connection will be returned unless
you pass PGSQL_CONNECT_FORCE_NEW as connect_type.
To enable persistent connection, the pgsql.allow_persistent php.ini
directive must be set to "On" (which is the default). The maximum number
of persistent connection can be defined with the pgsql.max_persistent
php.ini directive (defaults to -1 for no limit). The total number of
connections can be set with the pgsql.max_links php.ini directive.
pg_close() will not close persistent links generated by pg_pconnect().
Parameters
connection_string
The connection_string can be empty to use all default parameters,
or it can contain one or more parameter settings separated by
whitespace. Each parameter setting is in the form keyword = value.
Spaces around the equal sign are optional. To write an empty value
or a value containing spaces, surround it with single quotes,
e.g., keyword = 'a value'. Single quotes and backslashes within
the value must be escaped with a backslash, i.e., \' and \\.
The currently recognized parameter keywords are: host, hostaddr,
port, dbname, user, password, connect_timeout, options, tty
(ignored), sslmode, requiressl (deprecated in favor of sslmode),
and service. Which of these arguments exist depends on your
PostgreSQL version.
connect_type
If PGSQL_CONNECT_FORCE_NEW is passed, then a new connection is
created, even if the connection_string is identical to an existing
connection.
Return Values
PostgreSQL connection resource on success, FALSE on failure.
Examples
Example #1 Using pg_pconnect()
See Also
* pg_connect() - Open a PostgreSQL connection
* Persistent Database Connections
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_ping
(PHP 4 >= 4.3.0, PHP 5)
pg_ping - Ping database connection
Description
bool pg_ping ([ resource $connection ] )
pg_ping() pings a database connection and tries to reconnect it if it is
broken.
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 pg_ping() example
See Also
* pg_connection_status() - Get connection status
* pg_connection_reset() - Reset connection (reconnect)
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_port
(PHP 4, PHP 5)
pg_port - Return the port number associated with the connection
Description
int pg_port ([ resource $connection ] )
pg_port() returns the port number that the given PostgreSQL connection
resource is connected to.
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
Return Values
An int containing the port number of the database server the connection is
to, or FALSE on error.
Examples
Example #1 pg_port() example
\n";
} else {
print pg_last_error($pgsql_conn);
exit;
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_prepare
(PHP 5 >= 5.1.0)
pg_prepare - Submits a request to create a prepared statement with the
given parameters, and waits for completion.
Description
resource pg_prepare ([ resource $connection ], string $stmtname , string
$query )
pg_prepare() creates a prepared statement for later execution with
pg_execute() or pg_send_execute(). This feature allows commands that will
be used repeatedly to be parsed and planned just once, rather than each
time they are executed. pg_prepare() is supported only against PostgreSQL
7.4 or higher connections; it will fail when using earlier versions.
The function creates a prepared statement named stmtname from the query
string, which must contain a single SQL command. stmtname may be "" to
create an unnamed statement, in which case any pre-existing unnamed
statement is automatically replaced; otherwise it is an error if the
statement name is already defined in the current session. If any
parameters are used, they are referred to in the query as $1, $2, etc.
Prepared statements for use with pg_prepare() can also be created by
executing SQL PREPARE statements. (But pg_prepare() is more flexible since
it does not require parameter types to be pre-specified.) Also, although
there is no PHP function for deleting a prepared statement, the SQL
DEALLOCATE statement can be used for that purpose.
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
stmtname
The name to give the prepared statement. Must be unique
per-connection. If "" is specified, then an unnamed statement is
created, overwriting any previously defined unnamed statement.
query
The parameterized SQL statement. Must contain only a single
statement. (multiple statements separated by semi-colons are not
allowed.) If any parameters are used, they are referred to as $1,
$2, etc.
Return Values
A query result resource on success or FALSE on failure.
Examples
Example #1 Using pg_prepare()
See Also
* pg_execute() - Sends a request to execute a prepared statement with
given parameters, and waits for the result.
* pg_send_execute() - Sends a request to execute a prepared statement
with given parameters, without waiting for the result(s).
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_put_line
(PHP 4 >= 4.0.3, PHP 5)
pg_put_line - Send a NULL-terminated string to PostgreSQL backend
Description
bool pg_put_line ([ resource $connection ], string $data )
pg_put_line() sends a NULL-terminated string to the PostgreSQL backend
server. This is needed in conjunction with PostgreSQL's COPY FROM command.
COPY is a high-speed data loading interface supported by PostgreSQL. Data
is passed in without being parsed, and in a single transaction.
An alternative to using raw pg_put_line() commands is to use
pg_copy_from(). This is a far simpler interface.
Note:
The application must explicitly send the two characters "\." on the last
line to indicate to the backend that it has finished sending its data,
before issuing pg_end_copy().
Warning
Use of the pg_put_line() causes most large object operations, including
pg_lo_read() and pg_lo_tell(), to subsequently fail. You can use
pg_copy_from() and pg_copy_to() instead.
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
data
A line of text to be sent directly to the PostgreSQL backend. A
NULL terminator is added automatically.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 pg_put_line() example
See Also
* pg_end_copy() - Sync with PostgreSQL backend
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_query_params
(PHP 5 >= 5.1.0)
pg_query_params - Submits a command to the server and waits for the
result, with the ability to pass parameters separately from the SQL
command text.
Description
resource pg_query_params ([ resource $connection ], string $query , array
$params )
Submits a command to the server and waits for the result, with the ability
to pass parameters separately from the SQL command text.
pg_query_params() is like pg_query(), but offers additional functionality:
parameter values can be specified separately from the command string
proper. pg_query_params() is supported only against PostgreSQL 7.4 or
higher connections; it will fail when using earlier versions.
If parameters are used, they are referred to in the query string as $1,
$2, etc. params specifies the actual values of the parameters. A NULL
value in this array means the corresponding parameter is SQL NULL.
The primary advantage of pg_query_params() over pg_query() is that
parameter values may be separated from the query string, thus avoiding the
need for tedious and error-prone quoting and escaping. Unlike pg_query(),
pg_query_params() allows at most one SQL command in the given string.
(There can be semicolons in it, but not more than one nonempty command.)
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
query
The parameterized SQL statement. Must contain only a single
statement. (multiple statements separated by semi-colons are not
allowed.) If any parameters are used, they are referred to as $1,
$2, etc.
params
An array of parameter values to substitute for the $1, $2, etc.
placeholders in the original prepared query string. The number of
elements in the array must match the number of placeholders.
Return Values
A query result resource on success or FALSE on failure.
Examples
Example #1 Using pg_query_params()
See Also
* pg_query() - Execute a query
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_query
(PHP 4 >= 4.2.0, PHP 5)
pg_query - Execute a query
Description
resource pg_query ([ resource $connection ], string $query )
pg_query() executes the query on the specified database connection.
If an error occurs, and FALSE is returned, details of the error can be
retrieved using the pg_last_error() function if the connection is valid.
Note: Although connection can be omitted, it is not recommended, since
it can be the cause of hard to find bugs in scripts.
Note:
This function used to be called pg_exec(). pg_exec() is still available
for compatibility reasons, but users are encouraged to use the newer
name.
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
query
The SQL statement or statements to be executed. When multiple
statements are passed to the function, they are automatically
executed as one transaction, unless there are explicit
BEGIN/COMMIT commands included in the query string. However, using
multiple transactions in one function call is not recommended.
Data inside the query should be properly escaped.
Return Values
A query result resource on success or FALSE on failure.
Examples
Example #1 pg_query() example
\n";
}
?>
Example #2 Using pg_query() with multiple statements
See Also
* pg_connect() - Open a PostgreSQL connection
* pg_pconnect() - Open a persistent PostgreSQL connection
* pg_fetch_array() - Fetch a row as an array
* pg_fetch_object() - Fetch a row as an object
* pg_num_rows() - Returns the number of rows in a result
* pg_affected_rows() - Returns number of affected records (tuples)
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_result_error_field
(PHP 5 >= 5.1.0)
pg_result_error_field - Returns an individual field of an error report.
Description
string pg_result_error_field ( resource $result , int $fieldcode )
pg_result_error_field() returns one of the detailed error message fields
associated with result resource. It is only available against a PostgreSQL
7.4 or above server. The error field is specified by the fieldcode.
Because pg_query() and pg_query_params() return FALSE if the query fails,
you must use pg_send_query() and pg_get_result() to get the result handle.
If you need to get additional error information from failed pg_query()
queries, use pg_set_error_verbosity() and pg_last_error() and then parse
the result.
Parameters
result
A PostgreSQL query result resource from a previously executed
statement.
fieldcode
Possible fieldcode values are: PGSQL_DIAG_SEVERITY,
PGSQL_DIAG_SQLSTATE, PGSQL_DIAG_MESSAGE_PRIMARY,
PGSQL_DIAG_MESSAGE_DETAIL, PGSQL_DIAG_MESSAGE_HINT,
PGSQL_DIAG_STATEMENT_POSITION, PGSQL_DIAG_INTERNAL_POSITION
(PostgreSQL 8.0+ only), PGSQL_DIAG_INTERNAL_QUERY (PostgreSQL 8.0+
only), PGSQL_DIAG_CONTEXT, PGSQL_DIAG_SOURCE_FILE,
PGSQL_DIAG_SOURCE_LINE or PGSQL_DIAG_SOURCE_FUNCTION.
Return Values
A string containing the contents of the error field, NULL if the field
does not exist or FALSE on failure.
Examples
Example #1 pg_result_error_field() example
See Also
* pg_result_error() - Get error message associated with result
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_result_error
(PHP 4 >= 4.2.0, PHP 5)
pg_result_error - Get error message associated with result
Description
string pg_result_error ( resource $result )
pg_result_error() returns any error message associated with the result
resource. Therefore, the user has a better chance of getting the correct
error message than with pg_last_error().
The function pg_result_error_field() can give much greater detail on
result errors than pg_result_error().
Because pg_query() returns FALSE if the query fails, you must use
pg_send_query() and pg_get_result() to get the result handle.
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
Return Values
Returns a string if there is an error associated with the result
parameter, FALSE otherwise.
Examples
Example #1 pg_result_error() example
See Also
* pg_result_error_field() - Returns an individual field of an error
report.
* pg_query() - Execute a query
* pg_send_query() - Sends asynchronous query
* pg_get_result() - Get asynchronous query result
* pg_last_error() - Get the last error message string of a connection
* pg_last_notice() - Returns the last notice message from PostgreSQL
server
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_result_seek
(PHP 4 >= 4.3.0, PHP 5)
pg_result_seek - Set internal row offset in result resource
Description
bool pg_result_seek ( resource $result , int $offset )
pg_result_seek() sets the internal row offset in a result resource.
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
offset
Row to move the internal offset to in the result resource. Rows
are numbered starting from zero.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 pg_result_seek() example
See Also
* pg_fetch_row() - Get a row as an enumerated array
* pg_fetch_assoc() - Fetch a row as an associative array
* pg_fetch_array() - Fetch a row as an array
* pg_fetch_object() - Fetch a row as an object
* pg_fetch_result() - Returns values from a result resource
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_result_status
(PHP 4 >= 4.2.0, PHP 5)
pg_result_status - Get status of query result
Description
mixed pg_result_status ( resource $result [, int $type = PGSQL_STATUS_LONG
] )
pg_result_status() returns the status of a result resource, or the
PostgreSQL command completion tag associated with the result
Parameters
result
PostgreSQL query result resource, returned by pg_query(),
pg_query_params() or pg_execute() (among others).
type
Either PGSQL_STATUS_LONG to return the numeric status of the
result, or PGSQL_STATUS_STRING to return the command tag of the
result. If not specified, PGSQL_STATUS_LONG is the default.
Return Values
Possible return values are PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK,
PGSQL_TUPLES_OK, PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR if PGSQL_STATUS_LONG is
specified. Otherwise, a string containing the PostgreSQL command tag is
returned.
Changelog
Version Description
4.3.0 The type parameter was added.
Examples
Example #1 pg_result_status() example
The above example will output:
Copy began.
See Also
* pg_connection_status() - Get connection status
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_select
(PHP 4 >= 4.3.0, PHP 5)
pg_select - Select records
Description
mixed pg_select ( resource $connection , string $table_name , array
$assoc_array [, int $options = PGSQL_DML_EXEC ] )
pg_select() selects records specified by assoc_array which has
field=>value. For a successful query, it returns an array containing all
records and fields that match the condition specified by assoc_array.
If options is specified, pg_convert() is applied to assoc_array with the
specified flags.
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Parameters
connection
PostgreSQL database connection resource.
table_name
Name of the table from which to select rows.
assoc_array
An array whose keys are field names in the table table_name, and
whose values are the conditions that a row must meet to be
retrieved.
options
Any number of PGSQL_CONV_FORCE_NULL, PGSQL_DML_NO_CONV,
PGSQL_DML_EXEC, PGSQL_DML_ASYNC or PGSQL_DML_STRING combined. If
PGSQL_DML_STRING is part of the options then query string is
returned.
Return Values
Returns TRUE on success or FALSE on failure. Returns string if
PGSQL_DML_STRING is passed via options.
Examples
Example #1 pg_select() example
See Also
* pg_convert() - Convert associative array values into suitable for SQL
statement
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_send_execute
(PHP 5 >= 5.1.0)
pg_send_execute - Sends a request to execute a prepared statement with
given parameters, without waiting for the result(s).
Description
bool pg_send_execute ( resource $connection , string $stmtname , array
$params )
Sends a request to execute a prepared statement with given parameters,
without waiting for the result(s).
This is similar to pg_send_query_params(), but the command to be executed
is specified by naming a previously-prepared statement, instead of giving
a query string. The function's parameters are handled identically to
pg_execute(). Like pg_execute(), it will not work on pre-7.4 versions of
PostgreSQL.
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
stmtname
The name of the prepared statement to execute. if "" is specified,
then the unnamed statement is executed. The name must have been
previously prepared using pg_prepare(), pg_send_prepare() or a
PREPARE SQL command.
params
An array of parameter values to substitute for the $1, $2, etc.
placeholders in the original prepared query string. The number of
elements in the array must match the number of placeholders.
Return Values
Returns TRUE on success, FALSE on failure. Use pg_get_result() to
determine the query result.
Examples
Example #1 Using pg_send_execute()
See Also
* pg_prepare() - Submits a request to create a prepared statement with
the given parameters, and waits for completion.
* pg_send_prepare() - Sends a request to create a prepared statement
with the given parameters, without waiting for completion.
* pg_execute() - Sends a request to execute a prepared statement with
given parameters, and waits for the result.
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_send_prepare
(PHP 5 >= 5.1.0)
pg_send_prepare - Sends a request to create a prepared statement with the
given parameters, without waiting for completion.
Description
bool pg_send_prepare ( resource $connection , string $stmtname , string
$query )
Sends a request to create a prepared statement with the given parameters,
without waiting for completion.
This is an asynchronous version of pg_prepare(): it returns TRUE if it was
able to dispatch the request, and FALSE if not. After a successful call,
call pg_get_result() to determine whether the server successfully created
the prepared statement. The function's parameters are handled identically
to pg_prepare(). Like pg_prepare(), it will not work on pre-7.4 versions
of PostgreSQL.
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
stmtname
The name to give the prepared statement. Must be unique
per-connection. If "" is specified, then an unnamed statement is
created, overwriting any previously defined unnamed statement.
query
The parameterized SQL statement. Must contain only a single
statement. (multiple statements separated by semi-colons are not
allowed.) If any parameters are used, they are referred to as $1,
$2, etc.
Return Values
Returns TRUE on success, FALSE on failure. Use pg_get_result() to
determine the query result.
Examples
Example #1 Using pg_send_prepare()
See Also
* pg_connect() - Open a PostgreSQL connection
* pg_pconnect() - Open a persistent PostgreSQL connection
* pg_execute() - Sends a request to execute a prepared statement with
given parameters, and waits for the result.
* pg_send_execute() - Sends a request to execute a prepared statement
with given parameters, without waiting for the result(s).
* pg_send_query_params() - Submits a command and separate parameters to
the server without waiting for the result(s).
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_send_query_params
(PHP 5 >= 5.1.0)
pg_send_query_params - Submits a command and separate parameters to the
server without waiting for the result(s).
Description
bool pg_send_query_params ( resource $connection , string $query , array
$params )
Submits a command and separate parameters to the server without waiting
for the result(s).
This is equivalent to pg_send_query() except that query parameters can be
specified separately from the query string. The function's parameters are
handled identically to pg_query_params(). Like pg_query_params(), it will
not work on pre-7.4 PostgreSQL connections, and it allows only one command
in the query string.
Parameters
connection
PostgreSQL database connection resource.
query
The parameterized SQL statement. Must contain only a single
statement. (multiple statements separated by semi-colons are not
allowed.) If any parameters are used, they are referred to as $1,
$2, etc.
params
An array of parameter values to substitute for the $1, $2, etc.
placeholders in the original prepared query string. The number of
elements in the array must match the number of placeholders.
Return Values
Returns TRUE on success or FALSE on failure.
Use pg_get_result() to determine the query result.
Examples
Example #1 Using pg_send_query_params()
See Also
* pg_send_query() - Sends asynchronous query
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_send_query
(PHP 4 >= 4.2.0, PHP 5)
pg_send_query - Sends asynchronous query
Description
bool pg_send_query ( resource $connection , string $query )
pg_send_query() sends a query or queries asynchronously to the connection.
Unlike pg_query(), it can send multiple queries at once to PostgreSQL and
get the results one by one using pg_get_result().
Script execution is not blocked while the queries are executing. Use
pg_connection_busy() to check if the connection is busy (i.e. the query is
executing). Queries may be cancelled using pg_cancel_query().
Although the user can send multiple queries at once, multiple queries
cannot be sent over a busy connection. If a query is sent while the
connection is busy, it waits until the last query is finished and discards
all its results.
Parameters
connection
PostgreSQL database connection resource.
query
The SQL statement or statements to be executed.
Data inside the query should be properly escaped.
Return Values
Returns TRUE on success or FALSE on failure.
Use pg_get_result() to determine the query result.
Examples
Example #1 pg_send_query() example
The above example will output:
First call to pg_get_result(): Resource id #3
Resource id #3 has 3 records
Second call to pg_get_result(): Resource id #4
Resource id #4 has 1 records
See Also
* pg_query() - Execute a query
* pg_cancel_query() - Cancel an asynchronous query
* pg_get_result() - Get asynchronous query result
* pg_connection_busy() - Get connection is busy or not
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_set_client_encoding
(PHP 4 >= 4.0.3, PHP 5)
pg_set_client_encoding - Set the client encoding
Description
int pg_set_client_encoding ([ resource $connection ], string $encoding )
pg_set_client_encoding() sets the client encoding and returns 0 if success
or -1 if error.
PostgreSQL will automatically convert data in the backend database
encoding into the frontend encoding.
Note:
The function used to be called pg_setclientencoding().
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
encoding
The required client encoding. One of SQL_ASCII, EUC_JP, EUC_CN,
EUC_KR, EUC_TW, UNICODE, MULE_INTERNAL, LATINX (X=1...9), KOI8,
WIN, ALT, SJIS, BIG5 or WIN1250.
The exact list of available encodings depends on your PostgreSQL
version, so check your PostgreSQL manual for a more specific list.
Return Values
Returns 0 on success or -1 on error.
Examples
Example #1 pg_set_client_encoding() example
\n";
}
?>
See Also
* pg_client_encoding() - Gets the client encoding
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_set_error_verbosity
(PHP 5 >= 5.1.0)
pg_set_error_verbosity - Determines the verbosity of messages returned by
pg_last_error() and pg_result_error().
Description
int pg_set_error_verbosity ([ resource $connection ], int $verbosity )
Determines the verbosity of messages returned by pg_last_error() and
pg_result_error().
pg_set_error_verbosity() sets the verbosity mode, returning the
connection's previous setting. In PGSQL_ERRORS_TERSE mode, returned
messages include severity, primary text, and position only; this will
normally fit on a single line. The default mode (PGSQL_ERRORS_DEFAULT)
produces messages that include the above plus any detail, hint, or context
fields (these may span multiple lines). The PGSQL_ERRORS_VERBOSE mode
includes all available fields. Changing the verbosity does not affect the
messages available from already-existing result objects, only
subsequently-created ones.
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
verbosity
The required verbosity: PGSQL_ERRORS_TERSE, PGSQL_ERRORS_DEFAULT
or PGSQL_ERRORS_VERBOSE.
Return Values
The previous verbosity level: PGSQL_ERRORS_TERSE, PGSQL_ERRORS_DEFAULT or
PGSQL_ERRORS_VERBOSE.
Examples
Example #1 pg_set_error_verbosity() example
See Also
* pg_last_error() - Get the last error message string of a connection
* pg_result_error() - Get error message associated with result
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_trace
(PHP 4 >= 4.0.1, PHP 5)
pg_trace - Enable tracing a PostgreSQL connection
Description
bool pg_trace ( string $pathname [, string $mode = "w" [, resource
$connection ]] )
pg_trace() enables tracing of the PostgreSQL frontend/backend
communication to a file. To fully understand the results, one needs to be
familiar with the internals of PostgreSQL communication protocol.
For those who are not, it can still be useful for tracing errors in
queries sent to the server, you could do for example grep '^To backend'
trace.log and see what queries actually were sent to the PostgreSQL
server. For more information, refer to the >> PostgreSQL Documentation.
Parameters
pathname
The full path and file name of the file in which to write the
trace log. Same as in fopen().
pathname
An optional file access mode, same as for fopen().
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 pg_trace() example
See Also
* fopen() - Opens file or URL
* pg_untrace() - Disable tracing of a PostgreSQL connection
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_transaction_status
(PHP 5 >= 5.1.0)
pg_transaction_status - Returns the current in-transaction status of the
server.
Description
int pg_transaction_status ( resource $connection )
Returns the current in-transaction status of the server.
Caution
pg_transaction_status() will give incorrect results when using a
PostgreSQL 7.3 server that has the parameter autocommit set to off. The
server-side autocommit feature has been deprecated and does not exist in
later server versions.
Parameters
connection
PostgreSQL database connection resource.
Return Values
The status can be PGSQL_TRANSACTION_IDLE (currently idle),
PGSQL_TRANSACTION_ACTIVE (a command is in progress),
PGSQL_TRANSACTION_INTRANS (idle, in a valid transaction block), or
PGSQL_TRANSACTION_INERROR (idle, in a failed transaction block).
PGSQL_TRANSACTION_UNKNOWN is reported if the connection is bad.
PGSQL_TRANSACTION_ACTIVE is reported only when a query has been sent to
the server and not yet completed.
Examples
Example #1 pg_transaction_status() example
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_tty
(PHP 4, PHP 5)
pg_tty - Return the TTY name associated with the connection
Description
string pg_tty ([ resource $connection ] )
pg_tty() returns the TTY name that server side debugging output is sent to
on the given PostgreSQL connection resource.
Note:
pg_tty() is obsolete, since the server no longer pays attention to the
TTY setting, but the function remains for backwards compatibility.
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
Return Values
A string containing the debug TTY of the connection, or FALSE on error.
Examples
Example #1 pg_tty() example
\n";
} else {
print pg_last_error($pgsql_conn);
exit;
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_unescape_bytea
(PHP 4 >= 4.3.0, PHP 5)
pg_unescape_bytea - Unescape binary for bytea type
Description
string pg_unescape_bytea ( string $data )
pg_unescape_bytea() unescapes PostgreSQL bytea data values. It returns the
unescaped string, possibly containing binary data.
Note:
When you SELECT a bytea type, PostgreSQL returns octal byte values
prefixed with '\' (e.g. \032). Users are supposed to convert back to
binary format manually.
This function requires PostgreSQL 7.2 or later. With PostgreSQL 7.2.0
and 7.2.1, bytea values must be cast when you enable multi-byte support.
i.e. INSERT INTO test_table (image) VALUES ('$image_escaped'::bytea);
PostgreSQL 7.2.2 or later does not need a cast. The exception is when
the client and backend character encoding does not match, and there may
be multi-byte stream error. User must then cast to bytea to avoid this
error.
Parameters
data
A string containing PostgreSQL bytea data to be converted into a
PHP binary string.
Return Values
A string containing the unescaped data.
Examples
Example #1 pg_unescape_bytea() example
See Also
* pg_escape_bytea() - Escape a string for insertion into a bytea field
* pg_escape_string() - Escape a string for insertion into a text field
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_untrace
(PHP 4 >= 4.0.1, PHP 5)
pg_untrace - Disable tracing of a PostgreSQL connection
Description
bool pg_untrace ([ resource $connection ] )
Stop tracing started by pg_trace().
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
Return Values
Always returns TRUE.
Examples
Example #1 pg_untrace() example
See Also
* pg_trace() - Enable tracing a PostgreSQL connection
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_update
(PHP 4 >= 4.3.0, PHP 5)
pg_update - Update table
Description
mixed pg_update ( resource $connection , string $table_name , array $data
, array $condition [, int $options = PGSQL_DML_EXEC ] )
pg_update() updates records that matches condition with data. If options
is specified, pg_convert() is applied to data with specified options.
Warning
This function is EXPERIMENTAL. The behaviour of this function, its name,
and surrounding documentation may change without notice in a future
release of PHP. This function should be used at your own risk.
Parameters
connection
PostgreSQL database connection resource.
table_name
Name of the table into which to update rows.
data
An array whose keys are field names in the table table_name, and
whose values are what matched rows are to be updated to.
condition
An array whose keys are field names in the table table_name, and
whose values are the conditions that a row must meet to be
updated.
options
Any number of PGSQL_CONV_OPTS, PGSQL_DML_NO_CONV, PGSQL_DML_EXEC
or PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the
options then query string is returned.
Return Values
Returns TRUE on success or FALSE on failure. Returns string if
PGSQL_DML_STRING is passed via options.
Examples
Example #1 pg_update() example
'AA', 'field2'=>'BB');
// This is safe, since $_POST is converted automatically
$res = pg_update($db, 'post_log', $_POST, $data);
if ($res) {
echo "Data is updated: $res\n";
} else {
echo "User must have sent wrong inputs\n";
}
?>
See Also
* pg_convert() - Convert associative array values into suitable for SQL
statement
----------------------------------------------------------------------
----------------------------------------------------------------------
pg_version
(PHP 5)
pg_version - Returns an array with client, protocol and server version
(when available)
Description
array pg_version ([ resource $connection ] )
pg_version() returns an array with the client, protocol and server
version. Protocol and server versions are only available if PHP was
compiled with PostgreSQL 7.4 or later.
For more detailed server information, use pg_parameter_status().
Parameters
connection
PostgreSQL database connection resource. When connection is not
present, the default connection is used. The default connection is
the last connection made by pg_connect() or pg_pconnect().
Return Values
Returns an array with client, protocol and server keys and values (if
available). Returns FALSE on error or invalid connection.
Examples
Example #1 pg_version() example
The above example will output:
7.4
See Also
* pg_parameter_status() - Looks up a current parameter setting of the
server.
----------------------------------------------------------------------
Table of Contents
* pg_affected_rows - Returns number of affected records (tuples)
* pg_cancel_query - Cancel an asynchronous query
* pg_client_encoding - Gets the client encoding
* pg_close - Closes a PostgreSQL connection
* pg_connect - Open a PostgreSQL connection
* pg_connection_busy - Get connection is busy or not
* pg_connection_reset - Reset connection (reconnect)
* pg_connection_status - Get connection status
* pg_convert - Convert associative array values into suitable for SQL
statement
* pg_copy_from - Insert records into a table from an array
* pg_copy_to - Copy a table to an array
* pg_dbname - Get the database name
* pg_delete - Deletes records
* pg_end_copy - Sync with PostgreSQL backend
* pg_escape_bytea - Escape a string for insertion into a bytea field
* pg_escape_string - Escape a string for insertion into a text field
* pg_execute - Sends a request to execute a prepared statement with
given parameters, and waits for the result.
* pg_fetch_all_columns - Fetches all rows in a particular result column
as an array
* pg_fetch_all - Fetches all rows from a result as an array
* pg_fetch_array - Fetch a row as an array
* pg_fetch_assoc - Fetch a row as an associative array
* pg_fetch_object - Fetch a row as an object
* pg_fetch_result - Returns values from a result resource
* pg_fetch_row - Get a row as an enumerated array
* pg_field_is_null - Test if a field is SQL NULL
* pg_field_name - Returns the name of a field
* pg_field_num - Returns the field number of the named field
* pg_field_prtlen - Returns the printed length
* pg_field_size - Returns the internal storage size of the named field
* pg_field_table - Returns the name or oid of the tables field
* pg_field_type_oid - Returns the type ID (OID) for the corresponding
field number
* pg_field_type - Returns the type name for the corresponding field
number
* pg_free_result - Free result memory
* pg_get_notify - Gets SQL NOTIFY message
* pg_get_pid - Gets the backend's process ID
* pg_get_result - Get asynchronous query result
* pg_host - Returns the host name associated with the connection
* pg_insert - Insert array into table
* pg_last_error - Get the last error message string of a connection
* pg_last_notice - Returns the last notice message from PostgreSQL
server
* pg_last_oid - Returns the last row's OID
* pg_lo_close - Close a large object
* pg_lo_create - Create a large object
* pg_lo_export - Export a large object to file
* pg_lo_import - Import a large object from file
* pg_lo_open - Open a large object
* pg_lo_read_all - Reads an entire large object and send straight to
browser
* pg_lo_read - Read a large object
* pg_lo_seek - Seeks position within a large object
* pg_lo_tell - Returns current seek position a of large object
* pg_lo_unlink - Delete a large object
* pg_lo_write - Write to a large object
* pg_meta_data - Get meta data for table
* pg_num_fields - Returns the number of fields in a result
* pg_num_rows - Returns the number of rows in a result
* pg_options - Get the options associated with the connection
* pg_parameter_status - Looks up a current parameter setting of the
server.
* pg_pconnect - Open a persistent PostgreSQL connection
* pg_ping - Ping database connection
* pg_port - Return the port number associated with the connection
* pg_prepare - Submits a request to create a prepared statement with the
given parameters, and waits for completion.
* pg_put_line - Send a NULL-terminated string to PostgreSQL backend
* pg_query_params - Submits a command to the server and waits for the
result, with the ability to pass parameters separately from the SQL
command text.
* pg_query - Execute a query
* pg_result_error_field - Returns an individual field of an error
report.
* pg_result_error - Get error message associated with result
* pg_result_seek - Set internal row offset in result resource
* pg_result_status - Get status of query result
* pg_select - Select records
* pg_send_execute - Sends a request to execute a prepared statement with
given parameters, without waiting for the result(s).
* pg_send_prepare - Sends a request to create a prepared statement with
the given parameters, without waiting for completion.
* pg_send_query_params - Submits a command and separate parameters to
the server without waiting for the result(s).
* pg_send_query - Sends asynchronous query
* pg_set_client_encoding - Set the client encoding
* pg_set_error_verbosity - Determines the verbosity of messages returned
by pg_last_error and pg_result_error.
* pg_trace - Enable tracing a PostgreSQL connection
* pg_transaction_status - Returns the current in-transaction status of
the server.
* pg_tty - Return the TTY name associated with the connection
* pg_unescape_bytea - Unescape binary for bytea type
* pg_untrace - Disable tracing of a PostgreSQL connection
* pg_update - Update table
* pg_version - Returns an array with client, protocol and server version
(when available)
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* Basic usage
* PostgreSQL Functions
* pg_affected_rows - Returns number of affected records (tuples)
* pg_cancel_query - Cancel an asynchronous query
* pg_client_encoding - Gets the client encoding
* pg_close - Closes a PostgreSQL connection
* pg_connect - Open a PostgreSQL connection
* pg_connection_busy - Get connection is busy or not
* pg_connection_reset - Reset connection (reconnect)
* pg_connection_status - Get connection status
* pg_convert - Convert associative array values into suitable for
SQL statement
* pg_copy_from - Insert records into a table from an array
* pg_copy_to - Copy a table to an array
* pg_dbname - Get the database name
* pg_delete - Deletes records
* pg_end_copy - Sync with PostgreSQL backend
* pg_escape_bytea - Escape a string for insertion into a bytea
field
* pg_escape_string - Escape a string for insertion into a text
field
* pg_execute - Sends a request to execute a prepared statement with
given parameters, and waits for the result.
* pg_fetch_all_columns - Fetches all rows in a particular result
column as an array
* pg_fetch_all - Fetches all rows from a result as an array
* pg_fetch_array - Fetch a row as an array
* pg_fetch_assoc - Fetch a row as an associative array
* pg_fetch_object - Fetch a row as an object
* pg_fetch_result - Returns values from a result resource
* pg_fetch_row - Get a row as an enumerated array
* pg_field_is_null - Test if a field is SQL NULL
* pg_field_name - Returns the name of a field
* pg_field_num - Returns the field number of the named field
* pg_field_prtlen - Returns the printed length
* pg_field_size - Returns the internal storage size of the named
field
* pg_field_table - Returns the name or oid of the tables field
* pg_field_type_oid - Returns the type ID (OID) for the
corresponding field number
* pg_field_type - Returns the type name for the corresponding field
number
* pg_free_result - Free result memory
* pg_get_notify - Gets SQL NOTIFY message
* pg_get_pid - Gets the backend's process ID
* pg_get_result - Get asynchronous query result
* pg_host - Returns the host name associated with the connection
* pg_insert - Insert array into table
* pg_last_error - Get the last error message string of a connection
* pg_last_notice - Returns the last notice message from PostgreSQL
server
* pg_last_oid - Returns the last row's OID
* pg_lo_close - Close a large object
* pg_lo_create - Create a large object
* pg_lo_export - Export a large object to file
* pg_lo_import - Import a large object from file
* pg_lo_open - Open a large object
* pg_lo_read_all - Reads an entire large object and send straight
to browser
* pg_lo_read - Read a large object
* pg_lo_seek - Seeks position within a large object
* pg_lo_tell - Returns current seek position a of large object
* pg_lo_unlink - Delete a large object
* pg_lo_write - Write to a large object
* pg_meta_data - Get meta data for table
* pg_num_fields - Returns the number of fields in a result
* pg_num_rows - Returns the number of rows in a result
* pg_options - Get the options associated with the connection
* pg_parameter_status - Looks up a current parameter setting of the
server.
* pg_pconnect - Open a persistent PostgreSQL connection
* pg_ping - Ping database connection
* pg_port - Return the port number associated with the connection
* pg_prepare - Submits a request to create a prepared statement
with the given parameters, and waits for completion.
* pg_put_line - Send a NULL-terminated string to PostgreSQL backend
* pg_query_params - Submits a command to the server and waits for
the result, with the ability to pass parameters separately from
the SQL command text.
* pg_query - Execute a query
* pg_result_error_field - Returns an individual field of an error
report.
* pg_result_error - Get error message associated with result
* pg_result_seek - Set internal row offset in result resource
* pg_result_status - Get status of query result
* pg_select - Select records
* pg_send_execute - Sends a request to execute a prepared statement
with given parameters, without waiting for the result(s).
* pg_send_prepare - Sends a request to create a prepared statement
with the given parameters, without waiting for completion.
* pg_send_query_params - Submits a command and separate parameters
to the server without waiting for the result(s).
* pg_send_query - Sends asynchronous query
* pg_set_client_encoding - Set the client encoding
* pg_set_error_verbosity - Determines the verbosity of messages
returned by pg_last_error and pg_result_error.
* pg_trace - Enable tracing a PostgreSQL connection
* pg_transaction_status - Returns the current in-transaction status
of the server.
* pg_tty - Return the TTY name associated with the connection
* pg_unescape_bytea - Unescape binary for bytea type
* pg_untrace - Disable tracing of a PostgreSQL connection
* pg_update - Update table
* pg_version - Returns an array with client, protocol and server
version (when available)
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite
----------------------------------------------------------------------
Introduction
This is an extension for the SQLite Embeddable SQL Database Engine. SQLite
is a C library that implements an embeddable SQL database engine. Programs
that link with the SQLite library can have SQL database access without
running a separate RDBMS process.
SQLite is not a client library used to connect to a big database server.
SQLite is the server. The SQLite library reads and writes directly to and
from the database files on disk.
Note:
For further information see the SQLite Website (>> http://sqlite.org/).
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
The SQLite extension is enabled by default as of PHP 5. Before that time
the SQLite library is needed.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
As of PHP 5 this extension is enabled by default, so simply do not disable
it and it'll be available.
Caution
Do not use the PECL version of this extension, as it is unmaintained.
Always use the SQLite extension that comes with the PHP sources even while
compiling as shared. In this case the sources are in
php-src-dir/ext/sqlite and the phpize method of building applies.
Windows users must enable php_sqlite.dll inside of php.ini in order to use
these functions. A DLL for this PECL extension is currently unavailable.
See also the building on Windows section.
Windows builds must also enable PDO because as of PHP 5.1.0 it depends on
it. So, php.ini will end up with something like this:
extension=php_pdo.dll
extension=php_sqlite.dll
On Linux or Unix operating systems, if you build PDO as a shared
extension, you must build SQLite as a shared extension using the
--with-sqlite=shared configure option.
The PHP 5.0.x series of Windows builds enabled this extension by default,
where no DLL file is necessary.
SQLite 3 is supported through PDO SQLite.
Note: Windows installation for unprivileged accounts
On Windows operating systems, unprivileged accounts don't have the TMP
environment variable set by default. This will make sqlite create
temporary files in the windows directory, which is not desirable. So,
you should set the TMP environment variable for the web server or the
user account the web server is running under. If Apache is your web
server, you can accomplish this via a SetEnv directive in your
httpd.conf file. For example:
SetEnv TMP c:/temp
If you are unable to establish this setting at the server level, you can
implement the setting in your script:
The setting must refer to a directory that the web server has permission
to create files in and subsequently write to and delete the files it
created. Otherwise, you may receive the following error message:
malformed database schema - unable to open a temporary database file for
storing temporary tables
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
SQLite Configure Options
Name Default Changeable Changelog
sqlite.assoc_case "0" PHP_INI_ALL Available since PHP 5.0.0.
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
Here's a short explanation of the configuration directives.
sqlite.assoc_case int
Whether to use mixed case (0), upper case (1) or lower case (2)
hash indexes.
This option is primarily useful when you need compatibility with
other database systems, where the names of the columns are always
returned as uppercase or lowercase, regardless of the case of the
actual field names in the database schema.
The SQLite library returns the column names in their natural case
(that matches the case you used in your schema). When
sqlite.assoc_case is set to 0 the natural case will be preserved.
When it is set to 1 or 2, PHP will apply case folding on the hash
keys to upper- or lower-case the keys, respectively.
Use of this option incurs a slight performance penalty, but is
MUCH faster than performing the case folding yourself using PHP
script.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
There are two resources used in the SQLite Interface. The first one is the
database connection, the second one the result set.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
The functions sqlite_fetch_array() and sqlite_current() use a constant for
the different types of result arrays. The following constants are defined:
SQLite result type constants
SQLITE_ASSOC (int)
Columns are returned into the array having the field name as the
array index.
SQLITE_BOTH (int)
Columns are returned into the array having both a numerical index
and the field name as the array index.
SQLITE_NUM (int)
Columns are returned into the array having a numerical index to
the fields. This index starts with 0, the first field in the
result.
A number of functions may return status codes. The following constants are
defined:
SQLite status code constants
SQLITE_OK (int)
Successful result.
SQLITE_ERROR (int)
SQL error or missing database.
SQLITE_INTERNAL (int)
An internal logic error in SQLite.
SQLITE_PERM (int)
Access permission denied.
SQLITE_ABORT (int)
Callback routine requested an abort.
SQLITE_BUSY (int)
The database file is locked.
SQLITE_LOCKED (int)
A table in the database is locked.
SQLITE_NOMEM (int)
Memory allocation failed.
SQLITE_READONLY (int)
Attempt to write a readonly database.
SQLITE_INTERRUPT (int)
Operation terminated internally.
SQLITE_IOERR (int)
Disk I/O error occurred.
SQLITE_NOTADB (int)
File opened that is not a database file.
SQLITE_CORRUPT (int)
The database disk image is malformed.
SQLITE_FORMAT (int)
Auxiliary database format error.
SQLITE_NOTFOUND (int)
(Internal) Table or record not found.
SQLITE_FULL (int)
Insertion failed because database is full.
SQLITE_CANTOPEN (int)
Unable to open the database file.
SQLITE_PROTOCOL (int)
Database lock protocol error.
SQLITE_EMPTY (int)
(Internal) Database table is empty.
SQLITE_SCHEMA (int)
The database schema changed.
SQLITE_TOOBIG (int)
Too much data for one row of a table.
SQLITE_CONSTRAINT (int)
Abort due to constraint violation.
SQLITE_MISMATCH (int)
Data type mismatch.
SQLITE_MISUSE (int)
Library used incorrectly.
SQLITE_NOLFS (int)
Uses of OS features not supported on host.
SQLITE_AUTH (int)
Authorized failed.
SQLITE_ROW (int)
Internal process has another row ready.
SQLITE_DONE (int)
Internal process has finished executing.
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite Functions
Predefined Classes
SQLiteDatabase
Represents an opened SQLite database.
Constructor
* __construct - construct a new SQLiteDatabase object
Methods
* query - Execute a query
* queryExec - Execute a result-less query
* arrayQuery - Execute a query and return the result as an array
* singleQuery - Execute a query and return either an array for one
single column or the value of the first row
* unbufferedQuery - Execute an unbuffered query
* lastInsertRowid - Returns the rowid of the most recently inserted row
* changes - Returns the number of rows changed by the most recent
statement
* createAggregate - Register an aggregating UDF for use in SQL
statements
* createFunction - Register a UDF for use in SQL statements
* busyTimeout - Sets or disables busy timeout duration
* lastError - Returns the last error code of the most recently
encountered error
* fetchColumnTypes - Return an array of column types from a particular
table
SQLiteResult
Represents a buffered SQLite result set.
Methods
* fetch - Fetches the next row from the result set as an array
* fetchObject - Fetches the next row from the result set as an object
* fetchSingle - Fetches the first column from the result set as a string
* fetchAll - Fetches all rows from the result set as an array of arrays
* column - Fetches a column from the current row of the result set
* numFields - Returns the number of fields in the result set
* fieldName - Returns the name of a particular field in the result set
* current - Fetches the current row from the result set as an array
* key - Return the current row index
* next - Seek to the next row number
* valid - Returns whether more rows are available
* rewind - Seek to the first row number of the result set
* prev - Seek to the previous row number of the result set
* hasPrev - Returns whether or not a previous row is available
* numRows - Returns the number of rows in the result set
* seek - Seek to a particular row number
SQLiteUnbuffered
Represents an unbuffered SQLite result set. Unbuffered results sets are
sequential, forward-seeking only.
Methods
* fetch - Fetches the next row from the result set as an array
* fetchObject - Fetches the next row from the result set as an object
* fetchSingle - Fetches the first column from the result set as a string
* fetchAll - Fetches all rows from the result set as an array of arrays
* column - Fetches a column from the current row of the result set
* numFields - Returns the number of fields in the result set
* fieldName - Returns the name of a particular field in the result set
* current - Fetches the current row from the result set as an array
* next - Seek to the next row number
* valid - Returns whether more rows are available
----------------------------------------------------------------------
sqlite_array_query
SQLiteDatabase->arrayQuery
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_array_query -- SQLiteDatabase->arrayQuery - Execute a query against
a given database and returns an array
Description
array sqlite_array_query ( resource $dbhandle , string $query [, int
$result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )
array sqlite_array_query ( string $query , resource $dbhandle [, int
$result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )
Object oriented style (method):
array SQLiteDatabase::arrayQuery ( string $query [, int $result_type =
SQLITE_BOTH [, bool $decode_binary = true ]] )
sqlite_array_query() executes the given query and returns an array of the
entire result set. It is similar to calling sqlite_query() and then
sqlite_fetch_array() for each row in the result set. sqlite_array_query()
is significantly faster than the aforementioned.
Tip
sqlite_array_query() is best suited to queries returning 45 rows or less.
If you have more data than that, it is recommended that you write your
scripts to use sqlite_unbuffered_query() instead for more optimal
performance.
Parameters
query
The query to be executed.
Data inside the query should be properly escaped.
dbhandle
The SQLite Database resource; returned from sqlite_open() when
used procedurally. This parameter is not required when using the
object-oriented method.
result_type
The optional result_type parameter accepts a constant and
determines how the returned array will be indexed. Using
SQLITE_ASSOC will return only associative indices (named fields)
while SQLITE_NUM will return only numerical indices (ordinal field
numbers). SQLITE_BOTH will return both associative and numerical
indices. SQLITE_BOTH is the default for this function.
decode_binary
When the decode_binary parameter is set to TRUE (the default), PHP
will decode the binary encoding it applied to the data if it was
encoded using the sqlite_escape_string(). You should normally
leave this value at its default, unless you are interoperating
with databases created by other sqlite capable applications.
Note: Two alternative syntaxes are supported for compatibility with
other database extensions (such as MySQL). The preferred form is the
first, where the dbhandle parameter is the first parameter to the
function.
Return Values
Returns an array of the entire result set; FALSE otherwise.
The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be
case-folded according to the value of the sqlite.assoc_case configuration
option.
Examples
Example #1 Procedural style
Example #2 Object-oriented style
arrayQuery('SELECT name, email FROM users LIMIT 25', SQLITE_ASSOC);
foreach ($result as $entry) {
echo 'Name: ' . $entry['name'] . ' E-mail: ' . $entry['email'];
}
?>
See Also
* sqlite_query() - Executes a query against a given database and returns
a result handle
* sqlite_fetch_array() - Fetches the next row from a result set as an
array
* sqlite_fetch_string() - Alias of sqlite_fetch_single
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_busy_timeout
SQLiteDatabase->busyTimeout
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_busy_timeout -- SQLiteDatabase->busyTimeout - Set busy timeout
duration, or disable busy handlers
Description
void sqlite_busy_timeout ( resource $dbhandle , int $milliseconds )
Object oriented style (method):
void SQLiteDatabase::busyTimeout ( int $milliseconds )
Set the maximum time, in milliseconds, that SQLite will wait for a
dbhandle to become ready for use.
Parameters
dbhandle
The SQLite Database resource; returned from sqlite_open() when
used procedurally. This parameter is not required when using the
object-oriented method.
milliseconds
The number of milliseconds. When set to 0, busy handlers will be
disabled and SQLite will return immediately with a SQLITE_BUSY
status code if another process/thread has the database locked for
an update.
PHP sets the default busy timeout to be 60 seconds when the
database is opened.
Note:
There are one thousand (1000) milliseconds in one second.
Return Values
No value is returned.
Examples
Example #1 Procedural style
Example #2 Object oriented style
busyTimeout(10000); // 10 seconds
$dbhandle->busyTimeout(0); // disable
?>
See Also
* sqlite_open() - Opens an SQLite database and create the database if it
does not exist
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_changes
SQLiteDatabase->changes
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_changes -- SQLiteDatabase->changes - Returns the number of rows
that were changed by the most recent SQL statement
Description
int sqlite_changes ( resource $dbhandle )
Object oriented style (method):
int SQLiteDatabase::changes ( void )
Returns the numbers of rows that were changed by the most recent SQL
statement executed against the dbhandle database handle.
Parameters
dbhandle
The SQLite Database resource; returned from sqlite_open() when
used procedurally. This parameter is not required when using the
object-oriented method.
Return Values
Returns the number of changed rows.
Examples
Example #1 Procedural style
Example #2 Object oriented style
query("UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'");
if (!$query) {
exit('Error in query.');
} else {
echo 'Number of rows modified: ', $dbhandle->changes();
}
?>
See Also
* sqlite_open() - Opens an SQLite database and create the database if it
does not exist
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_close
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_close - Closes an open SQLite database
Description
void sqlite_close ( resource $dbhandle )
Closes the given db_handle database handle. If the database was
persistent, it will be closed and removed from the persistent list.
Parameters
dbhandle
The SQLite Database resource; returned from sqlite_open() when
used procedurally.
Return Values
No value is returned.
Examples
Example #1 sqlite_close() example
See Also
* sqlite_open() - Opens an SQLite database and create the database if it
does not exist
* sqlite_popen() - Opens a persistent handle to an SQLite database and
create the database if it does not exist
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_column
SQLiteResult->column
SQLiteUnbuffered->column
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_column -- SQLiteResult->column -- SQLiteUnbuffered->column -
Fetches a column from the current row of a result set
Description
mixed sqlite_column ( resource $result , mixed $index_or_name [, bool
$decode_binary = true ] )
mixed SQLiteResult::column ( mixed $index_or_name [, bool $decode_binary =
true ] )
mixed SQLiteUnbuffered::column ( mixed $index_or_name [, bool
$decode_binary = true ] )
Fetches the value of a column named index_or_name (if it is a string), or
of the ordinal column numbered index_or_name (if it is an integer) from
the current row of the query result handle result.
Parameters
result
The SQLite result resource. This parameter is not required when
using the object-oriented method.
index_or_name
The column index or name to fetch.
decode_binary
When the decode_binary parameter is set to TRUE (the default), PHP
will decode the binary encoding it applied to the data if it was
encoded using the sqlite_escape_string(). You should normally
leave this value at its default, unless you are interoperating
with databases created by other sqlite capable applications.
Return Values
Returns the column value.
Notes
Note:
Use this function when you are iterating a large result set with many
columns, or with columns that contain large amounts of data.
See Also
* sqlite_fetch_string() - Alias of sqlite_fetch_single
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_create_aggregate
SQLiteDatabase->createAggregate
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_create_aggregate -- SQLiteDatabase->createAggregate - Register an
aggregating UDF for use in SQL statements
Description
void sqlite_create_aggregate ( resource $dbhandle , string $function_name
, callback $step_func , callback $finalize_func [, int $num_args = -1 ] )
Object oriented style (method):
void SQLiteDatabase::createAggregate ( string $function_name , callback
$step_func , callback $finalize_func [, int $num_args = -1 ] )
sqlite_create_aggregate() is similar to sqlite_create_function() except
that it registers functions that can be used to calculate a result
aggregated across all the rows of a query.
The key difference between this function and sqlite_create_function() is
that two functions are required to manage the aggregate; step_func is
called for each row of the result set. Your PHP function should accumulate
the result and store it into the aggregation context. Once all the rows
have been processed, finalize_func will be called and it should then take
the data from the aggregation context and return the result. Callback
functions should return a type understood by SQLite (i.e. scalar type).
Parameters
dbhandle
The SQLite Database resource; returned from sqlite_open() when
used procedurally. This parameter is not required when using the
object-oriented method.
function_name
The name of the function used in SQL statements.
step_func
Callback function called for each row of the result set. Function
parameters are &$context, $value, ....
finalize_func
Callback function to aggregate the "stepped" data from each row.
Function parameter is &$context and the function should return the
final result of aggregation.
num_args
Hint to the SQLite parser if the callback function accepts a
predetermined number of arguments.
Return Values
No value is returned.
Examples
Example #1 max_length aggregation function example
$context) {
$context = strlen($string);
}
}
function max_len_finalize(&$context)
{
return $context;
}
sqlite_create_aggregate($dbhandle, 'max_len', 'max_len_step', 'max_len_finalize');
var_dump(sqlite_array_query($dbhandle, 'SELECT max_len(a) from strings'));
?>
In this example, we are creating an aggregating function that will
calculate the length of the longest string in one of the columns of the
table. For each row, the max_len_step function is called and passed a
context parameter. The context parameter is just like any other PHP
variable and be set to hold an array or even an object value. In this
example, we are simply using it to hold the maximum length we have seen so
far; if the string has a length longer than the current maximum, we update
the context to hold this new maximum length.
After all of the rows have been processed, SQLite calls the
max_len_finalize function to determine the aggregate result. Here, we
could perform some kind of calculation based on the data found in the
context. In our simple example though, we have been calculating the result
as the query progressed, so we simply need to return the context value.
Note:
The example above will not work correctly if the column contains binary
data. Take a look at the manual page for sqlite_udf_decode_binary() for
an explanation of why this is so, and an example of how to make it
respect the binary encoding.
Tip
It is NOT recommended for you to store a copy of the values in the context
and then process them at the end, as you would cause SQLite to use a lot
of memory to process the query - just think of how much memory you would
need if a million rows were stored in memory, each containing a string 32
bytes in length.
Tip
You can use sqlite_create_function() and sqlite_create_aggregate() to
override SQLite native SQL functions.
See Also
* sqlite_create_function() - Registers a "regular" User Defined Function
for use in SQL statements
* sqlite_udf_encode_binary() - Encode binary data before returning it
from an UDF
* sqlite_udf_decode_binary() - Decode binary data passed as parameters
to an UDF
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_create_function
SQLiteDatabase->createFunction
(PHP 5, sqlite >= 1.0.0)
sqlite_create_function -- SQLiteDatabase->createFunction - Registers a
"regular" User Defined Function for use in SQL statements
Description
void sqlite_create_function ( resource $dbhandle , string $function_name ,
callback $callback [, int $num_args = -1 ] )
Object oriented style (method):
void SQLiteDatabase::createFunction ( string $function_name , callback
$callback [, int $num_args = -1 ] )
sqlite_create_function() allows you to register a PHP function with SQLite
as an UDF (User Defined Function), so that it can be called from within
your SQL statements.
The UDF can be used in any SQL statement that can call functions, such as
SELECT and UPDATE statements and also in triggers.
Parameters
dbhandle
The SQLite Database resource; returned from sqlite_open() when
used procedurally. This parameter is not required when using the
object-oriented method.
function_name
The name of the function used in SQL statements.
callback
Callback function to handle the defined SQL function.
Note: Callback functions should return a type understood by
SQLite (i.e. scalar type).
num_args
Hint to the SQLite parser if the callback function accepts a
predetermined number of arguments.
Note: Two alternative syntaxes are supported for compatibility with
other database extensions (such as MySQL). The preferred form is the
first, where the dbhandle parameter is the first parameter to the
function.
Return Values
No value is returned.
Examples
Example #1 sqlite_create_function() example
In this example, we have a function that calculates the md5 sum of a
string, and then reverses it. When the SQL statement executes, it returns
the value of the filename transformed by our function. The data returned
in $rows contains the processed result.
The beauty of this technique is that you do not need to process the result
using a foreach loop after you have queried for the data.
PHP registers a special function named php when the database is first
opened. The php function can be used to call any PHP function without
having to register it first.
Example #2 Example of using the PHP function
This example will call the md5() on each filename column in the database
and return the result into $rows
Note:
For performance reasons, PHP will not automatically encode/decode binary
data passed to and from your UDF's. You need to manually encode/decode
the parameters and return values if you need to process binary data in
this way. Take a look at sqlite_udf_encode_binary() and
sqlite_udf_decode_binary() for more details.
Tip
It is not recommended to use UDF's to handle processing of binary data,
unless high performance is not a key requirement of your application.
Tip
You can use sqlite_create_function() and sqlite_create_aggregate() to
override SQLite native SQL functions.
See Also
* sqlite_create_aggregate() - Register an aggregating UDF for use in SQL
statements
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_current
SQLiteResult->current
SQLiteUnbuffered->current
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_current -- SQLiteResult->current -- SQLiteUnbuffered->current -
Fetches the current row from a result set as an array
Description
array sqlite_current ( resource $result [, int $result_type = SQLITE_BOTH
[, bool $decode_binary = true ]] )
Object oriented style (method):
array SQLiteResult::current ([ int $result_type = SQLITE_BOTH [, bool
$decode_binary = true ]] )
array SQLiteUnbuffered::current ([ int $result_type = SQLITE_BOTH [, bool
$decode_binary = true ]] )
sqlite_current() is identical to sqlite_fetch_array() except that it does
not advance to the next row prior to returning the data; it returns the
data from the current position only.
Parameters
result
The SQLite result resource. This parameter is not required when
using the object-oriented method.
result_type
The optional result_type parameter accepts a constant and
determines how the returned array will be indexed. Using
SQLITE_ASSOC will return only associative indices (named fields)
while SQLITE_NUM will return only numerical indices (ordinal field
numbers). SQLITE_BOTH will return both associative and numerical
indices. SQLITE_BOTH is the default for this function.
decode_binary
When the decode_binary parameter is set to TRUE (the default), PHP
will decode the binary encoding it applied to the data if it was
encoded using the sqlite_escape_string(). You should normally
leave this value at its default, unless you are interoperating
with databases created by other sqlite capable applications.
Return Values
Returns an array of the current row from a result set; FALSE if the
current position is beyond the final row.
The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be
case-folded according to the value of the sqlite.assoc_case configuration
option.
See Also
* sqlite_seek() - Seek to a particular row number of a buffered result
set
* sqlite_next() - Seek to the next row number
* sqlite_fetch_array() - Fetches the next row from a result set as an
array
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_error_string
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_error_string - Returns the textual description of an error code
Description
string sqlite_error_string ( int $error_code )
Returns a human readable description of the error_code returned from
sqlite_last_error().
Parameters
error_code
The error code being used, which might be passed in from
sqlite_last_error().
Return Values
Returns a human readable description of the error_code, as a string.
See Also
* sqlite_last_error() - Returns the error code of the last error for a
database
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_escape_string
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_escape_string - Escapes a string for use as a query parameter
Description
string sqlite_escape_string ( string $item )
sqlite_escape_string() will correctly quote the string specified by item
for use in an SQLite SQL statement. This includes doubling up single-quote
characters (') and checking for binary-unsafe characters in the query
string.
Although the encoding makes it safe to insert the data, it will render
simple text comparisons and LIKE clauses in your queries unusable for the
columns that contain the binary data. In practice, this shouldn't be a
problem, as your schema should be such that you don't use such things on
binary columns (in fact, it might be better to store binary data using
other means, such as in files).
Parameters
item
The string being quoted.
If the item contains a NUL character, or if it begins with a
character whose ordinal value is 0x01, PHP will apply a binary
encoding scheme so that you can safely store and retrieve binary
data.
Return Values
Returns an escaped string for use in an SQLite SQL statement.
Notes
Note: Do not use this function to encode the return values from UDF's
created using sqlite_create_function() or sqlite_create_aggregate() -
use sqlite_udf_encode_binary() instead.
Warning
addslashes() should NOT be used to quote your strings for SQLite queries;
it will lead to strange results when retrieving your data.
See Also
* sqlite_udf_encode_binary() - Encode binary data before returning it
from an UDF
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_exec
SQLiteDatabase->exec
(PHP 5, PECL sqlite >= 1.0.3)
sqlite_exec -- SQLiteDatabase->exec - Executes a result-less query against
a given database
Description
bool sqlite_exec ( resource $dbhandle , string $query [, string
&$error_msg ] )
bool sqlite_exec ( string $query , resource $dbhandle )
Object oriented style (method):
bool SQLiteDatabase::queryExec ( string $query [, string &$error_msg ] )
Executes an SQL statement given by the query against a given database
handle (specified by the dbhandle parameter).
Warning
SQLite will execute multiple queries separated by semicolons, so you can
use it to execute a batch of SQL that you have loaded from a file or have
embedded in a script.
Parameters
dbhandle
The SQLite Database resource; returned from sqlite_open() when
used procedurally. This parameter is not required when using the
object-oriented method.
query
The query to be executed.
Data inside the query should be properly escaped.
error_msg
The specified variable will be filled if an error occurs. This is
specially important because SQL syntax errors can't be fetched
using the sqlite_last_error() function.
Note: Two alternative syntaxes are supported for compatibility with
other database extensions (such as MySQL). The preferred form is the
first, where the dbhandle parameter is the first parameter to the
function.
Return Values
This function will return a boolean result; TRUE for success or FALSE for
failure. If you need to run a query that returns rows, see sqlite_query().
The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be
case-folded according to the value of the sqlite.assoc_case configuration
option.
Changelog
Version Description
5.1.0 Added the error_msg parameter
Examples
Example #1 Procedural example
Example #2 Object-oriented example
queryExec("UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'", $error);
if (!$query) {
exit("Error in query: '$error'");
} else {
echo 'Number of rows modified: ', $dbhandle->changes();
}
?>
See Also
* sqlite_query() - Executes a query against a given database and returns
a result handle
* sqlite_unbuffered_query() - Execute a query that does not prefetch and
buffer all data
* sqlite_array_query() - Execute a query against a given database and
returns an array
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_factory
(PHP 5)
sqlite_factory - Opens an SQLite database and returns an SQLiteDatabase
object
Description
SQLiteDatabase sqlite_factory ( string $filename [, int $mode = 0666 [,
string &$error_message ]] )
sqlite_factory() behaves similarly to sqlite_open() in that it opens an
SQLite database or attempts to create it if it does not exist. However, a
SQLiteDatabase object is returned rather than a resource. Please see the
sqlite_open() reference page for further usage and caveats.
Parameters
filename
The filename of the SQLite database.
mode
The mode of the file. Intended to be used to open the database in
read-only mode. Presently, this parameter is ignored by the sqlite
library. The default value for mode is the octal value 0666 and
this is the recommended value.
error_message
Passed by reference and is set to hold a descriptive error message
explaining why the database could not be opened if there was an
error.
Return Values
Returns an SQLiteDatabase object on success, NULL on error.
Examples
Example #1 sqlite_factory() example
query('SELECT user_id, username FROM users');
/* functionally equivalent to: */
$dbhandle = new SQLiteDatabase('sqlitedb');
$dbhandle->query('SELECT user_id, username FROM users');
?>
See Also
* sqlite_open() - Opens an SQLite database and create the database if it
does not exist
* sqlite_popen() - Opens a persistent handle to an SQLite database and
create the database if it does not exist
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_fetch_all
SQLiteResult->fetchAll
SQLiteUnbuffered->fetchAll
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_fetch_all -- SQLiteResult->fetchAll -- SQLiteUnbuffered->fetchAll -
Fetches all rows from a result set as an array of arrays
Description
array sqlite_fetch_all ( resource $result [, int $result_type =
SQLITE_BOTH [, bool $decode_binary = true ]] )
Object oriented style (method):
array SQLiteResult::fetchAll ([ int $result_type = SQLITE_BOTH [, bool
$decode_binary = true ]] )
array SQLiteUnbuffered::fetchAll ([ int $result_type = SQLITE_BOTH [, bool
$decode_binary = true ]] )
sqlite_fetch_all() returns an array of the entire result set from the
result resource. It is similar to calling sqlite_query() (or
sqlite_unbuffered_query()) and then sqlite_fetch_array() for each row in
the result set.
Parameters
result
The SQLite result resource. This parameter is not required when
using the object-oriented method.
result_type
The optional result_type parameter accepts a constant and
determines how the returned array will be indexed. Using
SQLITE_ASSOC will return only associative indices (named fields)
while SQLITE_NUM will return only numerical indices (ordinal field
numbers). SQLITE_BOTH will return both associative and numerical
indices. SQLITE_BOTH is the default for this function.
decode_binary
When the decode_binary parameter is set to TRUE (the default), PHP
will decode the binary encoding it applied to the data if it was
encoded using the sqlite_escape_string(). You should normally
leave this value at its default, unless you are interoperating
with databases created by other sqlite capable applications.
Return Values
Returns an array of the remaining rows in a result set. If called right
after sqlite_query(), it returns all rows. If called after
sqlite_fetch_array(), it returns the rest. If there are no rows in a
result set, it returns an empty array.
The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be
case-folded according to the value of the sqlite.assoc_case configuration
option.
Examples
Example #1 Procedural example
Example #2 Object-oriented example
query('SELECT name, email FROM users LIMIT 25'); // buffered result set
$query = $dbhandle->unbufferedQuery('SELECT name, email FROM users LIMIT 25'); // unbuffered result set
$result = $query->fetchAll(SQLITE_ASSOC);
foreach ($result as $entry) {
echo 'Name: ' . $entry['name'] . ' E-mail: ' . $entry['email'];
}
?>
See Also
* sqlite_fetch_array() - Fetches the next row from a result set as an
array
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_fetch_array
SQLiteResult->fetch
SQLiteUnbuffered->fetch
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_fetch_array -- SQLiteResult->fetch -- SQLiteUnbuffered->fetch -
Fetches the next row from a result set as an array
Description
array sqlite_fetch_array ( resource $result [, int $result_type =
SQLITE_BOTH [, bool $decode_binary = true ]] )
Object oriented style (method):
array SQLiteResult::fetch ([ int $result_type = SQLITE_BOTH [, bool
$decode_binary = true ]] )
array SQLiteUnbuffered::fetch ([ int $result_type = SQLITE_BOTH [, bool
$decode_binary = true ]] )
Fetches the next row from the given result handle. If there are no more
rows, returns FALSE, otherwise returns an associative array representing
the row data.
Parameters
result
The SQLite result resource. This parameter is not required when
using the object-oriented method.
result_type
The optional result_type parameter accepts a constant and
determines how the returned array will be indexed. Using
SQLITE_ASSOC will return only associative indices (named fields)
while SQLITE_NUM will return only numerical indices (ordinal field
numbers). SQLITE_BOTH will return both associative and numerical
indices. SQLITE_BOTH is the default for this function.
decode_binary
When the decode_binary parameter is set to TRUE (the default), PHP
will decode the binary encoding it applied to the data if it was
encoded using the sqlite_escape_string(). You should normally
leave this value at its default, unless you are interoperating
with databases created by other sqlite capable applications.
Return Values
Returns an array of the next row from a result set; FALSE if the next
position is beyond the final row.
The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be
case-folded according to the value of the sqlite.assoc_case configuration
option.
Examples
Example #1 Procedural example
Example #2 Object-oriented example
query('SELECT name, email FROM users LIMIT 25'); // buffered result set
$query = $dbhandle->unbufferedQuery('SELECT name, email FROM users LIMIT 25'); // unbuffered result set
while ($entry = $query->fetch(SQLITE_ASSOC)) {
echo 'Name: ' . $entry['name'] . ' E-mail: ' . $entry['email'];
}
?>
See Also
* sqlite_array_query() - Execute a query against a given database and
returns an array
* sqlite_fetch_string() - Alias of sqlite_fetch_single
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_fetch_column_types
SQLiteDatabase->fetchColumnTypes
(PHP 5)
sqlite_fetch_column_types -- SQLiteDatabase->fetchColumnTypes - Return an
array of column types from a particular table
Description
array sqlite_fetch_column_types ( string $table_name , resource $dbhandle
[, int $result_type = SQLITE_ASSOC ] )
Object oriented style (method):
array SQLiteDatabase::fetchColumnTypes ( string $table_name [, int
$result_type = SQLITE_ASSOC ] )
sqlite_fetch_column_types() returns an array of column data types from the
specified table_name table.
Parameters
table_name
The table name to query.
dbhandle
The SQLite Database resource; returned from sqlite_open() when
used procedurally. This parameter is not required when using the
object-oriented method.
result_type
The optional result_type parameter accepts a constant and
determines how the returned array will be indexed. Using
SQLITE_ASSOC will return only associative indices (named fields)
while SQLITE_NUM will return only numerical indices (ordinal field
numbers). SQLITE_ASSOC is the default for this function.
Return Values
Returns an array of column data types; FALSE on error.
The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be
case-folded according to the value of the sqlite.assoc_case configuration
option.
Changelog
Version Description
5.1.0 Added result_type
Examples
Example #1 Procedural example
$type) {
echo "Column: $column Type: $type\n";
}
?>
Example #2 Object-oriented example
query('CREATE TABLE foo (bar varchar(10), arf text)');
$cols = $db->fetchColumnTypes('foo', SQLITE_ASSOC);
foreach ($cols as $column => $type) {
echo "Column: $column Type: $type\n";
}
?>
The above example will output:
Column: bar Type: VARCHAR
Column: arf Type: TEXT
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_fetch_object
SQLiteResult->fetchObject
SQLiteUnbuffered->fetchObject
(PHP 5)
sqlite_fetch_object -- SQLiteResult->fetchObject --
SQLiteUnbuffered->fetchObject - Fetches the next row from a result set as
an object
Description
object sqlite_fetch_object ( resource $result [, string $class_name [,
array $ctor_params [, bool $decode_binary = true ]]] )
Object oriented style (method):
object SQLiteResult::fetchObject ([ string $class_name [, array
$ctor_params [, bool $decode_binary = true ]]] )
object SQLiteUnbuffered::fetchObject ([ string $class_name [, array
$ctor_params [, bool $decode_binary = true ]]] )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_fetch_single
SQLiteResult->fetchSingle
SQLiteUnbuffered->fetchSingle
(PHP 5, PECL sqlite >= 1.0.1)
sqlite_fetch_single -- SQLiteResult->fetchSingle --
SQLiteUnbuffered->fetchSingle - Fetches the first column of a result set
as a string
Description
string sqlite_fetch_single ( resource $result [, bool $decode_binary =
true ] )
Object oriented style (method):
string SQLiteResult::fetchSingle ([ bool $decode_binary = true ] )
string SQLiteUnbuffered::fetchSingle ([ bool $decode_binary = true ] )
sqlite_fetch_single() is identical to sqlite_fetch_array() except that it
returns the value of the first column of the rowset.
This is the most optimal way to retrieve data when you are only interested
in the values from a single column of data.
Parameters
result
The SQLite result resource. This parameter is not required when
using the object-oriented method.
decode_binary
When the decode_binary parameter is set to TRUE (the default), PHP
will decode the binary encoding it applied to the data if it was
encoded using the sqlite_escape_string(). You should normally
leave this value at its default, unless you are interoperating
with databases created by other sqlite capable applications.
Return Values
Returns the first column value, as a string.
Examples
Example #1 A sqlite_fetch_single() example
0) {
echo sqlite_fetch_single($res); // 42
}
sqlite_close($dbhandle);
}
?>
See Also
* sqlite_fetch_array() - Fetches the next row from a result set as an
array
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_fetch_string
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_fetch_string - Alias of sqlite_fetch_single()
Description
This function is an alias of: sqlite_fetch_single().
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_field_name
SQLiteResult->fieldName
SQLiteUnbuffered->fieldName
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_field_name -- SQLiteResult->fieldName --
SQLiteUnbuffered->fieldName - Returns the name of a particular field
Description
string sqlite_field_name ( resource $result , int $field_index )
Object oriented style (method):
string SQLiteResult::fieldName ( int $field_index )
string SQLiteUnbuffered::fieldName ( int $field_index )
Given the ordinal column number, field_index, sqlite_field_name() returns
the name of that field in the result set result.
Parameters
result
The SQLite result resource. This parameter is not required when
using the object-oriented method.
field_index
The ordinal column number in the result set.
Return Values
Returns the name of a field in an SQLite result set, given the ordinal
column number; FALSE on error.
The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be
case-folded according to the value of the sqlite.assoc_case configuration
option.
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_has_more
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_has_more - Finds whether or not more rows are available
Description
bool sqlite_has_more ( resource $result )
Finds whether more rows are available from the given result set.
Parameters
result
The SQLite result resource.
Return Values
Returns TRUE if there are more rows available from the result handle, or
FALSE otherwise.
See Also
* sqlite_num_rows() - Returns the number of rows in a buffered result
set
* sqlite_changes() - Returns the number of rows that were changed by the
most recent SQL statement
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_has_prev
SQLiteResult->hasPrev
(PHP 5)
sqlite_has_prev -- SQLiteResult->hasPrev - Returns whether or not a
previous row is available
Description
bool sqlite_has_prev ( resource $result )
Object oriented style (method):
bool SQLiteResult::hasPrev ( void )
Find whether there are more previous rows from the given result handle.
Parameters
result
The SQLite result resource. This parameter is not required when
using the object-oriented method.
Note:
This function cannot be used with unbuffered result handles.
Return Values
Returns TRUE if there are more previous rows available from the result
handle, or FALSE otherwise.
See Also
* sqlite_prev() - Seek to the previous row number of a result set
* sqlite_has_more() - Finds whether or not more rows are available
* sqlite_num_rows() - Returns the number of rows in a buffered result
set
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_key
SQLiteResult->key
(PHP 5 >= 5.1.0)
sqlite_key -- SQLiteResult->key - Returns the current row index
Description
int sqlite_key ( resource $result )
Object oriented style (method):
int SQLiteResult::key ( void )
sqlite_key() returns the current row index of the buffered result set
result.
Parameters
result
The SQLite result resource. This parameter is not required when
using the object-oriented method.
Note:
This function cannot be used with unbuffered result handles.
Return Values
Returns the current row index of the buffered result set result.
Changelog
Version Description
5.0.4 Prior to PHP 5.0.4, sqlite_key() was only able to be called as a
method on a SQLiteResult object, not procedurally.
See Also
* sqlite_next() - Seek to the next row number
* sqlite_current() - Fetches the current row from a result set as an
array
* sqlite_rewind() - Seek to the first row number
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_last_error
SQLiteDatabase->lastError
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_last_error -- SQLiteDatabase->lastError - Returns the error code of
the last error for a database
Description
int sqlite_last_error ( resource $dbhandle )
Object oriented style (method):
int SQLiteDatabase::lastError ( void )
Returns the error code from the last operation performed on dbhandle (the
database handle), or 0 when no error occurred. A human readable
description of the error code can be retrieved using
sqlite_error_string().
Parameters
dbhandle
The SQLite Database resource; returned from sqlite_open() when
used procedurally. This parameter is not required when using the
object-oriented method.
Return Values
Returns an error code, or 0 if no error occurred.
See Also
* sqlite_error_string() - Returns the textual description of an error
code
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_last_insert_rowid
SQLiteDatabase->lastInsertRowid
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_last_insert_rowid -- SQLiteDatabase->lastInsertRowid - Returns the
rowid of the most recently inserted row
Description
int sqlite_last_insert_rowid ( resource $dbhandle )
Object oriented style (method):
int SQLiteDatabase::lastInsertRowid ( void )
Returns the rowid of the row that was most recently inserted into the
database dbhandle, if it was created as an auto-increment field.
Tip
You can create auto-increment fields in SQLite by declaring them as
INTEGER PRIMARY KEY in your table schema.
Parameters
dbhandle
The SQLite Database resource; returned from sqlite_open() when
used procedurally. This parameter is not required when using the
object-oriented method.
Return Values
Returns the row id, as an integer.
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_libencoding
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_libencoding - Returns the encoding of the linked SQLite library
Description
string sqlite_libencoding ( void )
The SQLite library may be compiled in either ISO-8859-1 or UTF-8
compatible modes. This function allows you to determine which encoding
scheme is used by your version of the library.
Warning
The default PHP distribution builds libsqlite in ISO-8859-1 encoding mode.
However, this is a misnomer; rather than handling ISO-8859-1, it operates
according to your current locale settings for string comparisons and sort
ordering. So, rather than ISO-8859-1, you should think of it as being
'8-bit' instead.
When compiled with UTF-8 support, sqlite handles encoding and decoding of
UTF-8 multi-byte character sequences, but does not yet do a complete job
when working with the data (no normalization is performed for example),
and some comparison operations may still not be carried out correctly.
Warning
It is not recommended that you use PHP in a web-server configuration with
a version of the SQLite library compiled with UTF-8 support, since
libsqlite will abort the process if it detects a problem with the UTF-8
encoding.
Return Values
Returns the library encoding.
See Also
* sqlite_lib_version()
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_libversion
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_libversion - Returns the version of the linked SQLite library
Description
string sqlite_libversion ( void )
Returns the version of the linked SQLite library.
Return Values
Returns the library version, as a string.
See Also
* sqlite_libencoding() - Returns the encoding of the linked SQLite
library
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_next
SQLiteResult->next
SQLiteUnbuffered->next
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_next -- SQLiteResult->next -- SQLiteUnbuffered->next - Seek to the
next row number
Description
bool sqlite_next ( resource $result )
Object oriented style (method):
bool SQLiteResult::next ( void )
bool SQLiteUnbuffered::next ( void )
sqlite_next() advances the result handle result to the next row.
Parameters
result
The SQLite result resource. This parameter is not required when
using the object-oriented method.
Return Values
Returns TRUE on success, or FALSE if there are no more rows.
See Also
* sqlite_seek() - Seek to a particular row number of a buffered result
set
* sqlite_current() - Fetches the current row from a result set as an
array
* sqlite_rewind() - Seek to the first row number
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_num_fields
SQLiteResult->numFields
SQLiteUnbuffered->numFields
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_num_fields -- SQLiteResult->numFields --
SQLiteUnbuffered->numFields - Returns the number of fields in a result set
Description
int sqlite_num_fields ( resource $result )
Object oriented style (method):
int SQLiteResult::numFields ( void )
int SQLiteUnbuffered::numFields ( void )
Returns the number of fields in the result set.
Parameters
result
The SQLite result resource. This parameter is not required when
using the object-oriented method.
Return Values
Returns the number of fields, as an integer.
See Also
* sqlite_changes() - Returns the number of rows that were changed by the
most recent SQL statement
* sqlite_num_rows() - Returns the number of rows in a buffered result
set
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_num_rows
SQLiteResult->numRows
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_num_rows -- SQLiteResult->numRows - Returns the number of rows in a
buffered result set
Description
int sqlite_num_rows ( resource $result )
Object oriented style (method):
int SQLiteResult::numRows ( void )
Returns the number of rows in the buffered result set.
Parameters
result
The SQLite result resource. This parameter is not required when
using the object-oriented method.
Note:
This function cannot be used with unbuffered result handles.
Return Values
Returns the number of rows, as an integer.
Examples
Example #1 Procedural example
Example #2 Object-oriented example
query("SELECT * FROM mytable WHERE name='John Doe'");
$rows = $result->numRows();
echo "Number of rows: $rows";
?>
See Also
* sqlite_changes() - Returns the number of rows that were changed by the
most recent SQL statement
* sqlite_query() - Executes a query against a given database and returns
a result handle
* sqlite_num_fields() - Returns the number of fields in a result set
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_open
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_open - Opens an SQLite database and create the database if it does
not exist
Description
resource sqlite_open ( string $filename [, int $mode = 0666 [, string
&$error_message ]] )
Object oriented style (constructor):
SQLiteDatabase::__construct ( string $filename [, int $mode = 0666 [,
string &$error_message ]] )
Opens an SQLite database or creates the database if it does not exist.
Parameters
filename
The filename of the SQLite database. If the file does not exist,
SQLite will attempt to create it. PHP must have write permissions
to the file if data is inserted, the database schema is modified
or to create the database if it does not exist.
mode
The mode of the file. Intended to be used to open the database in
read-only mode. Presently, this parameter is ignored by the sqlite
library. The default value for mode is the octal value 0666 and
this is the recommended value.
error_message
Passed by reference and is set to hold a descriptive error message
explaining why the database could not be opened if there was an
error.
Return Values
Returns a resource (database handle) on success, FALSE on error.
Examples
Example #1 sqlite_open() example
Notes
Tip
On Unix platforms, SQLite is sensitive to scripts that use the fork()
system call. If you do have such a script, it is recommended that you
close the handle prior to forking and then re-open it in the child and/or
parent. For more information on this issue, see >> The C language
interface to the SQLite library in the section entitled Multi-Threading
And SQLite.
Tip
It is not recommended to work with SQLite databases mounted on NFS
partitions. Since NFS is notoriously bad when it comes to locking you may
find that you cannot even open the database at all, and if it succeeds,
the locking behaviour may be undefined.
Note: Starting with SQLite library version 2.8.2, you can specify
:memory: as the filename to create a database that lives only in the
memory of the computer. This is useful mostly for temporary processing,
as the in-memory database will be destroyed when the process ends. It
can also be useful when coupled with the ATTACH DATABASE SQL statement
to load other databases and move and query data between them.
Note: SQLite is safe mode and open_basedir aware.
See Also
* sqlite_popen() - Opens a persistent handle to an SQLite database and
create the database if it does not exist
* sqlite_close() - Closes an open SQLite database
* sqlite_factory() - Opens an SQLite database and returns an
SQLiteDatabase object
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_popen
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_popen - Opens a persistent handle to an SQLite database and create
the database if it does not exist
Description
resource sqlite_popen ( string $filename [, int $mode = 0666 [, string
&$error_message ]] )
This function behaves identically to sqlite_open() except that is uses the
persistent resource mechanism of PHP. For information about the meaning of
the parameters, read the sqlite_open() manual page.
sqlite_popen() will first check to see if a persistent handle has already
been opened for the given filename. If it finds one, it returns that
handle to your script, otherwise it opens a fresh handle to the database.
The benefit of this approach is that you don't incur the performance cost
of re-reading the database and index schema on each page hit served by
persistent web server SAPI's (any SAPI except for regular CGI or CLI).
Note: If you use persistent handles and have the database updated by a
background process (perhaps via a crontab), and that process re-creates
the database by overwriting it (either by unlinking and rebuilding, or
moving the updated version to replace the current version), you may
experience undefined behaviour when a persistent handle on the old
version of the database is recycled. To avoid this situation, have your
background processes open the same database file and perform their
updates in a transaction.
Parameters
filename
The filename of the SQLite database. If the file does not exist,
SQLite will attempt to create it. PHP must have write permissions
to the file if data is inserted, the database schema is modified
or to create the database if it does not exist.
mode
The mode of the file. Intended to be used to open the database in
read-only mode. Presently, this parameter is ignored by the sqlite
library. The default value for mode is the octal value 0666 and
this is the recommended value.
error_message
Passed by reference and is set to hold a descriptive error message
explaining why the database could not be opened if there was an
error.
Return Values
Returns a resource (database handle) on success, FALSE on error.
See Also
* sqlite_open() - Opens an SQLite database and create the database if it
does not exist
* sqlite_close() - Closes an open SQLite database
* sqlite_factory() - Opens an SQLite database and returns an
SQLiteDatabase object
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_prev
SQLiteResult->prev
(PHP 5)
sqlite_prev -- SQLiteResult->prev - Seek to the previous row number of a
result set
Description
bool sqlite_prev ( resource $result )
Object oriented style (method):
bool SQLiteResult::prev ( void )
sqlite_prev() seeks back the result handle to the previous row.
Parameters
result
The SQLite result resource. This parameter is not required when
using the object-oriented method.
Note:
This function cannot be used with unbuffered result handles.
Return Values
Returns TRUE on success, or FALSE if there are no more previous rows.
See Also
* sqlite_has_prev() - Returns whether or not a previous row is available
* sqlite_rewind() - Seek to the first row number
* sqlite_next() - Seek to the next row number
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_query
SQLiteDatabase->query
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_query -- SQLiteDatabase->query - Executes a query against a given
database and returns a result handle
Description
resource sqlite_query ( resource $dbhandle , string $query [, int
$result_type = SQLITE_BOTH [, string &$error_msg ]] )
resource sqlite_query ( string $query , resource $dbhandle [, int
$result_type = SQLITE_BOTH [, string &$error_msg ]] )
Object oriented style (method):
SQLiteResult SQLiteDatabase::query ( string $query [, int $result_type =
SQLITE_BOTH [, string &$error_msg ]] )
Executes an SQL statement given by the query against a given database
handle.
Parameters
dbhandle
The SQLite Database resource; returned from sqlite_open() when
used procedurally. This parameter is not required when using the
object-oriented method.
query
The query to be executed.
Data inside the query should be properly escaped.
result_type
The optional result_type parameter accepts a constant and
determines how the returned array will be indexed. Using
SQLITE_ASSOC will return only associative indices (named fields)
while SQLITE_NUM will return only numerical indices (ordinal field
numbers). SQLITE_BOTH will return both associative and numerical
indices. SQLITE_BOTH is the default for this function.
error_msg
The specified variable will be filled if an error occurs. This is
specially important because SQL syntax errors can't be fetched
using the sqlite_last_error() function.
Note: Two alternative syntaxes are supported for compatibility with
other database extensions (such as MySQL). The preferred form is the
first, where the dbhandle parameter is the first parameter to the
function.
Return Values
This function will return a result handle or FALSE on failure. For queries
that return rows, the result handle can then be used with functions such
as sqlite_fetch_array() and sqlite_seek().
Regardless of the query type, this function will return FALSE if the query
failed.
sqlite_query() returns a buffered, seekable result handle. This is useful
for reasonably small queries where you need to be able to randomly access
the rows. Buffered result handles will allocate memory to hold the entire
result and will not return until it has been fetched. If you only need
sequential access to the data, it is recommended that you use the much
higher performance sqlite_unbuffered_query() instead.
Changelog
Version Description
5.1.0 Added the error_msg parameter
Notes
Warning
SQLite will execute multiple queries separated by semicolons, so you can
use it to execute a batch of SQL that you have loaded from a file or have
embedded in a script. However, this works only when the result of the
function is not used - if it is used, only the first SQL statement would
be executed. Function sqlite_exec() will always execute multiple SQL
statements.
When executing multiple queries, the return value of this function will be
FALSE if there was an error, but undefined otherwise (it might be TRUE for
success or it might return a result handle).
See Also
* sqlite_unbuffered_query() - Execute a query that does not prefetch and
buffer all data
* sqlite_array_query() - Execute a query against a given database and
returns an array
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_rewind
SQLiteResult->rewind
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_rewind -- SQLiteResult->rewind - Seek to the first row number
Description
bool sqlite_rewind ( resource $result )
Object oriented style (method):
bool SQLiteResult::rewind ( void )
sqlite_rewind() seeks back to the first row in the given result set.
Parameters
result
The SQLite result resource. This parameter is not required when
using the object-oriented method.
Note:
This function cannot be used with unbuffered result handles.
Return Values
Returns FALSE if there are no rows in the result set, TRUE otherwise.
See Also
* sqlite_next() - Seek to the next row number
* sqlite_current() - Fetches the current row from a result set as an
array
* sqlite_seek() - Seek to a particular row number of a buffered result
set
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_seek
SQLiteResult->seek
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_seek -- SQLiteResult->seek - Seek to a particular row number of a
buffered result set
Description
bool sqlite_seek ( resource $result , int $rownum )
Object oriented style (method):
bool SQLiteResult::seek ( int $rownum )
sqlite_seek() seeks to the row given by the parameter rownum.
Parameters
result
The SQLite result resource. This parameter is not required when
using the object-oriented method.
Note:
This function cannot be used with unbuffered result handles.
rownum
The ordinal row number to seek to. The row number is zero-based (0
is the first row).
Note:
This function cannot be used with unbuffered result handles.
Return Values
Returns FALSE if the row does not exist, TRUE otherwise.
See Also
* sqlite_next() - Seek to the next row number
* sqlite_current() - Fetches the current row from a result set as an
array
* sqlite_rewind() - Seek to the first row number
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_single_query
SQLiteDatabase->singleQuery
(PHP 5, PECL sqlite >= 1.0.1)
sqlite_single_query -- SQLiteDatabase->singleQuery - Executes a query and
returns either an array for one single column or the value of the first
row
Description
array sqlite_single_query ( resource $db , string $query [, bool
$first_row_only [, bool $decode_binary ]] )
Object oriented style (method):
array SQLiteDatabase::singleQuery ( string $query [, bool $first_row_only
[, bool $decode_binary ]] )
Warning
This function is currently not documented; only its argument list is
available.
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_udf_decode_binary
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_udf_decode_binary - Decode binary data passed as parameters to an
UDF
Description
string sqlite_udf_decode_binary ( string $data )
Decodes binary data passed as parameters to a UDF.
You must call this function on parameters passed to your UDF if you need
them to handle binary data, as the binary encoding employed by PHP will
obscure the content and of the parameter in its natural, non-coded form.
PHP does not perform this encode/decode operation automatically as it
would severely impact performance if it did.
Parameters
data
The encoded data that will be decoded, data that was applied by
either sqlite_udf_encode_binary() or sqlite_escape_string().
Return Values
The decoded string.
Examples
Example #1 binary-safe max_length aggregation function example
$context) {
$context = strlen($string);
}
}
function max_len_finalize(&$context)
{
return $context;
}
sqlite_create_aggregate($db, 'max_len', 'max_len_step', 'max_len_finalize');
var_dump(sqlite_array_query($db, 'SELECT max_len(a) from strings'));
?>
See Also
* sqlite_udf_encode_binary() - Encode binary data before returning it
from an UDF
* sqlite_create_function() - Registers a "regular" User Defined Function
for use in SQL statements
* sqlite_create_aggregate() - Register an aggregating UDF for use in SQL
statements
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_udf_encode_binary
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_udf_encode_binary - Encode binary data before returning it from an
UDF
Description
string sqlite_udf_encode_binary ( string $data )
sqlite_udf_encode_binary() applies a binary encoding to the data so that
it can be safely returned from queries (since the underlying libsqlite API
is not binary safe).
If there is a chance that your data might be binary unsafe (e.g.: it
contains a NUL byte in the middle rather than at the end, or if it has and
0x01 byte as the first character) then you must call this function to
encode the return value from your UDF.
PHP does not perform this encode/decode operation automatically as it
would severely impact performance if it did.
Note:
Do not use sqlite_escape_string() to quote strings returned from UDF's
as it will lead to double-quoting of the data. Use
sqlite_udf_encode_binary() instead!
Parameters
data
The string being encoded.
Return Values
The encoded string.
See Also
* sqlite_udf_decode_binary() - Decode binary data passed as parameters
to an UDF
* sqlite_escape_string() - Escapes a string for use as a query parameter
* sqlite_create_function() - Registers a "regular" User Defined Function
for use in SQL statements
* sqlite_create_aggregate() - Register an aggregating UDF for use in SQL
statements
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_unbuffered_query
SQLiteDatabase->unbufferedQuery
(PHP 5, PECL sqlite >= 1.0.0)
sqlite_unbuffered_query -- SQLiteDatabase->unbufferedQuery - Execute a
query that does not prefetch and buffer all data
Description
resource sqlite_unbuffered_query ( resource $dbhandle , string $query [,
int $result_type = SQLITE_BOTH [, string &$error_msg ]] )
resource sqlite_unbuffered_query ( string $query , resource $dbhandle [,
int $result_type = SQLITE_BOTH [, string &$error_msg ]] )
Object oriented style (method):
SQLiteUnbuffered SQLiteDatabase::unbufferedQuery ( string $query [, int
$result_type = SQLITE_BOTH [, string &$error_msg ]] )
sqlite_unbuffered_query() is identical to sqlite_query() except that the
result that is returned is a sequential forward-only result set that can
only be used to read each row, one after the other.
This function is ideal for generating things such as HTML tables where you
only need to process one row at a time and don't need to randomly access
the row data.
Note:
Functions such as sqlite_seek(), sqlite_rewind(), sqlite_next(),
sqlite_current(), and sqlite_num_rows() do not work on result handles
returned from sqlite_unbuffered_query().
Parameters
dbhandle
The SQLite Database resource; returned from sqlite_open() when
used procedurally. This parameter is not required when using the
object-oriented method.
query
The query to be executed.
Data inside the query should be properly escaped.
result_type
The optional result_type parameter accepts a constant and
determines how the returned array will be indexed. Using
SQLITE_ASSOC will return only associative indices (named fields)
while SQLITE_NUM will return only numerical indices (ordinal field
numbers). SQLITE_BOTH will return both associative and numerical
indices. SQLITE_BOTH is the default for this function.
error_msg
The specified variable will be filled if an error occurs. This is
specially important because SQL syntax errors can't be fetched
using the sqlite_last_error() function.
Note: Two alternative syntaxes are supported for compatibility with
other database extensions (such as MySQL). The preferred form is the
first, where the dbhandle parameter is the first parameter to the
function.
Return Values
Returns a result handle or FALSE on failure.
sqlite_unbuffered_query() returns a sequential forward-only result set
that can only be used to read each row, one after the other.
Changelog
Version Description
5.1.0 Added the error_msg parameter
See Also
* sqlite_query() - Executes a query against a given database and returns
a result handle
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlite_valid
SQLiteResult->valid
SQLiteUnbuffered->valid
(PHP 5)
sqlite_valid -- SQLiteResult->valid -- SQLiteUnbuffered->valid - Returns
whether more rows are available
Description
bool sqlite_valid ( resource $result )
Object oriented style (method):
bool SQLiteResult::valid ( void )
bool SQLiteUnbuffered::valid ( void )
Finds whether more rows are available from the given result handle.
Parameters
result
The SQLite result resource. This parameter is not required when
using the object-oriented method.
Note:
This function cannot be used with unbuffered result handles.
Return Values
Returns TRUE if there are more rows available from the result handle, or
FALSE otherwise.
See Also
* sqlite_num_rows() - Returns the number of rows in a buffered result
set
* sqlite_changes() - Returns the number of rows that were changed by the
most recent SQL statement
----------------------------------------------------------------------
Table of Contents
* sqlite_array_query - Execute a query against a given database and
returns an array
* sqlite_busy_timeout - Set busy timeout duration, or disable busy
handlers
* sqlite_changes - Returns the number of rows that were changed by the
most recent SQL statement
* sqlite_close - Closes an open SQLite database
* sqlite_column - Fetches a column from the current row of a result set
* sqlite_create_aggregate - Register an aggregating UDF for use in SQL
statements
* sqlite_create_function - Registers a "regular" User Defined Function
for use in SQL statements
* sqlite_current - Fetches the current row from a result set as an array
* sqlite_error_string - Returns the textual description of an error code
* sqlite_escape_string - Escapes a string for use as a query parameter
* sqlite_exec - Executes a result-less query against a given database
* sqlite_factory - Opens an SQLite database and returns an
SQLiteDatabase object
* sqlite_fetch_all - Fetches all rows from a result set as an array of
arrays
* sqlite_fetch_array - Fetches the next row from a result set as an
array
* sqlite_fetch_column_types - Return an array of column types from a
particular table
* sqlite_fetch_object - Fetches the next row from a result set as an
object
* sqlite_fetch_single - Fetches the first column of a result set as a
string
* sqlite_fetch_string - Alias of sqlite_fetch_single
* sqlite_field_name - Returns the name of a particular field
* sqlite_has_more - Finds whether or not more rows are available
* sqlite_has_prev - Returns whether or not a previous row is available
* sqlite_key - Returns the current row index
* sqlite_last_error - Returns the error code of the last error for a
database
* sqlite_last_insert_rowid - Returns the rowid of the most recently
inserted row
* sqlite_libencoding - Returns the encoding of the linked SQLite library
* sqlite_libversion - Returns the version of the linked SQLite library
* sqlite_next - Seek to the next row number
* sqlite_num_fields - Returns the number of fields in a result set
* sqlite_num_rows - Returns the number of rows in a buffered result set
* sqlite_open - Opens an SQLite database and create the database if it
does not exist
* sqlite_popen - Opens a persistent handle to an SQLite database and
create the database if it does not exist
* sqlite_prev - Seek to the previous row number of a result set
* sqlite_query - Executes a query against a given database and returns a
result handle
* sqlite_rewind - Seek to the first row number
* sqlite_seek - Seek to a particular row number of a buffered result set
* sqlite_single_query - Executes a query and returns either an array for
one single column or the value of the first row
* sqlite_udf_decode_binary - Decode binary data passed as parameters to
an UDF
* sqlite_udf_encode_binary - Encode binary data before returning it from
an UDF
* sqlite_unbuffered_query - Execute a query that does not prefetch and
buffer all data
* sqlite_valid - Returns whether more rows are available
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* SQLite Functions
* sqlite_array_query - Execute a query against a given database and
returns an array
* sqlite_busy_timeout - Set busy timeout duration, or disable busy
handlers
* sqlite_changes - Returns the number of rows that were changed by
the most recent SQL statement
* sqlite_close - Closes an open SQLite database
* sqlite_column - Fetches a column from the current row of a result
set
* sqlite_create_aggregate - Register an aggregating UDF for use in
SQL statements
* sqlite_create_function - Registers a "regular" User Defined
Function for use in SQL statements
* sqlite_current - Fetches the current row from a result set as an
array
* sqlite_error_string - Returns the textual description of an error
code
* sqlite_escape_string - Escapes a string for use as a query
parameter
* sqlite_exec - Executes a result-less query against a given
database
* sqlite_factory - Opens an SQLite database and returns an
SQLiteDatabase object
* sqlite_fetch_all - Fetches all rows from a result set as an array
of arrays
* sqlite_fetch_array - Fetches the next row from a result set as an
array
* sqlite_fetch_column_types - Return an array of column types from
a particular table
* sqlite_fetch_object - Fetches the next row from a result set as
an object
* sqlite_fetch_single - Fetches the first column of a result set as
a string
* sqlite_fetch_string - Alias of sqlite_fetch_single
* sqlite_field_name - Returns the name of a particular field
* sqlite_has_more - Finds whether or not more rows are available
* sqlite_has_prev - Returns whether or not a previous row is
available
* sqlite_key - Returns the current row index
* sqlite_last_error - Returns the error code of the last error for
a database
* sqlite_last_insert_rowid - Returns the rowid of the most recently
inserted row
* sqlite_libencoding - Returns the encoding of the linked SQLite
library
* sqlite_libversion - Returns the version of the linked SQLite
library
* sqlite_next - Seek to the next row number
* sqlite_num_fields - Returns the number of fields in a result set
* sqlite_num_rows - Returns the number of rows in a buffered result
set
* sqlite_open - Opens an SQLite database and create the database if
it does not exist
* sqlite_popen - Opens a persistent handle to an SQLite database
and create the database if it does not exist
* sqlite_prev - Seek to the previous row number of a result set
* sqlite_query - Executes a query against a given database and
returns a result handle
* sqlite_rewind - Seek to the first row number
* sqlite_seek - Seek to a particular row number of a buffered
result set
* sqlite_single_query - Executes a query and returns either an
array for one single column or the value of the first row
* sqlite_udf_decode_binary - Decode binary data passed as
parameters to an UDF
* sqlite_udf_encode_binary - Encode binary data before returning it
from an UDF
* sqlite_unbuffered_query - Execute a query that does not prefetch
and buffer all data
* sqlite_valid - Returns whether more rows are available
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3
----------------------------------------------------------------------
Introduction
Support for SQLite version 3 databases.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
The SQLite3 extension is enabled by default as of PHP 5.3.0. It's possible
to disable it by using --without-sqlite3 at compile time.
Windows users must enable php_sqlite3.dll in order to use this extension.
This DLL is included with Windows distributions of PHP as of PHP 5.3.0.
Note:
This extension was briefly a PECL extension but that version is only
recommended for experimental use.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
SQLite3 Configure Options
Name Default Changeable Changelog
sqlite3.extension_dir NULL PHP_INI_SYSTEM
Here's a short explanation of the configuration directives.
sqlite3.extension_dir string
Path to the directory where the loadable extensions for SQLite
reside.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
SQLITE3_ASSOC (integer)
Specifies that the Sqlite3Result::fetchArray() method shall return
an array indexed by column name as returned in the corresponding
result set.
SQLITE3_NUM (integer)
Specifies that the Sqlite3Result::fetchArray() method shall return
an array indexed by column number as returned in the corresponding
result set, starting at column 0.
SQLITE3_BOTH (integer)
Specifies that the Sqlite3Result::fetchArray() method shall return
an array indexed by both column name and number as returned in the
corresponding result set, starting at column 0.
SQLITE3_INTEGER (integer)
Represents the SQLite3 INTEGER storage class.
SQLITE3_FLOAT (integer)
Represents the SQLite3 REAL (FLOAT) storage class.
SQLITE3_TEXT (integer)
Represents the SQLite3 TEXT storage class.
SQLITE3_BLOB (integer)
Represents the SQLite3 BLOB storage class.
SQLITE3_NULL (integer)
Represents the SQLite3 NULL storage class.
SQLITE3_OPEN_READONLY (integer)
Specifies that the SQLite3 database be opened for reading only.
SQLITE3_OPEN_READWRITE (integer)
Specifies that the SQLite3 database be opened for reading and
writing.
SQLITE3_OPEN_CREATE (integer)
Specifies that the SQLite3 database be created if it does not
already exist.
----------------------------------------------------------------------
----------------------------------------------------------------------
The SQLite3 class
Introduction
A class that interfaces SQLite 3 databases.
Class synopsis
SQLite3 {
/* Methods */
public bool busyTimeout ( int $msecs )
public int changes ( void )
public bool close ( void )
__construct ( string $filename [, int $flags [, string $encryption_key ]]
)
public bool createAggregate ( string $name , mixed $step_callback , mixed
$final_callback [, int $argument_count = -1 ] )
public bool createFunction ( string $name , mixed $callback [, int
$argument_count = -1 ] )
public string escapeString ( string $value )
public bool exec ( string $query )
public int lastErrorCode ( void )
public string lastErrorMsg ( void )
public int lastInsertRowID ( void )
public bool loadExtension ( string $shared_library )
public void open ( string $filename [, int $flags = SQLITE3_OPEN_READWRITE
| SQLITE3_OPEN_CREATE [, string $encryption_key ]] )
public SQLite3Stmt prepare ( string $query )
public SQLite3Result query ( string $query )
public mixed querySingle ( string $query [, bool $entire_row = false ] )
public array version ( void )
}
----------------------------------------------------------------------
SQLite3::busyTimeout
(PHP 5 >= 5.3.3)
SQLite3::busyTimeout - Sets the busy connection handler
Description
public bool SQLite3::busyTimeout ( int $msecs )
Sets a busy handler that will sleep until the database is not locked or
the timeout is reached.
Parameters
msecs
The milliseconds to sleep. Setting this value to a value less than
or equal to zero, will turn off an already set timeout handler.
Return Values
Returns TRUE on success, FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3::changes
(PHP 5 >= 5.3.0)
SQLite3::changes - Returns the number of database rows that were changed
(or inserted or deleted) by the most recent SQL statement
Description
public int SQLite3::changes ( void )
Returns the number of database rows that were changed (or inserted or
deleted) by the most recent SQL statement.
Parameters
This function has no parameters.
Return Values
Returns an integer value corresponding to the number of database rows
changed (or inserted or deleted) by the most recent SQL statement.
Examples
Example #1 SQLite3::changes() example
exec('UPDATE counter SET views=0 WHERE page="test"');
if ($query) {
echo 'Number of rows modified: ', $db->changes();
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3::close
(PHP 5 >= 5.3.0)
SQLite3::close - Closes the database connection
Description
public bool SQLite3::close ( void )
Closes the database connection.
Parameters
This function has no parameters.
Return Values
Returns TRUE on success, FALSE on failure.
Examples
Example #1 SQLite3::close() example
close();
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3::__construct
(PHP 5 >= 5.3.0)
SQLite3::__construct - Instantiates an SQLite3 object and opens an SQLite
3 database
Description
SQLite3::__construct ( string $filename [, int $flags [, string
$encryption_key ]] )
Instantiates an SQLite3 object and opens a connection to an SQLite 3
database. If the build includes encryption, then it will attempt to use
the key.
Parameters
filename
Path to the SQLite database, or :memory: to use in-memory
database.
flags
Optional flags used to determine how to open the SQLite database.
By default, open uses SQLITE3_OPEN_READWRITE |
SQLITE3_OPEN_CREATE.
* SQLITE3_OPEN_READONLY: Open the database for reading only.
* SQLITE3_OPEN_READWRITE: Open the database for reading and
writing.
* SQLITE3_OPEN_CREATE: Create the database if it does not
exist.
encryption_key
An optional encryption key used when encrypting and decrypting an
SQLite database.
Return Values
Returns an SQLite3 object on success.
Examples
Example #1 SQLite3::__construct() example
exec('CREATE TABLE foo (bar STRING)');
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");
$result = $db->query('SELECT bar FROM foo');
var_dump($result->fetchArray());
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3::createAggregate
(PHP 5 >= 5.3.0)
SQLite3::createAggregate - Registers a PHP function for use as an SQL
aggregate function
Description
public bool SQLite3::createAggregate ( string $name , mixed $step_callback
, mixed $final_callback [, int $argument_count = -1 ] )
Registers a PHP function or user-defined function for use as an SQL
aggregate function for use within SQL statements.
Parameters
name
Name of the SQL aggregate to be created or redefined.
step_callback
The name of a PHP function or user-defined function to apply as a
callback for every item in the aggregate.
final_callback
The name of a PHP function or user-defined function to apply as a
callback at the end of the aggregate data.
argument_count
The number of arguments that the SQL aggregate takes. If this
parameter is negative, then the SQL aggregate may take any number
of arguments.
Return Values
Returns TRUE upon successful creation of the aggregate, FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3::createFunction
(PHP 5 >= 5.3.0)
SQLite3::createFunction - Registers a PHP function for use as an SQL
scalar function
Description
public bool SQLite3::createFunction ( string $name , mixed $callback [,
int $argument_count = -1 ] )
Registers a PHP function or user-defined function for use as an SQL scalar
function for use within SQL statements.
Parameters
name
Name of the SQL function to be created or redefined.
callback
The name of a PHP function or user-defined function to apply as a
callback, defining the behavior of the SQL function.
argument_count
The number of arguments that the SQL function takes. If this
parameter is negative, then the SQL function may take any number
of arguments.
Return Values
Returns TRUE upon successful creation of the function, FALSE on failure.
Examples
Example #1 SQLite3::createFunction() example
createFunction('my_udf_md5', 'my_udf_md5');
var_dump($db->querySingle('SELECT my_udf_md5("test")'));
?>
The above example will output something similar to:
string(32) "098f6bcd4621d373cade4e832627b4f6"
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3::escapeString
(PHP 5 >= 5.3.0)
SQLite3::escapeString - Returns a string that has been properly escaped
Description
public string SQLite3::escapeString ( string $value )
Returns a string that has been properly escaped for safe inclusion in an
SQL statement.
Parameters
value
The string to be escaped.
Return Values
Returns a properly escaped string that may be used safely in an SQL
statement.
Notes
Warning
addslashes() should NOT be used to quote your strings for SQLite queries;
it will lead to strange results when retrieving your data.
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3::exec
(PHP 5 >= 5.3.0)
SQLite3::exec - Executes a result-less query against a given database
Description
public bool SQLite3::exec ( string $query )
Executes a result-less query against a given database.
Parameters
query
The SQL query to execute (typically an INSERT, UPDATE, or DELETE
query).
Return Values
Returns TRUE if the query succeeded, FALSE on failure.
Examples
Example #1 SQLite3::exec() example
exec('CREATE TABLE bar (bar STRING)');
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3::lastErrorCode
(PHP 5 >= 5.3.0)
SQLite3::lastErrorCode - Returns the numeric result code of the most
recent failed SQLite request
Description
public int SQLite3::lastErrorCode ( void )
Returns the numeric result code of the most recent failed SQLite request.
Parameters
This function has no parameters.
Return Values
Returns an integer value representing the numeric result code of the most
recent failed SQLite request.
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3::lastErrorMsg
(PHP 5 >= 5.3.0)
SQLite3::lastErrorMsg - Returns English text describing the most recent
failed SQLite request
Description
public string SQLite3::lastErrorMsg ( void )
Returns English text describing the most recent failed SQLite request.
Parameters
This function has no parameters.
Return Values
Returns an English string describing the most recent failed SQLite
request.
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3::lastInsertRowID
(PHP 5 >= 5.3.0)
SQLite3::lastInsertRowID - Returns the row ID of the most recent INSERT
into the database
Description
public int SQLite3::lastInsertRowID ( void )
Returns the row ID of the most recent INSERT into the database.
Parameters
This function has no parameters.
Return Values
Returns the row ID of the most recent INSERT into the database
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3::loadExtension
(PHP 5 >= 5.3.0)
SQLite3::loadExtension - Attempts to load an SQLite extension library
Description
public bool SQLite3::loadExtension ( string $shared_library )
Attempts to load an SQLite extension library.
Parameters
shared_library
The name of the library to load. The library must be located in
the directory specified in the configure option
sqlite3.extension_dir.
Return Values
Returns TRUE if the extension is successfully loaded, FALSE on failure.
Examples
Example #1 SQLite3::loadExtension() example
loadExtension('libagg.so');
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3::open
(PHP 5 >= 5.3.0)
SQLite3::open - Opens an SQLite database
Description
public void SQLite3::open ( string $filename [, int $flags =
SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE [, string $encryption_key ]]
)
Opens an SQLite 3 Database. If the build includes encryption, then it will
attempt to use the key.
Parameters
filename
Path to the SQLite database, or :memory: to use in-memory
database.
flags
Optional flags used to determine how to open the SQLite database.
By default, open uses SQLITE3_OPEN_READWRITE |
SQLITE3_OPEN_CREATE.
* SQLITE3_OPEN_READONLY: Open the database for reading only.
* SQLITE3_OPEN_READWRITE: Open the database for reading and
writing.
* SQLITE3_OPEN_CREATE: Create the database if it does not
exist.
encryption_key
An optional encryption key used when encrypting and decrypting an
SQLite database.
Return Values
No value is returned.
Examples
Example #1 SQLite3::open() example
open('mysqlitedb.db');
}
}
$db = new MyDB();
$db->exec('CREATE TABLE foo (bar STRING)');
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");
$result = $db->query('SELECT bar FROM foo');
var_dump($result->fetchArray());
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3::prepare
(PHP 5 >= 5.3.0)
SQLite3::prepare - Prepares an SQL statement for execution
Description
public SQLite3Stmt SQLite3::prepare ( string $query )
Prepares an SQL statement for execution and returns an SQLite3Stmt object.
Parameters
query
The SQL query to prepare.
Return Values
Returns an SQLite3Stmt object on success or FALSE on failure.
Examples
Example #1 SQLite3::prepare() example
exec('CREATE TABLE foo (id INTEGER, bar STRING)');
$db->exec("INSERT INTO foo (id, bar) VALUES (1, 'This is a test')");
$stmt = $db->prepare('SELECT bar FROM foo WHERE id=:id');
$stmt->bindValue(':id', 1, SQLITE3_INTEGER);
$result = $stmt->execute();
var_dump($result->fetchArray());
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3::query
(PHP 5 >= 5.3.0)
SQLite3::query - Executes an SQL query
Description
public SQLite3Result SQLite3::query ( string $query )
Executes an SQL query, returning an SQLite3Result object if the query
returns results.
Parameters
query
The SQL query to execute.
Return Values
Returns an SQLite3Result object if the query returns results. Otherwise,
returns TRUE if the query succeeded, FALSE on failure.
Examples
Example #1 SQLite3::query() example
query('SELECT bar FROM foo');
while ($row = $results->fetchArray()) {
var_dump($row);
}
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3::querySingle
(PHP 5 >= 5.3.0)
SQLite3::querySingle - Executes a query and returns a single result
Description
public mixed SQLite3::querySingle ( string $query [, bool $entire_row =
false ] )
Executes a query and returns a single result.
Parameters
query
The SQL query to execute.
entire_row
By default, querySingle() returns the value of the first column
returned by the query. If entire_row is TRUE, then it returns an
array of the entire first row.
Return Values
Returns the value of the first column of results or an array of the entire
first row (if entire_row is TRUE).
If the query is valid but no results are returned, then NULL will be
returned if entire_row is FALSE, otherwise an empty array is returned.
Invalid or failing queries will return FALSE.
Examples
Example #1 SQLite3::querySingle() example
querySingle('SELECT username FROM user WHERE userid=1'));
print_r($db->querySingle('SELECT username, email FROM user WHERE userid=1', true));
?>
The above example will output something similar to:
string(5) "Scott"
Array
(
[username] => Scott
[email] => scott@example.com
)
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3::version
(PHP 5 >= 5.3.0)
SQLite3::version - Returns the SQLite3 library version as a string
constant and as a number
Description
public array SQLite3::version ( void )
Returns the SQLite3 library version as a string constant and as a number.
Parameters
This function has no parameters.
Return Values
Returns an associative array with the keys "versionString" and
"versionNumber".
Examples
Example #1 SQLite3::version() example
The above example will output something similar to:
Array
(
[versionString] => 3.5.9
[versionNumber] => 3005009
)
----------------------------------------------------------------------
Table of Contents
* SQLite3::busyTimeout - Sets the busy connection handler
* SQLite3::changes - Returns the number of database rows that were
changed (or inserted or deleted) by the most recent SQL statement
* SQLite3::close - Closes the database connection
* SQLite3::__construct - Instantiates an SQLite3 object and opens an
SQLite 3 database
* SQLite3::createAggregate - Registers a PHP function for use as an SQL
aggregate function
* SQLite3::createFunction - Registers a PHP function for use as an SQL
scalar function
* SQLite3::escapeString - Returns a string that has been properly
escaped
* SQLite3::exec - Executes a result-less query against a given database
* SQLite3::lastErrorCode - Returns the numeric result code of the most
recent failed SQLite request
* SQLite3::lastErrorMsg - Returns English text describing the most
recent failed SQLite request
* SQLite3::lastInsertRowID - Returns the row ID of the most recent
INSERT into the database
* SQLite3::loadExtension - Attempts to load an SQLite extension library
* SQLite3::open - Opens an SQLite database
* SQLite3::prepare - Prepares an SQL statement for execution
* SQLite3::query - Executes an SQL query
* SQLite3::querySingle - Executes a query and returns a single result
* SQLite3::version - Returns the SQLite3 library version as a string
constant and as a number
----------------------------------------------------------------------
----------------------------------------------------------------------
The SQLite3Stmt class
Introduction
A class that handles prepared statements for the SQLite 3 extension.
Class synopsis
SQLite3Stmt {
/* Methods */
public bool bindParam ( string $sql_param , mixed &$param [, int $type ] )
public bool bindValue ( string $sql_param , mixed $value [, int $type ] )
public bool clear ( void )
public bool close ( void )
public SQLite3Result execute ( void )
public int paramCount ( void )
public bool reset ( void )
}
----------------------------------------------------------------------
SQLite3Stmt::bindParam
(PHP 5 >= 5.3.0)
SQLite3Stmt::bindParam - Binds a parameter to a statement variable
Description
public bool SQLite3Stmt::bindParam ( string $sql_param , mixed &$param [,
int $type ] )
Binds a parameter to a statement variable.
Parameters
sql_param
An string identifying the statement variable to which the
parameter should be bound.
param
The parameter to bind to a statement variable.
type
The data type of the parameter to bind.
* SQLITE3_INTEGER: The value is a signed integer, stored in 1,
2, 3, 4, 6, or 8 bytes depending on the magnitude of the
value.
* SQLITE3_FLOAT: The value is a floating point value, stored as
an 8-byte IEEE floating point number.
* SQLITE3_TEXT: The value is a text string, stored using the
database encoding (UTF-8, UTF-16BE or UTF-16-LE).
* SQLITE3_BLOB: The value is a blob of data, stored exactly as
it was input.
* SQLITE3_NULL: The value is a NULL value.
Return Values
Returns TRUE if the parameter is bound to the statement variable, FALSE on
failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3Stmt::bindValue
(PHP 5 >= 5.3.0)
SQLite3Stmt::bindValue - Binds the value of a parameter to a statement
variable
Description
public bool SQLite3Stmt::bindValue ( string $sql_param , mixed $value [,
int $type ] )
Binds the value of a parameter to a statement variable.
Parameters
sql_param
An string identifying the statement variable to which the value
should be bound.
value
The value to bind to a statement variable.
type
The data type of the value to bind.
* SQLITE3_INTEGER: The value is a signed integer, stored in 1,
2, 3, 4, 6, or 8 bytes depending on the magnitude of the
value.
* SQLITE3_FLOAT: The value is a floating point value, stored as
an 8-byte IEEE floating point number.
* SQLITE3_TEXT: The value is a text string, stored using the
database encoding (UTF-8, UTF-16BE or UTF-16-LE).
* SQLITE3_BLOB: The value is a blob of data, stored exactly as
it was input.
* SQLITE3_NULL: The value is a NULL value.
Return Values
Returns TRUE if the value is bound to the statement variable, FALSE on
failure.
Examples
Example #1 SQLite3Stmt::bindValue() example
exec('CREATE TABLE foo (id INTEGER, bar STRING)');
$db->exec("INSERT INTO foo (id, bar) VALUES (1, 'This is a test')");
$stmt = $db->prepare('SELECT bar FROM foo WHERE id=:id');
$stmt->bindValue(':id', 1, SQLITE3_INTEGER);
$result = $stmt->execute();
var_dump($result->fetchArray());
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3Stmt::clear
(PHP 5 >= 5.3.0)
SQLite3Stmt::clear - Clears all current bound parameters
Description
public bool SQLite3Stmt::clear ( void )
Clears all current bound parameters.
Parameters
This function has no parameters.
Return Values
Returns TRUE on successful clearing of bound parameters, FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3Stmt::close
(PHP 5 >= 5.3.0)
SQLite3Stmt::close - Closes the prepared statement
Description
public bool SQLite3Stmt::close ( void )
Closes the prepared statement.
Parameters
This function has no parameters.
Return Values
Returns TRUE
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3Stmt::execute
(PHP 5 >= 5.3.0)
SQLite3Stmt::execute - Executes a prepared statement and returns a result
set object
Description
public SQLite3Result SQLite3Stmt::execute ( void )
Executes a prepared statement and returns a result set object.
Parameters
This function has no parameters.
Return Values
Returns an SQLite3Result object on successful execution of the prepared
statement, FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3Stmt::paramCount
(PHP 5 >= 5.3.0)
SQLite3Stmt::paramCount - Returns the number of parameters within the
prepared statement
Description
public int SQLite3Stmt::paramCount ( void )
Returns the number of parameters within the prepared statement.
Parameters
This function has no parameters.
Return Values
Returns the number of parameters within the prepared statement.
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3Stmt::reset
(PHP 5 >= 5.3.0)
SQLite3Stmt::reset - Resets the prepared statement
Description
public bool SQLite3Stmt::reset ( void )
Resets the prepared statement to its state prior to execution. All
bindings remain intact after reset.
Parameters
This function has no parameters.
Return Values
Returns TRUE if the statement is successfully reset, FALSE on failure.
----------------------------------------------------------------------
Table of Contents
* SQLite3Stmt::bindParam - Binds a parameter to a statement variable
* SQLite3Stmt::bindValue - Binds the value of a parameter to a statement
variable
* SQLite3Stmt::clear - Clears all current bound parameters
* SQLite3Stmt::close - Closes the prepared statement
* SQLite3Stmt::execute - Executes a prepared statement and returns a
result set object
* SQLite3Stmt::paramCount - Returns the number of parameters within the
prepared statement
* SQLite3Stmt::reset - Resets the prepared statement
----------------------------------------------------------------------
----------------------------------------------------------------------
The SQLite3Result class
Introduction
A class that handles result sets for the SQLite 3 extension.
Class synopsis
SQLite3Result {
/* Methods */
public string columnName ( int $column_number )
public int columnType ( int $column_number )
public array fetchArray ([ int $mode = SQLITE3_BOTH ] )
public bool finalize ( void )
public int numColumns ( void )
public bool reset ( void )
}
----------------------------------------------------------------------
SQLite3Result::columnName
(PHP 5 >= 5.3.0)
SQLite3Result::columnName - Returns the name of the nth column
Description
public string SQLite3Result::columnName ( int $column_number )
Returns the name of the column specified by the column_number.
Parameters
column_number
The numeric zero-based index of the column.
Return Values
Returns the string name of the column identified by column_number.
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3Result::columnType
(PHP 5 >= 5.3.0)
SQLite3Result::columnType - Returns the type of the nth column
Description
public int SQLite3Result::columnType ( int $column_number )
Returns the type of the column identified by column_number.
Parameters
column_number
The numeric zero-based index of the column.
Return Values
Returns the data type index of the column identified by column_number (one
of SQLITE3_INTEGER, SQLITE3_FLOAT, SQLITE3_TEXT, SQLITE3_BLOB, or
SQLITE3_NULL).
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3Result::fetchArray
(PHP 5 >= 5.3.0)
SQLite3Result::fetchArray - Fetches a result row as an associative or
numerically indexed array or both
Description
public array SQLite3Result::fetchArray ([ int $mode = SQLITE3_BOTH ] )
Fetches a result row as an associative or numerically indexed array or
both. By default, fetches as both.
Parameters
mode
Controls how the next row will be returned to the caller. This
value must be one of either SQLITE3_ASSOC, SQLITE3_NUM, or
SQLITE3_BOTH.
* SQLITE3_ASSOC: returns an array indexed by column name as
returned in the corresponding result set
* SQLITE3_NUM: returns an array indexed by column number as
returned in the corresponding result set, starting at column
0
* SQLITE3_BOTH: returns an array indexed by both column name
and number as returned in the corresponding result set,
starting at column 0
Return Values
Returns a result row as an associatively or numerically indexed array or
both.
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3Result::finalize
(PHP 5 >= 5.3.0)
SQLite3Result::finalize - Closes the result set
Description
public bool SQLite3Result::finalize ( void )
Closes the result set.
Parameters
This function has no parameters.
Return Values
Returns TRUE.
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3Result::numColumns
(PHP 5 >= 5.3.0)
SQLite3Result::numColumns - Returns the number of columns in the result
set
Description
public int SQLite3Result::numColumns ( void )
Returns the number of columns in the result set.
Parameters
This function has no parameters.
Return Values
Returns the number of columns in the result set.
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLite3Result::reset
(PHP 5 >= 5.3.0)
SQLite3Result::reset - Resets the result set back to the first row
Description
public bool SQLite3Result::reset ( void )
Resets the result set back to the first row.
Parameters
This function has no parameters.
Return Values
Returns TRUE if the result set is successfully reset back to the first
row, FALSE on failure.
----------------------------------------------------------------------
Table of Contents
* SQLite3Result::columnName - Returns the name of the nth column
* SQLite3Result::columnType - Returns the type of the nth column
* SQLite3Result::fetchArray - Fetches a result row as an associative or
numerically indexed array or both
* SQLite3Result::finalize - Closes the result set
* SQLite3Result::numColumns - Returns the number of columns in the
result set
* SQLite3Result::reset - Resets the result set back to the first row
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* SQLite3 - The SQLite3 class
* SQLite3::busyTimeout - Sets the busy connection handler
* SQLite3::changes - Returns the number of database rows that were
changed (or inserted or deleted) by the most recent SQL statement
* SQLite3::close - Closes the database connection
* SQLite3::__construct - Instantiates an SQLite3 object and opens
an SQLite 3 database
* SQLite3::createAggregate - Registers a PHP function for use as an
SQL aggregate function
* SQLite3::createFunction - Registers a PHP function for use as an
SQL scalar function
* SQLite3::escapeString - Returns a string that has been properly
escaped
* SQLite3::exec - Executes a result-less query against a given
database
* SQLite3::lastErrorCode - Returns the numeric result code of the
most recent failed SQLite request
* SQLite3::lastErrorMsg - Returns English text describing the most
recent failed SQLite request
* SQLite3::lastInsertRowID - Returns the row ID of the most recent
INSERT into the database
* SQLite3::loadExtension - Attempts to load an SQLite extension
library
* SQLite3::open - Opens an SQLite database
* SQLite3::prepare - Prepares an SQL statement for execution
* SQLite3::query - Executes an SQL query
* SQLite3::querySingle - Executes a query and returns a single
result
* SQLite3::version - Returns the SQLite3 library version as a
string constant and as a number
* SQLite3Stmt - The SQLite3Stmt class
* SQLite3Stmt::bindParam - Binds a parameter to a statement
variable
* SQLite3Stmt::bindValue - Binds the value of a parameter to a
statement variable
* SQLite3Stmt::clear - Clears all current bound parameters
* SQLite3Stmt::close - Closes the prepared statement
* SQLite3Stmt::execute - Executes a prepared statement and returns
a result set object
* SQLite3Stmt::paramCount - Returns the number of parameters within
the prepared statement
* SQLite3Stmt::reset - Resets the prepared statement
* SQLite3Result - The SQLite3Result class
* SQLite3Result::columnName - Returns the name of the nth column
* SQLite3Result::columnType - Returns the type of the nth column
* SQLite3Result::fetchArray - Fetches a result row as an
associative or numerically indexed array or both
* SQLite3Result::finalize - Closes the result set
* SQLite3Result::numColumns - Returns the number of columns in the
result set
* SQLite3Result::reset - Resets the result set back to the first
row
----------------------------------------------------------------------
----------------------------------------------------------------------
Microsoft SQL Server Driver for PHP
----------------------------------------------------------------------
Introduction
The SQLSRV extension allows you to access Microsoft SQL Server and SQL
Azure databases when running PHP on Windows.
The SQLSRV extension is supported by Microsoft and available for download
here: >> http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
The SQLSRV extension can be used on the following operating systems:
* Windows Server 2003 Service Pack 1
* Windows XP Service Pack 3
* Windows Vista Service Pack 1 or later
* Windows Server 2008
* Windows Server 2008 R2
* Windows 7
The SQLSRV extension requires that the Microsoft SQL Server 2008 R2 Native
Client be installed on the same computer that is running PHP. If the
Microsoft SQL Server 2008 R2 is not already installed, click the
appropriate link below to download it:
* >> Download the x86 package
* >> Download the x64 package
The SQLSRV download comes with several driver files. Which driver file you
use will depend on 3 factors: the PHP version you are using, whether you
are using thread-safe or non-thread-safe PHP, and whether your PHP
installation was compiled with the VC6 or VC9 compiler. For example, if
you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP
installation was compiled with the VC9 compiler, you should use the
php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version
compiled with the VC9 compiler if you are using IIS as your web server).
If you are running PHP 5.2, you are using thread-safe PHP, and your PHP
installation was compiled with the VC6 compiler, you should use the
php_sqlsrv_52_ts_vc6.dll file.
For more information about SQLSRV requirements, see >> SQLSRV System
Requirements.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
The SQLSRV extension is enabled by adding appropriate DLL file to your PHP
extension directory and the corresponding entry to the php.ini file. The
SQLSRV download comes with several driver files. Which driver file you use
will depend on 3 factors: the PHP version you are using, whether you are
using thread-safe or non-thread-safe PHP, and whether your PHP
installation was compiled with the VC6 or VC9 compiler. For example, if
you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP
installation was compiled with the VC9 compiler, you should use the
php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version
compiled with the VC9 compiler if you are using IIS as your web server).
If you are running PHP 5.2, you are using thread-safe PHP, and your PHP
installation was compiled with the VC6 compiler, you should use the
php_sqlsrv_52_ts_vc6.dll file.
For more information about SQLSRV requirements, see >> SQLSRV System
Requirements.
The SQLSRV extension is only compatible with PHP running on Windows.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
The following table lists the configuration options available in the
SQLSRV extension. For more information about these options, see
>> Handling SQLSRV Warnings and Errors.
SQLSRV Configure Options
Name Default Changeable Changelog
sqlsrv.WarningsReturnAsErrors 1 (TRUE) PHP_INI_ALL Available since SQLSRV
1.0
sqlsrv.LogSubsystems 0 PHP_INI_ALL Available since SQLSRV
1.0
sqlsrv.LogSeverity 1 PHP_INI_ALL Available since SQLSRV
1.0
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
Connection resource
A connection resource returned by sqlsrv_connect().
Statement resource
A statement resource returned by sqlsrv_query() or by sqlsrv_prepare().
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
SQLSRV_FETCH_ASSOC (integer)
Forces sqlsrv_fetch_array() to return an associative array when
passed as a parameter.
SQLSRV_FETCH_NUMERIC (integer)
Forces sqlsrv_fetch_array() to return an array with numeric when
passed as a parameter.
SQLSRV_FETCH_BOTH (integer)
Forces sqlsrv_fetch_array() to return an array with both
associative and numeric keys when passed as a parameter (the
default behavior).
SQLSRV_ERR_ALL (integer)
Forces sqlsrv_errors() to return both errors and warings when
passed as a parameter (the default behavior).
SQLSRV_ERR_ERRORS (integer)
Forces sqlsrv_errors() to return errors only (no warnings) when
passed as a parameter.
SQLSRV_ERR_WARNINGS (integer)
Forces sqlsrv_errors() to return warnings only (no errors) when
passed as a parameter.
SQLSRV_LOG_SYSTEM_ALL (integer)
Turns on logging of all subsystems when passed to
sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_CONN (integer)
Turns on logging of connection activity when passed to
sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_INIT (integer)
Turns on logging of initialization activity when passed to
sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_OFF (integer)
Turns off logging of all subsystems when passed to
sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_STMT (integer)
Turns on logging of statement activity when passed to
sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_UTIL (integer)
Turns on logging of error function activity when passed to
sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_ALL (integer)
Specifies that errors, warnings, and notices will be logged when
passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_ERROR (integer)
Specifies that errors will be logged when passed to
sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_NOTICE (integer)
Specifies that notices will be logged when passed to
sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_WARNING (integer)
Specifies that warnings will be logged when passed to
sqlsrv_configure() as a parameter.
SQLSRV_NULLABLE_YES (integer)
Indicates that a column is nullable.
SQLSRV_NULLABLE_NO (integer)
Indicates that a column is not nullable.
SQLSRV_NULLABLE_UNKNOWN (integer)
Indicates that it is not known if a column is nullable.
SQLSRV_PARAM_IN (integer)
Indicates an input parameter when passed to sqlsrv_query() or
sqlsrv_prepare().
SQLSRV_PARAM_INOUT (integer)
Indicates a bidirectional parameter when passed to sqlsrv_query()
or sqlsrv_prepare().
SQLSRV_PARAM_OUT (integer)
Indicates an output parameter when passed to sqlsrv_query() or
sqlsrv_prepare().
SQLSRV_PHPTYPE_INT (integer)
Specifies an integer PHP data type. For usage information, see
>> How to: Specify PHP Types.
SQLSRV_PHPTYPE_DATETIME (integer)
Specifies a datetime PHP data type. For usage information, see
>> How to: Specify PHP Types.
SQLSRV_PHPTYPE_FLOAT (integer)
Specifies a float PHP data type. For usage information, see >> How
to: Specify PHP Types.
SQLSRV_PHPTYPE_STREAM (integer)
Specifies a PHP stream. This constant works like a function and
accepts an encoding constant. See the SQLSRV_ENC_* constants. For
usage information, see >> How to: Specify PHP Types.
SQLSRV_PHPTYPE_STRING (integer)
Specifies a string PHP data type. This constant works like a
function and accepts an encoding constant. See the SQLSRV_ENC_*
constants. For usage information, see >> How to: Specify PHP
Types.
SQLSRV_ENC_BINARY (integer)
Specifies that data is returned as a raw byte stream from the
server without performing encoding or translation. For usage
information, see >> How to: Specify PHP Types.
SQLSRV_ENC_CHAR (integer)
Data is returned in 8-bit characters as specified in the code page
of the Windows locale that is set on the system. Any multi-byte
characters or characters that do not map into this code page are
substituted with a single byte question mark (?) character. This
is the default encoding. For usage information, see >> How to:
Specify PHP Types.
UTF-8 (integer)
Specifies that data is returned with UTF-8 encoding. For usage
information, see >> How to: Specify PHP Types.
SQLSRV_SQLTYPE_BIGINT (integer)
Describes the bigint SQL Server data type. For usage information,
see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_BINARY (integer)
Describes the binary SQL Server data type. For usage information,
see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_BIT (integer)
Describes the bit SQL Server data type. For usage information, see
>> How to: Specify SQL Types.
SQLSRV_SQLTYPE_CHAR (integer)
Describes the char SQL Server data type. This constant works like
a function and accepts a parameter indicating the number
characters. For usage information, see >> How to: Specify SQL
Types.
SQLSRV_SQLTYPE_DATE (integer)
Describes the date SQL Server data type. For usage information,
see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_DATETIME (integer)
Describes the datetime SQL Server data type. For usage
information, see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_DATETIME2 (integer)
Describes the datetime2 SQL Server data type. For usage
information, see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_DATETIMEOFFSET (integer)
Describes the datetimeoffset SQL Server data type. For usage
information, see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_DECIMAL (integer)
Describes the decimal SQL Server data type. This constant works
like a function and accepts two parameters indicating (in order)
precision and scale. For usage information, see >> How to: Specify
SQL Types.
SQLSRV_SQLTYPE_FLOAT (integer)
Describes the float SQL Server data type. For usage information,
see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_IMAGE (integer)
Describes the image SQL Server data type. For usage information,
see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_INT (integer)
Describes the int SQL Server data type. For usage information, see
>> How to: Specify SQL Types.
SQLSRV_SQLTYPE_MONEY (integer)
Describes the money SQL Server data type. For usage information,
see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_NCHAR (integer)
Describes the nchar SQL Server data type. This constant works like
a function and accepts a single parameter indicating the character
count. For usage information, see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_NUMERIC (integer)
Describes the numeric SQL Server data type. This constant works
like a function and accepts two parameter indicating (in order)
precision and scale. For usage information, see >> How to: Specify
SQL Types.
SQLSRV_SQLTYPE_NVARCHAR (integer)
Describes the nvarchar SQL Server data type. This constant works
like a function and accepts a single parameter indicating the
character count. For usage information, see >> How to: Specify SQL
Types.
SQLSRV_SQLTYPE_NVARCHAR('max') (integer)
Describes the nvarchar(MAX) SQL Server data type. For usage
information, see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_NTEXT (integer)
Describes the ntext SQL Server data type. For usage information,
see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_REAL (integer)
Describes the real SQL Server data type. For usage information,
see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_SMALLDATETIME (integer)
Describes the smalldatetime SQL Server data type. For usage
information, see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_SMALLINT (integer)
Describes the smallint SQL Server data type. For usage
information, see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_SMALLMONEY (integer)
Describes the smallmoney SQL Server data type. For usage
information, see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_TEXT (integer)
Describes the text SQL Server data type. For usage information,
see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_TIME (integer)
Describes the time SQL Server data type. For usage information,
see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_TIMESTAMP (integer)
Describes the timestamp SQL Server data type. For usage
information, see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_TINYINT (integer)
Describes the tinyint SQL Server data type. For usage information,
see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_UNIQUEIDENTIFIER (integer)
Describes the uniqueidentifier SQL Server data type. For usage
information, see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_UDT (integer)
Describes the UDT SQL Server data type. For usage information, see
>> How to: Specify SQL Types.
SQLSRV_SQLTYPE_VARBINARY (integer)
Describes the varbinary SQL Server data type. This constant works
like a function and accepts a single parameter indicating the byte
count. For usage information, see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_VARBINARY('max') (integer)
Describes the varbinary(MAX) SQL Server data type. For usage
information, see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_VARCHAR (integer)
Describes the varchar SQL Server data type. This constant works
like a function and accepts a single parameter indicating the
character count. For usage information, see >> How to: Specify SQL
Types.
SQLSRV_SQLTYPE_VARCHAR('max') (integer)
Describes the varchar(MAX) SQL Server data type. For usage
information, see >> How to: Specify SQL Types.
SQLSRV_SQLTYPE_XML (integer)
Describes the XML SQL Server data type. For usage information, see
>> How to: Specify SQL Types.
SQLSRV_TXN_READ_UNCOMMITTED (integer)
Inidicates a transaction isolation level of READ UNCOMMITTED. This
value is used to set the TransactionIsolation level in the
$connectionOptions arrary passed to sqlsrv_connect().
SQLSRV_TXN_READ_COMMITTED (integer)
Inidicates a transaction isolation level of READ COMMITTED. This
value is used to set the TransactionIsolation level in the
$connectionOptions arrary passed to sqlsrv_connect().
SQLSRV_TXN_REPEATABLE_READ (integer)
Inidicates a transaction isolation level of REPEATABLE READ. This
value is used to set the TransactionIsolation level in the
$connectionOptions arrary passed to sqlsrv_connect().
SQLSRV_TXN_SNAPSHOT (integer)
Inidicates a transaction isolation level of SNAPSHOT. This value
is used to set the TransactionIsolation level in the
$connectionOptions arrary passed to sqlsrv_connect().
SQLSRV_TXN_READ_SERIALIZABLE (integer)
Inidicates a transaction isolation level of SERIALIZABLE. This
value is used to set the TransactionIsolation level in the
$connectionOptions arrary passed to sqlsrv_connect().
SQLSRV_CURSOR_FORWARD (integer)
Inidicates a forward-only cursor. For usage information, see
>> How to: Specify a Cursor Type.
SQLSRV_CURSOR_STATIC (integer)
Inidicates a static cursor. For usage information, see >> How to:
Specify a Cursor Type.
SQLSRV_DYNAMIC (integer)
Inidicates a dynamic cursor. For usage information, see >> How to:
Specify a Cursor Type.
SQLSRV_CURSOR_KEYSET (integer)
Inidicates a keyset cursor. For usage information, see >> How to:
Specify a Cursor Type.
SQLSRV_SCROLL_NEXT (integer)
Specifies which row to select in a result set. For usage
information, see >> How to: Specify a Cursor Type and Select Rows.
SQLSRV_SCROLL_PRIOR (integer)
Specifies which row to select in a result set. For usage
information, see >> How to: Specify a Cursor Type and Select Rows.
SQLSRV_SCROLL_FIRST (integer)
Specifies which row to select in a result set. For usage
information, see >> How to: Specify a Cursor Type and Select Rows.
SQLSRV_SCROLL_LAST (integer)
Specifies which row to select in a result set. For usage
information, see >> How to: Specify a Cursor Type and Select Rows.
SQLSRV_SCROLL_ABSOLUTE (integer)
Specifies which row to select in a result set. For usage
information, see >> How to: Specify a Cursor Type and Select Rows.
SQLSRV_SCROLL_RELATIVE (integer)
Specifies which row to select in a result set. For usage
information, see >> How to: Specify a Cursor Type and Select Rows.
----------------------------------------------------------------------
----------------------------------------------------------------------
SQLSRV Functions
----------------------------------------------------------------------
sqlsrv_begin_transaction
(No version information available, might only be in SVN)
sqlsrv_begin_transaction - Begins a database transaction
Description
bool sqlsrv_begin_transaction ( resource $conn )
The transaction begun by sqlsrv_begin_transaction() includes all
statements that were executed after the call to sqlsrv_begin_transaction()
and before calls to sqlsrv_rollback() or sqlsrv_commit(). Explicit
transactions should be started and committed or rolled back using these
functions instead of executing SQL statements that begin and committ/roll
back transactions. For more information, see >> SQLSRV Transactions.
Parameters
conn
The connection resource returned by a call to sqlsrv_connect().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 sqlsrv_begin_transaction() example
The following example demonstrates how to use sqlsrv_begin_transaction()
together with sqlsrv_commit() and sqlsrv_rollback().
"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* Initialize parameter values. */
$orderId = 1; $qty = 10; $productId = 100;
/* Set up and execute the first query. */
$sql1 = "INSERT INTO OrdersTable (ID, Quantity, ProductID)
VALUES (?, ?, ?)";
$params1 = array( $orderId, $qty, $productId );
$stmt1 = sqlsrv_query( $conn, $sql1, $params1 );
/* Set up and execute the second query. */
$sql2 = "UPDATE InventoryTable
SET Quantity = (Quantity - ?)
WHERE ProductID = ?";
$params2 = array($qty, $productId);
$stmt2 = sqlsrv_query( $conn, $sql2, $params2 );
/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
sqlsrv_commit( $conn );
echo "Transaction committed. ";
} else {
sqlsrv_rollback( $conn );
echo "Transaction rolled back. ";
}
?>
The above example will output something similar to:
See Also
* sqlsrv_commit() - Commits a transaction that was begun with
sqlsrv_begin_transaction
* sqlsrv_rollback() - Rolls back a transaction that was begun with
sqlsrv_begin_transaction
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_cancel
(No version information available, might only be in SVN)
sqlsrv_cancel - Cancels a statement
Description
bool sqlsrv_cancel ( resource $stmt )
Cancels a statement. Any results associated with the statement that have
not been consumed are deleted. After sqlsrv_cancel() has been called, the
specified statement can be re-executed if it was created with
sqlsrv_prepare(). Calling sqlsrv_cancel() is not necessary if all the
results associated with the statement have been consumed.
Parameters
stmt
The statement resource to be cancelled.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 sqlsrv_cancel() example
"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT Sales FROM Table_1";
$stmt = sqlsrv_prepare( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
if( sqlsrv_execute( $stmt ) === false) {
die( print_r( sqlsrv_errors(), true));
}
$salesTotal = 0;
$count = 0;
while( ($row = sqlsrv_fetch_array( $stmt)) && $salesTotal <=100000)
{
$qty = $row[0];
$price = $row[1];
$salesTotal += ( $price * $qty);
$count++;
}
echo "$count sales accounted for the first $$salesTotal in revenue. ";
// Cancel the pending results. The statement can be reused.
sqlsrv_cancel( $stmt);
?>
Notes
The main difference between sqlsrv_cancel() and sqlsrv_free_stmt() is that
a statement resource cancelled with sqlsrv_cancel() can be re-executed if
it was created with sqlsrv_prepare(). A statement resource cancelled with
sqlsrv_free_statement() cannot be re-executed.
See Also
* sqlsrv_free_stmt() - Frees all resources for the specified statement
* sqlsrv_prepare() - Prepares a query for execution
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_client_info
(No version information available, might only be in SVN)
sqlsrv_client_info - Returns information about the client and specified
connection
Description
array sqlsrv_client_info ( resource $conn )
Returns information about the client and specified connection
Parameters
conn
The connection about which information is returned.
Return Values
Returns an associative array with keys described in the table below.
Returns FALSE otherwise.
Array returned by sqlsrv_client_info
Key Description
DriverDllName SQLNCLI10.DLL
DriverODBCVer ODBC version (xx.yy)
DriverVer SQL Server Native Client DLL version (10.5.xxx)
ExtensionVer php_sqlsrv.dll version (2.0.xxx.x)
Examples
Example #1 sqlsrv_client_info() example
"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connOptions );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
if( $client_info = sqlsrv_client_info( $conn)) {
foreach( $client_info as $key => $value) {
echo $key.": ".$value." ";
}
} else {
echo "Error in retrieving client info. ";
}
?>
See Also
* sqlsrv_server_info() - Returns information about the server
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_close
(No version information available, might only be in SVN)
sqlsrv_close - Closes an open connection and releases resourses associated
with the connection
Description
bool sqlsrv_close ( resource $conn )
Closes an open connection and releases resourses associated with the
connection.
Parameters
conn
The connection to be closed.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 sqlsrv_close() example
"username", "PWD"=>"password", "Database"=>"dbname");
$conn = sqlsrv_connect( $serverName, $connOptions );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
//-------------------------------------
// Perform database operations here.
//-------------------------------------
// Close the connection.
sqlsrv_close( $conn );
?>
See Also
* sqlsrv_connect() - Opens a connection to a Microsoft SQL Server
database
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_commit
(No version information available, might only be in SVN)
sqlsrv_commit - Commits a transaction that was begun with
sqlsrv_begin_transaction()
Description
bool sqlsrv_commit ( resource $conn )
Commits a transaction that was begun with sqlsrv_begin_transaction(). The
connection is returned to auto-commit mode after sqlsrv_commit() is
called. The transaction that is committed includes all statements that
were executed after the call to sqlsrv_begin_transaction(). Explicit
transactions should be started and committed or rolled back using these
functions instead of executing SQL statements that begin and committ/roll
back transactions. For more information, see >> SQLSRV Transactions.
Parameters
conn
The connection on which the transaction is to be committed.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 sqlsrv_commit() example
The following example demonstrates how to use sqlsrv_commit() together
with sqlsrv_begin_transaction() and sqlsrv_rollback().
"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* Initialize parameter values. */
$orderId = 1; $qty = 10; $productId = 100;
/* Set up and execute the first query. */
$sql1 = "INSERT INTO OrdersTable (ID, Quantity, ProductID)
VALUES (?, ?, ?)";
$params1 = array( $orderId, $qty, $productId );
$stmt1 = sqlsrv_query( $conn, $sql1, $params1 );
/* Set up and execute the second query. */
$sql2 = "UPDATE InventoryTable
SET Quantity = (Quantity - ?)
WHERE ProductID = ?";
$params2 = array($qty, $productId);
$stmt2 = sqlsrv_query( $conn, $sql2, $params2 );
/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
sqlsrv_commit( $conn );
echo "Transaction committed. ";
} else {
sqlsrv_rollback( $conn );
echo "Transaction rolled back. ";
}
?>
See Also
* sqlsrv_begin_transaction() - Begins a database transaction
* sqlsrv_rollback() - Rolls back a transaction that was begun with
sqlsrv_begin_transaction
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_configure
(No version information available, might only be in SVN)
sqlsrv_configure - Changes the driver error handling and logging
configurations
Description
bool sqlsrv_configure ( string $setting , mixed $value )
Changes the driver error handling and logging configurations.
Parameters
setting
The name of the setting to set. The possible values are
"WarningsReturnAsErrors", "LogSubsystems", and "LogSeverity".
value
The value of the specified setting. The following table shows
possible values:
Error and Logging Setting Options
Setting Options
WarningsReturnAsErrors 1 (TRUE) or 0 (FALSE)
SQLSRV_LOG_SYSTEM_ALL (-1)
SQLSRV_LOG_SYSTEM_CONN (2)
LogSubsystems SQLSRV_LOG_SYSTEM_INIT (1)
SQLSRV_LOG_SYSTEM_OFF (0)
SQLSRV_LOG_SYSTEM_STMT (4)
SQLSRV_LOG_SYSTEM_UTIL (8)
SQLSRV_LOG_SEVERITY_ALL (-1)
LogSeverity SQLSRV_LOG_SEVERITY_ERROR (1)
SQLSRV_LOG_SEVERITY_NOTICE (4)
SQLSRV_LOG_SEVERITY_WARNING (2)
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* >> SQLSRV Error Handling.
* >> Logging SQLSRV Activity.
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_connect
(No version information available, might only be in SVN)
sqlsrv_connect - Opens a connection to a Microsoft SQL Server database
Description
resource sqlsrv_connect ( string $serverName [, array $connectionInfo ] )
Opens a connection to a Microsoft SQL Server database. By default, the
connection is attempted using Windows Authentication. To connect using SQL
Server Authentication, include "UID" and "PWD" in the connection options
array.
Parameters
serverName
The name of the server to which a connection is established. To
connect to a specific instance, follow the server name with a
forward slash and the instance name (e.g. serverName\sqlexpress).
connectionInfo
An associative array that specifies options for connecting to the
server. If values for the UID and PWD keys are not specified, the
connection will be attempted using Windows Authentication. For a
complete list of supported keys, see >> SQLSRV Connection Options.
Return Values
A connection resource. If a connection cannot be successfully opened,
FALSE is returned.
Examples
Example #1 Connect using Windows Authentication.
"dbName");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established. ";
}else{
echo "Connection could not be established. ";
die( print_r( sqlsrv_errors(), true));
}
?>
Example #2 Connect by specifying a user name and password.
"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established. ";
}else{
echo "Connection could not be established. ";
die( print_r( sqlsrv_errors(), true));
}
?>
Example #3 Connect on a specifed port.
"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established. ";
}else{
echo "Connection could not be established. ";
die( print_r( sqlsrv_errors(), true));
}
?>
Notes
By default, the sqlsrv_connect() uses connection pooling to improve
connection performance. To turn off connection pooling (i.e. force a new
connection on each call), set the "ConnectionPooling" option in the
$connectionOptions array to 0 (or FALSE). For more information, see
>> SQLSRV Connection Pooling.
The SQLSRV extension does not have a dedicated function for changing which
database is connected to. The target database is specified in the
$connectionOptions array that is passed to sqlsrv_connect. To change the
database on an open connection, execute the following query "USE dbName"
(e.g. sqlsrv_query($conn, "USE dbName")).
See Also
* sqlsrv_close() - Closes an open connection and releases resourses
associated with the connection
* sqlsrv_errors() - Returns error and warning information about the last
SQLSRV operation performed
* sqlsrv_query() - Prepares and executes a query.
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_errors
(No version information available, might only be in SVN)
sqlsrv_errors - Returns error and warning information about the last
SQLSRV operation performed
Description
mixed sqlsrv_errors ([ int $errorsOrWarnings ] )
Returns error and warning information about the last SQLSRV operation
performed.
Parameters
errorsOrWarnings
Determines whether error information, warning information, or both
are returned. If this parameter is not supplied, both error
information and warning information are returned. The following
are the supported values for this parameter: SQLSRV_ERR_ALL,
SQLSRV_ERR_ERRORS, SQLSRV_ERR_WARNINGS.
Return Values
If errors and/or warnings occured on the last sqlsrv operation, and array
of arrays containing error information is returned. If no errors and/or
warnings occured on the last sqlsrv operation, NULL is returned. The
following table describes the structure of the returned arrays:
Array returned by sqlsrv_errors
Key Description
For errors that originate from the ODBC driver, the SQLSTATE
returned by ODBC. For errors that originate from the Microsoft
SQLSTATE Drivers for PHP for SQL Server, a SQLSTATE of IMSSP. For warnings
that originate from the Microsoft Drivers for PHP for SQL Server,
a SQLSTATE of 01SSP.
For errors that originate from SQL Server, the native SQL Server
error code. For errors that originate from the ODBC driver, the
code error code returned by ODBC. For errors that originate from the
Microsoft Drivers for PHP for SQL Server, the Microsoft Drivers
for PHP for SQL Server error code.
message A description of the error.
Examples
Example #1 functionname() example
"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
/* Set up a query to select an invalid column name. */
$sql = "SELECT BadColumnName FROM Table_1";
/* Execution of the query will fail because of the bad column name. */
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false ) {
if( ($errors = sqlsrv_errors() ) != null) {
foreach( $errors as $error ) {
echo "SQLSTATE: ".$error[ 'SQLSTATE']." ";
echo "code: ".$error[ 'code']." ";
echo "message: ".$error[ 'message']." ";
}
}
}
?>
Notes
By default, warnings generated on a call to any SQLSRV function are
treated as errors. This means that if a warning occurs on a call to a
SQLSRV function, the function returns FALSE. However, warnings that
correspond to SQLSTATE values 01000, 01001, 01003, and 01S02 are never
treated as errors. For information about changing this behavior, see
sqlsrv_configure() and the WarningsReturnAsErrors setting.
See Also
* sqlsrv_configure() - Changes the driver error handling and logging
configurations
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_execute
(No version information available, might only be in SVN)
sqlsrv_execute - Executes a statement prepared with sqlsrv_prepare()
Description
bool sqlsrv_execute ( resource $stmt )
Executes a statement prepared with sqlsrv_prepare(). This function is
ideal for executing a prepared statement multiple times with different
parameter values.
Parameters
stmt
A statement resource returned by sqlsrv_prepare().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 sqlsrv_execute() example
This example demonstrates how to prepare a statement with sqlsrv_prepare()
and re-execute it multiple times (with different parameter values) using
sqlsrv_execute().
"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "UPDATE Table_1
SET OrderQty = ?
WHERE SalesOrderID = ?";
// Initialize parameters and prepare the statement.
// Variables $qty and $id are bound to the statement, $stmt.
$qty = 0; $id = 0;
$stmt = sqlsrv_prepare( $conn, $sql, array( &$qty, &$id));
if( !$stmt ) {
die( print_r( sqlsrv_errors(), true));
}
// Set up the SalesOrderDetailID and OrderQty information.
// This array maps the order ID to order quantity in key=>value pairs.
$orders = array( 1=>10, 2=>20, 3=>30);
// Execute the statement for each order.
foreach( $orders as $id => $qty) {
// Because $id and $qty are bound to $stmt1, their updated
// values are used with each execution of the statement.
if( sqlsrv_execute( $stmt ) === false ) {
die( print_r( sqlsrv_errors(), true));
}
}
?>
Notes
When you prepare a statement that uses variables as parameters, the
variables are bound to the statement. This means that if you update the
values of the variables, the next time you execute the statement it will
run with updated parameter values. For statements that you plan to execute
only once, use sqlsrv_query().
See Also
* sqlsrv_prepare() - Prepares a query for execution
* sqlsrv_query() - Prepares and executes a query.
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_fetch_array
(No version information available, might only be in SVN)
sqlsrv_fetch_array - Returns a row as an array
Description
array sqlsrv_fetch_array ( resource $stmt [, int $fetchType [, int $row [,
int $offset ]]] )
Returns the next available row of data as an associative array, a numeric
array, or both (the default).
Parameters
stmt
A statement resource returned by sqlsrv_query or sqlsrv_execute.
fetchType
A predefined constant specifying the type of array to return.
Possible values are SQLSRV_FETCH_ASSOC, SQLSRV_FETCH_NUMERIC, and
SQLSRV_FETCH_BOTH (the default).
A fetch type of SQLSRV_FETCH_ASSOC should not be used when
consuming a result set with multiple columns of the same name.
row
Specifies the row to access in a result set that uses a scrollable
cursor. Possible values are SQLSRV_SCROLL_NEXT,
SQLSRV_SCROLL_PRIOR, SQLSRV_SCROLL_FIRST, SQLSRV_SCROLL_LAST,
SQLSRV_SCROLL_ABSOLUTE and, SQLSRV_SCROLL_RELATIVE (the default).
When this parameter is specified, the fetchType must be explicitly
defined.
Return Values
Returns an array on success, NULL if there are no more rows to return, and
FALSE if an error occurs.
Examples
Example #1 Retrieving an associative array.
"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT FirstName, LastName FROM SomeTable";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
echo $row['LastName'].", ".$row['FirstName']." ";
}
sqlsrv_free_stmt( $stmt);
?>
Example #2 Retrieving a numeric array.
"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT FirstName, LastName FROM SomeTable";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC) ) {
echo $row[0].", ".$row[1]." ";
}
sqlsrv_free_stmt( $stmt);
?>
Notes
Not specifying the fetchType or explicity using the SQLSRV_FETCH_TYPE
constant in the examples above will return an array that has both
associative and numeric keys.
If more than one column is returned with the same name, the last column
will take precedence. To avoid field name collisions, use aliases.
If a column with no name is returned, the associative key for the array
element will be an empty string ("").
See Also
* sqlsrv_connect() - Opens a connection to a Microsoft SQL Server
database
* sqlsrv_query() - Prepares and executes a query.
* sqlsrv_errors() - Returns error and warning information about the last
SQLSRV operation performed
* sqlsrv_fetch() - Makes the next row in a result set available for
reading
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_fetch_object
(No version information available, might only be in SVN)
sqlsrv_fetch_object - Retrieves the next row of data in a result set as an
object
Description
mixed sqlsrv_fetch_object ( resource $stmt [, string $className [, array
$ctorParams [, int $row [, int $offset ]]]] )
Retrieves the next row of data in a result set as an instance of the
specified class with properties that match the row field names and values
that correspond to the row field values.
Parameters
stmt
A statement resource created by sqlsrv_query() or
sqlsrv_execute().
className
The name of the class to instantiate. If no class name is
specified, stdClass is instantiated.
ctorParams
Values passed to the constructor of the specified class. If the
constructor of the specified class takes parameters, the
ctorParams array must be supplied.
row
The row to be accessed. This parameter can only be used if the
specified statement was prepared with a scrollable cursor. In that
case, this parameter can take on one of the following values:
* SQLSRV_SCROLL_NEXT
* SQLSRV_SCROLL_PRIOR
* SQLSRV_SCROLL_FIRST
* SQLSRV_SCROLL_LAST
* SQLSRV_SCROLL_ABSOLUTE
* SQLSRV_SCROLL_RELATIVE
offset
Specifies the row to be accessed if the row parameter is set to
SQLSRV_SCROLL_ABSOLUTE or SQLSRV_SCROLL_RELATIVE. Note that the
first row in a result set has index 0.
Return Values
Returns an object on success, NULL if there are no more rows to return,
and FALSE if an error occurs or if the specified class does not exist.
Examples
Example #1 sqlsrv_fetch_object() example
The following example demonstrates how to retrieve a row as a stdClass
object.
"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT fName, lName FROM Table_1";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
// Retrieve each row as an object.
// Because no class is specified, each row will be retrieved as a stdClass object.
// Property names correspond to field names.
while( $obj = sqlsrv_fetch_object( $stmt)) {
echo $obj->fName.", ".$obj->lName." ";
}
?>
Notes
If a class name is specified with the optional $className parameter and
the class has properties whose names match the result set field names, the
corresponding result set values are applied to the properties. If a result
set field name does not match a class property, a property with the result
set field name is added to the object and the result set value is applied
to the property. The following rules apply when using the $className
parameter:
* Field-property name matching is case-sensitive.
* Field-property matching occurs regardless of access modifiers.
* Class property data types are ignored when applying a field value to a
property.
* If the class does not exist, the function returns FALSE and adds an
error to the error collection.
Regardless of whether the $className parameter is supplied, if a field
with no name is returned, the field value will be ignored and a warning
will be added to the error collection.
When consuming a result set that has multiple columns with the same name,
it may be better to use sqlsrv_fetch_array() or the combination of
sqlsrv_fetch() and sqlsrv_get_field().
See Also
* sqlsrv_fetch() - Makes the next row in a result set available for
reading
* sqlsrv_fetch_array() - Returns a row as an array
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_fetch
(No version information available, might only be in SVN)
sqlsrv_fetch - Makes the next row in a result set available for reading
Description
mixed sqlsrv_fetch ( resource $stmt [, int $row [, int $offset ]] )
Makes the next row in a result set available for reading. Use
sqlsrv_get_field() to read the fields of the row.
Parameters
stmt
A statement resource created by executing sqlsrv_query() or
sqlsrv_execute().
row
The row to be accessed. This parameter can only be used if the
specified statement was prepared with a scrollable cursor. In that
case, this parameter can take on one of the following values:
* SQLSRV_SCROLL_NEXT
* SQLSRV_SCROLL_PRIOR
* SQLSRV_SCROLL_FIRST
* SQLSRV_SCROLL_LAST
* SQLSRV_SCROLL_ABSOLUTE
* SQLSRV_SCROLL_RELATIVE
offset
Specifies the row to be accessed if the row parameter is set to
SQLSRV_SCROLL_ABSOLUTE or SQLSRV_SCROLL_RELATIVE. Note that the
first row in a result set has index 0.
Return Values
Returns TRUE if the next row of a result set was successfully retrieved,
FALSE if an error occurs, and NULL if there are no more rows in the result
set.
Examples
Example #1 sqlsrv_fetch() example
The following example demonstrates how to retrieve a row with
sqlsrv_fetch() and get the row fields with sqlsrv_get_field().
"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT Name, Comment
FROM Table_1
WHERE ReviewID=1";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
// Make the first (and in this case, only) row of the result set available for reading.
if( sqlsrv_fetch( $stmt ) === false) {
die( print_r( sqlsrv_errors(), true));
}
// Get the row fields. Field indeces start at 0 and must be retrieved in order.
// Retrieving row fields by name is not supported by sqlsrv_get_field.
$name = sqlsrv_get_field( $stmt, 0);
echo "$name: ";
$comment = sqlsrv_get_field( $stmt, 1);
echo $comment;
?>
See Also
* sqlsrv_get_field() - Gets field data from the currently selected row
* sqlsrv_fetch_array() - Returns a row as an array
* sqlsrv_fetch_object() - Retrieves the next row of data in a result set
as an object
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_field_metadata
(No version information available, might only be in SVN)
sqlsrv_field_metadata - Retrieves metadata for the fields of a statement
prepared by sqlsrv_prepare() or sqlsrv_query()
Description
mixed sqlsrv_field_metadata ( resource $stmt )
Retrieves metadata for the fields of a statement prepared by
sqlsrv_prepare() or sqlsrv_query(). sqlsrv_field_metadata() can be called
on a statement before or after statement execution.
Parameters
stmt
The statment resource for which metadata is returned.
Return Values
Returns an array of arrays is returned on success. Otherwise, FALSE is
returned. Each returned array is described by the following table:
Array returned by sqlsrv_field_metadata
Key Description
Name The name of the field.
Type The numeric value for the SQL type.
The number of characters for fields of character type, the
Size number of bytes for fields of binary type, or NULL for other
types.
Precision The precision for types of variable precision, NULL for other
types.
Scale The scale for types of variable scale, NULL for other types.
Nullable An enumeration indicating whether the column is nullable, not
nullable, or if it is not known.
For more information, see >> sqlsrv_field_metadata in the Microsoft SQLSRV
documentation.
Examples
Example #1 sqlsrv_field_metadata() example
"AdventureWorks", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT * FROM Table_1";
$stmt = sqlsrv_prepare( $conn, $sql );
foreach( sqlsrv_field_metadata( $stmt ) as $fieldMetadata ) {
foreach( $fieldMetadata as $name => $value) {
echo "$name: $value ";
}
echo " ";
}
?>
See Also
* sqlsrv_client_info() - Returns information about the client and
specified connection
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_free_stmt
(No version information available, might only be in SVN)
sqlsrv_free_stmt - Frees all resources for the specified statement
Description
bool sqlsrv_free_stmt ( resource $stmt )
Frees all resources for the specified statement. The statement cannot be
used after sqlsrv_free_stmt() has been called on it. If sqlsrv_free_stmt()
is called on an in-progress statement that alters server state, statement
execution is terminated and the statement is rolled back.
Parameters
stmt
The statment for which resources are freed. Note that NULL is a
valid parameter value. This allows the function to be called
multiple times in a script.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 sqlsrv_free_stmt() example
"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$stmt = sqlsrv_query( $conn, "SELECT * FROM Table_1");
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
/*-------------------------------
Process query results here.
-------------------------------*/
/* Free the statement resources. */
sqlsrv_free_stmt( $stmt);
?>
Notes
The main difference between sqlsrv_free_stmt() and sqlsrv_cancel() is that
a statement resource cancelled with sqlsrv_cancel() can be re-executed if
it was created with sqlsrv_prepare(). A statement resource cancelled with
sqlsrv_free_statement() cannot be re-executed.
See Also
* sqlsrv_cancel() - Cancels a statement
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_get_config
(No version information available, might only be in SVN)
sqlsrv_get_config - Returns the value of the specified configuration
setting
Description
mixed sqlsrv_get_config ( string $setting )
Returns the value of the specified configuration setting.
Parameters
setting
The name of the setting for which the value is returned. For a
list of configurable settings, see sqlsrv_configure().
Return Values
Returns the value of the specified setting. If an invalid setting is
specified, FALSE is returned.
See Also
* sqlsrv_configure() - Changes the driver error handling and logging
configurations
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_get_field
(No version information available, might only be in SVN)
sqlsrv_get_field - Gets field data from the currently selected row
Description
mixed sqlsrv_get_field ( resource $stmt , int $fieldIndex [, int
$getAsType ] )
Gets field data from the currently selected row. Fields must be accessed
in order. Field indices start at 0.
Parameters
stmt
A statement resource returned by sqlsrv_query() or
sqlsrv_execute().
fieldIndex
The index of the field to be retrieved. Field indices start at 0.
Fields must be accessed in order. i.e. If you access field index
1, then field index 0 will not be available.
getAsType
The PHP data type for the returned field data. If this parameter
is not set, the field data will be returned as its default PHP
data type. For information about default PHP data types, see
>> Default PHP Data Types in the Microsoft SQLSRV documentation.
Return Values
Returns data from the specified field on success. Returns FALSE otherwise.
Examples
Example #1 sqlsrv_get_field() example
The following example demonstrates how to retrieve a row with
sqlsrv_fetch() and get the row fields with sqlsrv_get_field().
"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT Name, Comment
FROM Table_1
WHERE ReviewID=1";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
// Make the first (and in this case, only) row of the result set available for reading.
if( sqlsrv_fetch( $stmt ) === false) {
die( print_r( sqlsrv_errors(), true));
}
// Get the row fields. Field indeces start at 0 and must be retrieved in order.
// Retrieving row fields by name is not supported by sqlsrv_get_field.
$name = sqlsrv_get_field( $stmt, 0);
echo "$name: ";
$comment = sqlsrv_get_field( $stmt, 1);
echo $comment;
?>
See Also
* sqlsrv_fetch() - Makes the next row in a result set available for
reading
* sqlsrv_fetch_array() - Returns a row as an array
* sqlsrv_fetch_object() - Retrieves the next row of data in a result set
as an object
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_has_rows
(No version information available, might only be in SVN)
sqlsrv_has_rows - Indicates whether the specified statement has rows
Description
bool sqlsrv_has_rows ( resource $stmt )
Indicates whether the specified statement has rows.
Parameters
stmt
A statement resource returned by sqlsrv_query() or
sqlsrv_execute().
Return Values
Returns TRUE if the specified statement has rows and FALSE if the
statement does not have rows or if an error occured.
Examples
Example #1 sqlsrv_has_rows() example
"dbName", "UID"=>"username", "PWD"=>"password" )
$conn = sqlsrv_connect( $server, $connectionInfo );
$stmt = sqlsrv_query( $conn, "SELECT * FROM Table_1");
if ($stmt) {
$rows = sqlsrv_has_rows( $stmt );
if ($rows === true)
echo "There are rows. ";
else
echo "There are no rows. ";
}
?>
See Also
* sqlsrv_num_rows() - Retrieves the number of rows in a result set
* sqlsrv_query() - Prepares and executes a query.
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_next_result
(No version information available, might only be in SVN)
sqlsrv_next_result - Makes the next result of the specified statement
active
Description
mixed sqlsrv_next_result ( resource $stmt )
Makes the next result of the specified statement active. Results include
result sets, row counts, and output parameters.
Parameters
stmt
The statment on which the next result is being called.
Return Values
Returns TRUE if the next result was successfully retrieved, FALSE if an
error occurred, and NULL if there are no more results to retrieve.
Examples
Example #1 sqlsrv_next_result() example
The following example executes a batch query that inserts into a table and
then selects from the table. This produces two results on the statement:
one for the rows affected by the INSERT and one for the rows returned by
the SELECT. To get to the rows returned by the SELECT,
sqlsrv_next_result() must be called to move past the first result.
"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$query = "INSERT INTO Table_1 (id, data) VALUES (?,?); SELECT * FROM TABLE_1;";
$params = array(1, "some data");
$stmt = sqlsrv_query($conn, $query, $params);
// Consume the first result (rows affected by INSERT) without calling sqlsrv_next_result.
echo "Rows affected: ".sqlsrv_rows_affected($stmt)." ";
// Move to the next result and display results.
$next_result = sqlsrv_next_result($stmt);
if( $next_result ) {
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
echo $row['id'].": ".$row['data']." ";
}
} elseif( is_null($next_result)) {
echo "No more results. ";
} else {
die(print_r(sqlsrv_errors(), true));
}
?>
See Also
* sqlsrv_query() - Prepares and executes a query.
* sqlsrv_fetch_array() - Returns a row as an array
* sqlsrv_rows_affected() - Returns the number of rows modified by the
last INSERT, UPDATE, or DELETE query executed
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_num_fields
(No version information available, might only be in SVN)
sqlsrv_num_fields - Retrieves the number of fields (columns) on a
statement
Description
mixed sqlsrv_num_fields ( resource $stmt )
Retrieves the number of fields (columns) on a statement.
Parameters
stmt
The statment for which the number of fields is returned.
sqlsrv_num_fields() can be called on a statement before or after
statement execution.
Return Values
Returns the number of fields on success. Returns FALSE otherwise.
Examples
Example #1 sqlsrv_num_fields() example
"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT * FROM Table_1";
$stmt = sqlsrv_query($conn, $sql);
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true));
}
$numFields = sqlsrv_num_fields( $stmt );
while( sqlsrv_fetch( $stmt )) {
// Iterate through the fields of each row.
for($i = 0; $i < $numFields; $i++) {
{
echo sqlsrv_get_field($stmt, $i)." ";
}
echo " ";
}
?>
See Also
* sqlsrv_field_metadata() - Retrieves metadata for the fields of a
statement prepared by sqlsrv_prepare or sqlsrv_query
* sqlsrv_fetch() - Makes the next row in a result set available for
reading
* sqlsrv_get_field() - Gets field data from the currently selected row
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_num_rows
(No version information available, might only be in SVN)
sqlsrv_num_rows - Retrieves the number of rows in a result set
Description
mixed sqlsrv_num_rows ( resource $stmt )
Retrieves the number of rows in a result set. This function requires that
the statment resource be created with a static or keyset cursor. For more
information, see sqlsrv_query(), sqlsrv_prepare(), or >> Specifying a
Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.
Parameters
stmt
The statement for which the row count is returned. The statment
resource must be created with a static or keyset cursor. For more
information, see sqlsrv_query(), sqlsrv_prepare(), or
>> Specifying a Cursor Type and Selecting Rows in the Microsoft
SQLSRV documentation.
Return Values
Returns the number of rows retrieved on success and FALSE if an error
occured. If a forward cursor (the default) or dynamic cursor is used,
FALSE is returned.
Examples
Example #1 sqlsrv_num_rows() example
"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $server, $connectionInfo );
$sql = "SELECT * FROM Table_1";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $sql , $params, $options );
$row_count = sqlsrv_num_rows( $stmt );
if ($row_count === false)
echo "Error in retrieveing row count.";
else
echo $row_count;
?>
See Also
* sqlsrv_has_rows() - Indicates whether the specified statement has rows
* sqlsrv_rows_affected() - Returns the number of rows modified by the
last INSERT, UPDATE, or DELETE query executed
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_prepare
(No version information available, might only be in SVN)
sqlsrv_prepare - Prepares a query for execution
Description
mixed sqlsrv_prepare ( resource $conn , string $sql [, array $params [,
array $options ]] )
Prepares a query for execution. This function is ideal for preparing a
query that will be executed multiple times with different parameter
values.
Parameters
conn
A connection resource returned by sqlsrv_connect().
sql
The string that defines the query to be prepared and executed.
params
An array specifying parameter information when executing a
parameterized query. Array elements can be any of the following:
* A literal value
* A PHP variable
* An array with this structure: array($value [, $direction [,
$phpType [, $sqlType]]])
The following table describes the elements in the array structure
above:
Array structure
Element Description
$value A literal value, a PHP variable, or a PHP
by-reference variable.
One of the following SQLSRV constants used
to indicate the parameter direction:
$direction (optional) SQLSRV_PARAM_IN, SQLSRV_PARAM_OUT,
SQLSRV_PARAM_INOUT. The default value is
SQLSRV_PARAM_IN.
$phpType (optional) A SQLSRV_PHPTYPE_* constant that specifies
PHP data type of the returned value.
$sqlType (optional) A SQLSRV_SQLTYPE_* constant that specifies
the SQL Server data type of the input value.
options
An array specifing query property options. The supported keys are
described in the following table:
Query Options
Key Values Description
Sets the query timeout in
QueryTimeout A positive integer seconds. By default, the
value. driver will wait
indefinitely for results.
Configures the driver to
send all stream data at
execution (TRUE), or to
SendStreamParamsAtExec TRUE or FALSE (the send stream data in chunks
default is TRUE) (FALSE). By default, the
value is set to TRUE. For
more information, see
sqlsrv_send_stream_data().
SQLSRV_CURSOR_FORWARD, See >> Specifying a Cursor
SQLSRV_CURSOR_STATIC, Type and Selecting Rows in
Scrollable SQLSRV_CURSOR_DYNAMIC, the Microsoft SQLSRV
or documentation.
SQLSRV_CURSOR_KEYSET
Return Values
Returns a statement resource on success and FALSE if an error occurred.
Examples
Example #1 sqlsrv_prepare() example
This example demonstrates how to prepare a statement with sqlsrv_prepare()
and re-execute it multiple times (with different parameter values) using
sqlsrv_execute().
"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "UPDATE Table_1
SET OrderQty = ?
WHERE SalesOrderID = ?";
// Initialize parameters and prepare the statement.
// Variables $qty and $id are bound to the statement, $stmt.
$qty = 0; $id = 0;
$stmt = sqlsrv_prepare( $conn, $sql, array( &$qty, &$id));
if( !$stmt ) {
die( print_r( sqlsrv_errors(), true));
}
// Set up the SalesOrderDetailID and OrderQty information.
// This array maps the order ID to order quantity in key=>value pairs.
$orders = array( 1=>10, 2=>20, 3=>30);
// Execute the statement for each order.
foreach( $orders as $id => $qty) {
// Because $id and $qty are bound to $stmt1, their updated
// values are used with each execution of the statement.
if( sqlsrv_execute( $stmt ) === false ) {
die( print_r( sqlsrv_errors(), true));
}
}
?>
Notes
When you prepare a statement that uses variables as parameters, the
variables are bound to the statement. This means that if you update the
values of the variables, the next time you execute the statement it will
run with updated parameter values. For statements that you plan to execute
only once, use sqlsrv_query().
See Also
* sqlsrv_execute() - Executes a statement prepared with sqlsrv_prepare
* sqlsrv_query() - Prepares and executes a query.
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_query
(No version information available, might only be in SVN)
sqlsrv_query - Prepares and executes a query.
Description
mixed sqlsrv_query ( resource $conn , string $sql [, array $params [,
array $options ]] )
Prepares and executes a query.
Parameters
conn
A connection resource returned by sqlsrv_connect().
sql
The string that defines the query to be prepared and executed.
params
An array specifying parameter information when executing a
parameterized query. Array elements can be any of the following:
* A literal value
* A PHP variable
* An array with this structure: array($value [, $direction [,
$phpType [, $sqlType]]])
The following table describes the elements in the array structure
above:
Array structure
Element Description
$value A literal value, a PHP variable, or a PHP
by-reference variable.
One of the following SQLSRV constants used
to indicate the parameter direction:
$direction (optional) SQLSRV_PARAM_IN, SQLSRV_PARAM_OUT,
SQLSRV_PARAM_INOUT. The default value is
SQLSRV_PARAM_IN.
$phpType (optional) A SQLSRV_PHPTYPE_* constant that specifies
PHP data type of the returned value.
$sqlType (optional) A SQLSRV_SQLTYPE_* constant that specifies
the SQL Server data type of the input value.
options
An array specifing query property options. The supported keys are
described in the following table:
Query Options
Key Values Description
Sets the query timeout in
QueryTimeout A positive integer seconds. By default, the
value. driver will wait
indefinitely for results.
Configures the driver to
send all stream data at
execution (TRUE), or to
SendStreamParamsAtExec TRUE or FALSE (the send stream data in chunks
default is TRUE) (FALSE). By default, the
value is set to TRUE. For
more information, see
sqlsrv_send_stream_data().
SQLSRV_CURSOR_FORWARD, See >> Specifying a Cursor
SQLSRV_CURSOR_STATIC, Type and Selecting Rows in
Scrollable SQLSRV_CURSOR_DYNAMIC, the Microsoft SQLSRV
or documentation.
SQLSRV_CURSOR_KEYSET
Return Values
Returns a statement resource on success and FALSE if an error occurred.
Examples
Example #1 sqlsrv_query() example
"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "INSERT INTO Table_1 (id, data) VALUES (?, ?)";
$params = array(1, "some data");
$stmt = sqlsrv_query( $conn, $sql, $params);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
?>
Notes
For statements that you plan to execute only once, use sqlsrv_query(). If
you intend to re-execute a statement with different parameter values, use
the combination of sqlsrv_prepare() and sqlsrv_execute().
See Also
* sqlsrv_prepare() - Prepares a query for execution
* sqlsrv_execute() - Executes a statement prepared with sqlsrv_prepare
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_rollback
(No version information available, might only be in SVN)
sqlsrv_rollback - Rolls back a transaction that was begun with
sqlsrv_begin_transaction()
Description
bool sqlsrv_rollback ( resource $conn )
Rolls back a transaction that was begun with sqlsrv_begin_transaction()
and returns the connection to auto-commit mode.
Parameters
conn
The connection resource returned by a call to sqlsrv_connect().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 sqlsrv_rollback() example
The following example demonstrates how to use sqlsrv_begin_transaction()
together with sqlsrv_commit() and sqlsrv_rollback().
"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* Initialize parameter values. */
$orderId = 1; $qty = 10; $productId = 100;
/* Set up and execute the first query. */
$sql1 = "INSERT INTO OrdersTable (ID, Quantity, ProductID)
VALUES (?, ?, ?)";
$params1 = array( $orderId, $qty, $productId );
$stmt1 = sqlsrv_query( $conn, $sql1, $params1 );
/* Set up and execute the second query. */
$sql2 = "UPDATE InventoryTable
SET Quantity = (Quantity - ?)
WHERE ProductID = ?";
$params2 = array($qty, $productId);
$stmt2 = sqlsrv_query( $conn, $sql2, $params2 );
/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
sqlsrv_commit( $conn );
echo "Transaction committed. ";
} else {
sqlsrv_rollback( $conn );
echo "Transaction rolled back. ";
}
?>
See Also
* sqlsrv_begin_transaction() - Begins a database transaction
* sqlsrv_commit() - Commits a transaction that was begun with
sqlsrv_begin_transaction
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_rows_affected
(No version information available, might only be in SVN)
sqlsrv_rows_affected - Returns the number of rows modified by the last
INSERT, UPDATE, or DELETE query executed
Description
mixed sqlsrv_rows_affected ( resource $stmt )
Returns the number of rows modified by the last INSERT, UPDATE, or DELETE
query executed. For information about the number of rows returned by a
SELECT query, see sqlsrv_num_rows().
Parameters
stmt
The executed statement resource for which the number of affected
rows is returned.
Return Values
Returns the number of rows affected by the last INSERT, UPDATE, or DELETE
query. If no rows were affected, 0 is returned. If the number of affected
rows cannot be determined, -1 is returned. If an error occured, FALSE is
returned.
Examples
Example #1 sqlsrv_rows_affected() example
"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "UPDATE Table_1 SET data = ? WHERE id = ?";
$params = array("updated data", 1);
$stmt = sqlsrv_query( $conn, $sql, $params);
$rows_affected = sqlsrv_rows_affected( $stmt);
if( $rows_affected === false) {
die( print_r( sqlsrv_errors(), true));
} elseif( $rows_affected == -1) {
echo "No information available. ";
} else {
echo $rows_affected." rows were updated. ";
}
?>
See Also
* sqlsrv_num_rows() - Retrieves the number of rows in a result set
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_send_stream_data
(No version information available, might only be in SVN)
sqlsrv_send_stream_data - Sends data from parameter streams to the server
Description
bool sqlsrv_send_stream_data ( resource $stmt )
Send data from parameter streams to the server. Up to 8 KB of data is sent
with each call.
Parameters
stmt
A statement resource returned by sqlsrv_query() or
sqlsrv_execute().
Return Values
Returns TRUE if there is more data to send and FALSE if there is not.
Examples
Example #1 sqlsrv_send_stream_data() example
"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "UPDATE Table_1 SET data = ( ?) WHERE id = 100";
// Open parameter data as a stream and put it in the $params array.
$data = fopen( "data://text/plain,[ Lengthy content here. ]", "r");
$params = array( &$data);
// Prepare the statement. Use the $options array to turn off the
// default behavior, which is to send all stream data at the time of query
// execution.
$options = array("SendStreamParamsAtExec"=>0);
$stmt = sqlsrv_prepare( $conn, $sql, $params, $options);
sqlsrv_execute( $stmt);
// Send up to 8K of parameter data to the server
// with each call to sqlsrv_send_stream_data.
$i = 1;
while( sqlsrv_send_stream_data( $stmt)) {
$i++;
}
echo "$i calls were made.";
?>
See Also
* sqlsrv_prepare() - Prepares a query for execution
* sqlsrv_query() - Prepares and executes a query.
----------------------------------------------------------------------
----------------------------------------------------------------------
sqlsrv_server_info
(No version information available, might only be in SVN)
sqlsrv_server_info - Returns information about the server
Description
array sqlsrv_server_info ( resource $conn )
Returns information about the server.
Parameters
conn
The connection resource that connects the client and the server.
Return Values
Returns an array as described in the following table:
Returned Array
CurrentDatabase The connected-to database.
SQLServerVersion The SQL Server version.
SQLServerName The name of the server.
Examples
Example #1 sqlsrv_server_info() example
$value) {
echo $key.": ".$value." ";
}
} else {
die( print_r( sqlsrv_errors(), true));
}
?>
See Also
* sqlsrv_client_info() - Returns information about the client and
specified connection
----------------------------------------------------------------------
Table of Contents
* sqlsrv_begin_transaction - Begins a database transaction
* sqlsrv_cancel - Cancels a statement
* sqlsrv_client_info - Returns information about the client and
specified connection
* sqlsrv_close - Closes an open connection and releases resourses
associated with the connection
* sqlsrv_commit - Commits a transaction that was begun with
sqlsrv_begin_transaction
* sqlsrv_configure - Changes the driver error handling and logging
configurations
* sqlsrv_connect - Opens a connection to a Microsoft SQL Server database
* sqlsrv_errors - Returns error and warning information about the last
SQLSRV operation performed
* sqlsrv_execute - Executes a statement prepared with sqlsrv_prepare
* sqlsrv_fetch_array - Returns a row as an array
* sqlsrv_fetch_object - Retrieves the next row of data in a result set
as an object
* sqlsrv_fetch - Makes the next row in a result set available for
reading
* sqlsrv_field_metadata - Retrieves metadata for the fields of a
statement prepared by sqlsrv_prepare or sqlsrv_query
* sqlsrv_free_stmt - Frees all resources for the specified statement
* sqlsrv_get_config - Returns the value of the specified configuration
setting
* sqlsrv_get_field - Gets field data from the currently selected row
* sqlsrv_has_rows - Indicates whether the specified statement has rows
* sqlsrv_next_result - Makes the next result of the specified statement
active
* sqlsrv_num_fields - Retrieves the number of fields (columns) on a
statement
* sqlsrv_num_rows - Retrieves the number of rows in a result set
* sqlsrv_prepare - Prepares a query for execution
* sqlsrv_query - Prepares and executes a query.
* sqlsrv_rollback - Rolls back a transaction that was begun with
sqlsrv_begin_transaction
* sqlsrv_rows_affected - Returns the number of rows modified by the last
INSERT, UPDATE, or DELETE query executed
* sqlsrv_send_stream_data - Sends data from parameter streams to the
server
* sqlsrv_server_info - Returns information about the server
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* SQLSRV Functions
* sqlsrv_begin_transaction - Begins a database transaction
* sqlsrv_cancel - Cancels a statement
* sqlsrv_client_info - Returns information about the client and
specified connection
* sqlsrv_close - Closes an open connection and releases resourses
associated with the connection
* sqlsrv_commit - Commits a transaction that was begun with
sqlsrv_begin_transaction
* sqlsrv_configure - Changes the driver error handling and logging
configurations
* sqlsrv_connect - Opens a connection to a Microsoft SQL Server
database
* sqlsrv_errors - Returns error and warning information about the
last SQLSRV operation performed
* sqlsrv_execute - Executes a statement prepared with
sqlsrv_prepare
* sqlsrv_fetch_array - Returns a row as an array
* sqlsrv_fetch_object - Retrieves the next row of data in a result
set as an object
* sqlsrv_fetch - Makes the next row in a result set available for
reading
* sqlsrv_field_metadata - Retrieves metadata for the fields of a
statement prepared by sqlsrv_prepare or sqlsrv_query
* sqlsrv_free_stmt - Frees all resources for the specified
statement
* sqlsrv_get_config - Returns the value of the specified
configuration setting
* sqlsrv_get_field - Gets field data from the currently selected
row
* sqlsrv_has_rows - Indicates whether the specified statement has
rows
* sqlsrv_next_result - Makes the next result of the specified
statement active
* sqlsrv_num_fields - Retrieves the number of fields (columns) on a
statement
* sqlsrv_num_rows - Retrieves the number of rows in a result set
* sqlsrv_prepare - Prepares a query for execution
* sqlsrv_query - Prepares and executes a query.
* sqlsrv_rollback - Rolls back a transaction that was begun with
sqlsrv_begin_transaction
* sqlsrv_rows_affected - Returns the number of rows modified by the
last INSERT, UPDATE, or DELETE query executed
* sqlsrv_send_stream_data - Sends data from parameter streams to
the server
* sqlsrv_server_info - Returns information about the server
----------------------------------------------------------------------
----------------------------------------------------------------------
Sybase
----------------------------------------------------------------------
Introduction
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
To enable Sybase-DB support configure PHP --with-sybase[=DIR] . DIR is the
Sybase home directory, defaults to /home/sybase. To enable Sybase-CT
support configure PHP --with-sybase-ct[=DIR] . DIR is the Sybase home
directory, defaults to /home/sybase.
Note:
As of PHP 5.3.0, the Sybase extension has been superseded by the
sybase_ct extension and is no longer maintained. To continue using
sybase you must use the sybase_ct extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Sybase configuration options
Name Default Changeable Changelog
PHP_INI_ALL in
PHP <= 4.0.2.
sybase.allow_persistent "1" PHP_INI_ALL PHP_INI_SYSTEM
in PHP <=
4.0.3.
PHP_INI_ALL in
PHP <= 4.0.2.
sybase.max_persistent "-1" PHP_INI_ALL PHP_INI_SYSTEM
in PHP <=
4.0.3.
PHP_INI_ALL in
PHP <= 4.0.2.
sybase.max_links "-1" PHP_INI_ALL PHP_INI_SYSTEM
in PHP <=
4.0.3.
sybase.interface_file "/usr/sybase/interfaces" PHP_INI_SYSTEM
sybase.min_error_severity "10" PHP_INI_ALL
sybase.min_message_severity "10" PHP_INI_ALL
sybase.compatability_mode "0" PHP_INI_ALL
Deprecated in
PHP 5.3.0.
This
magic_quotes_sybase "0" PHP_INI_ALL deprecated
feature will
certainly be
removed in the
future.
Here's a short explanation of the configuration directives.
sybase.allow_persistent boolean
Whether to allow persistent Sybase connections.
sybase.max_persistent integer
The maximum number of persistent Sybase connections per process.
-1 means no limit.
sybase.max_links integer
The maximum number of Sybase connections per process, including
persistent connections. -1 means no limit.
sybase.min_error_severity integer
Minimum error severity to display.
sybase.min_message_severity integer
Minimum message severity to display.
magic_quotes_sybase boolean
If magic_quotes_sybase is on, a single-quote is escaped with a
single-quote instead of a backslash if magic_quotes_gpc or
magic_quotes_runtime are enabled. This setting is also respected
by addslashes() and stripslashes().
Note:
Note that when magic_quotes_sybase is ON it completely overrides
magic_quotes_gpc . In this case even when magic_quotes_gpc is
enabled neither double quotes, backslashes or NUL's will be
escaped.
Warning
This feature has been DEPRECATED as of PHP 5.3.0. Relying on this
feature is highly discouraged.
Sybase-CT configuration options
Name Default Changeable Changelog
PHP_INI_ALL in PHP <=
sybct.allow_persistent "1" PHP_INI_SYSTEM 4.0.2. Available since
PHP 4.0.2. Removed in
PHP 4.0.3.
PHP_INI_ALL in PHP <=
sybct.max_persistent "-1" PHP_INI_SYSTEM 4.0.2. Available since
PHP 4.0.2. Removed in
PHP 4.0.3.
PHP_INI_ALL in PHP <=
sybct.max_links "-1" PHP_INI_SYSTEM 4.0.2. Available since
PHP 4.0.2. Removed in
PHP 4.0.3.
Available since PHP
sybct.min_server_severity "10" PHP_INI_ALL 4.0.2. Removed in PHP
4.0.3.
Available since PHP
sybct.min_client_severity "10" PHP_INI_ALL 4.0.2. Removed in PHP
4.0.3.
Available since PHP
sybct.hostname NULL PHP_INI_ALL 4.0.2. Removed in PHP
4.0.3.
sybct.deadlock_retry_count "0" PHP_INI_ALL Available since PHP
4.3.0.
Here's a short explanation of the configuration directives.
sybct.allow_persistent boolean
Whether to allow persistent Sybase-CT connections. The default is
on.
sybct.max_persistent integer
The maximum number of persistent Sybase-CT connections per
process. The default is -1 meaning unlimited.
sybct.max_links integer
The maximum number of Sybase-CT connections per process, including
persistent connections. The default is -1 meaning unlimited.
sybct.min_server_severity integer
Server messages with severity greater than or equal to
sybct.min_server_severity will be reported as warnings. This value
can also be set from a script by calling
sybase_min_server_severity(). The default is 10 which reports
errors of information severity or greater.
sybct.min_client_severity integer
Client library messages with severity greater than or equal to
sybct.min_client_severity will be reported as warnings. This value
can also be set from a script by calling
sybase_min_client_severity(). The default is 10 which effectively
disables reporting.
sybct.login_timeout integer
The maximum time in seconds to wait for a connection attempt to
succeed before returning failure. Note that if max_execution_time
has been exceeded when a connection attempt times out, your script
will be terminated before it can take action on failure. The
default is one minute.
sybct.timeout integer
The maximum time in seconds to wait for a select_db or query
operation to succeed before returning failure. Note that if
max_execution_time has been exceeded when an operation times out,
your script will be terminated before it can take action on
failure. The default is no limit.
sybct.hostname string
The name of the host you claim to be connecting from, for display
by sp_who. The default is none.
sybct.deadlock_retry_count int
Allows you to define how often deadlocks are to be retried. The
default is 0, value -1 means "forever".
For further details and definitions of the PHP_INI_* modes, see the Where
a configuration setting may be set.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
This extension has no constants defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
Sybase Functions
----------------------------------------------------------------------
sybase_affected_rows
(PHP 4, PHP 5)
sybase_affected_rows - Gets number of affected rows in last query
Description
int sybase_affected_rows ([ resource $link_identifier ] )
sybase_affected_rows() returns the number of rows affected by the last
INSERT, UPDATE or DELETE query on the server associated with the specified
link identifier.
This command is not effective for SELECT statements, only on statements
which modify records. To retrieve the number of rows returned from a
SELECT, use sybase_num_rows().
Parameters
link_identifier
If the link identifier isn't specified, the last opened link is
assumed.
Return Values
Returns the number of affected rows, as an integer.
Examples
Example #1 Delete-Query
The above example will output:
Records deleted: 10
See Also
* sybase_num_rows() - Get number of rows in a result set
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_close
(PHP 4, PHP 5)
sybase_close - Closes a Sybase connection
Description
bool sybase_close ([ resource $link_identifier ] )
sybase_close() closes the link to a Sybase database that's associated with
the specified link link_identifier.
Note that this isn't usually necessary, as non-persistent open links are
automatically closed at the end of the script's execution.
sybase_close() will not close persistent links generated by
sybase_pconnect().
Parameters
link_identifier
If the link identifier isn't specified, the last opened link is
assumed.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* sybase_connect() - Opens a Sybase server connection
* sybase_pconnect() - Open persistent Sybase connection
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_connect
(PHP 4, PHP 5)
sybase_connect - Opens a Sybase server connection
Description
resource sybase_connect ([ string $servername [, string $username [,
string $password [, string $charset [, string $appname [, bool $new =
false ]]]]]] )
sybase_connect() establishes a connection to a Sybase server.
In case a second call is made to sybase_connect() with the same arguments,
no new link will be established, but instead, the link identifier of the
already opened link will be returned.
The link to the server will be closed as soon as the execution of the
script ends, unless it's closed earlier by explicitly calling
sybase_close().
Parameters
servername
The servername argument has to be a valid servername that is
defined in the 'interfaces' file.
username
Sybase user name
password
Password associated with username.
charset
Specifies the charset for the connection
appname
Specifies an appname for the Sybase connection. This allow you to
make separate connections in the same script to the same database.
This may come handy when you have started a transaction in your
current connection, and you need to be able to do a separate query
which cannot be performed inside this transaction.
new
Whether to open a new connection or use the existing one.
Return Values
Returns a positive Sybase link identifier on success, or FALSE on failure.
Changelog
Version Description
5.3.0 The new parameter was added.
4.2.0 The appname parameter was added.
4.0.2 The charset parameter was added.
Examples
Example #1 sybase_connect() example
See Also
* sybase_pconnect() - Open persistent Sybase connection
* sybase_close() - Closes a Sybase connection
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_data_seek
(PHP 4, PHP 5)
sybase_data_seek - Moves internal row pointer
Description
bool sybase_data_seek ( resource $result_identifier , int $row_number )
sybase_data_seek() moves the internal row pointer of the Sybase result
associated with the specified result identifier to pointer to the
specified row number. The next call to sybase_fetch_row() would return
that row.
Parameters
result_identifier
row_number
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* sybase_fetch_row() - Get a result row as an enumerated array
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_deadlock_retry_count
(PHP 4 >= 4.3.0, PHP 5)
sybase_deadlock_retry_count - Sets the deadlock retry count
Description
void sybase_deadlock_retry_count ( int $retry_count )
Using sybase_deadlock_retry_count(), the number of retries can be defined
in cases of deadlocks. By default, every deadlock is retried an infinite
number of times or until the process is killed by Sybase, the executing
script is killed (for instance, by set_time_limit()) or the query
succeeds.
Parameters
retry_count
Values for retry_count
-1 Retry forever (default)
0 Do not retry
n Retry n times
Return Values
No value is returned.
Notes
Note: This function is only available when using the CT library
interface to Sybase, and not with the DB library.
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_fetch_array
(PHP 4, PHP 5)
sybase_fetch_array - Fetch row as array
Description
array sybase_fetch_array ( resource $result )
sybase_fetch_array() is an extended version of sybase_fetch_row(). In
addition to storing the data in the numeric indices of the result array,
it also stores the data in associative indices, using the field names as
keys.
An important thing to note is that using sybase_fetch_array() is NOT
significantly slower than using sybase_fetch_row(), while it provides a
significant added value.
Parameters
result
Return Values
Returns an array that corresponds to the fetched row, or FALSE if there
are no more rows.
Note:
When selecting fields with identical names (for instance, in a join),
the associative indices will have a sequential number prepended. See the
example for details.
Examples
Example #1 Identical fieldnames
The above example would produce the following output (assuming the two
tables only have each one column called "person_id"):
array(4) {
[0]=>
int(1)
["person_id"]=>
int(1)
[1]=>
int(1)
["person_id1"]=>
int(1)
}
See Also
* sybase_fetch_row() - Get a result row as an enumerated array
* sybase_fetch_assoc() - Fetch a result row as an associative array
* sybase_fetch_object() - Fetch a row as an object
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_fetch_assoc
(PHP 4 >= 4.3.0, PHP 5)
sybase_fetch_assoc - Fetch a result row as an associative array
Description
array sybase_fetch_assoc ( resource $result )
sybase_fetch_assoc() is a version of sybase_fetch_row() that uses column
names instead of integers for indices in the result array. Columns from
different tables with the same names are returned as name, name1, name2,
..., nameN.
An important thing to note is that using sybase_fetch_assoc() is NOT
significantly slower than using sybase_fetch_row(), while it provides a
significant added value.
Parameters
result
Return Values
Returns an array that corresponds to the fetched row, or FALSE if there
are no more rows.
Notes
Note: This function is only available when using the CT library
interface to Sybase, and not with the DB library.
See Also
* sybase_fetch_row() - Get a result row as an enumerated array
* sybase_fetch_array() - Fetch row as array
* sybase_fetch_object() - Fetch a row as an object
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_fetch_field
(PHP 4, PHP 5)
sybase_fetch_field - Get field information from a result
Description
object sybase_fetch_field ( resource $result [, int $field_offset = -1 ] )
sybase_fetch_field() can be used in order to obtain information about
fields in a certain query result.
Parameters
result
field_offset
If the field offset isn't specified, the next field that wasn't
yet retrieved by sybase_fetch_field() is retrieved.
Return Values
Returns an object containing field information.
The properties of the object are:
* name - column name. if the column is a result of a function, this
property is set to computed#N, where #N is a serial number.
* column_source - the table from which the column was taken
* max_length - maximum length of the column
* numeric - 1 if the column is numeric
* type - datatype of the column
See Also
* sybase_field_seek() - Sets field offset
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_fetch_object
(PHP 4, PHP 5)
sybase_fetch_object - Fetch a row as an object
Description
object sybase_fetch_object ( resource $result [, mixed $object ] )
sybase_fetch_object() is similar to sybase_fetch_assoc(), with one
difference - an object is returned, instead of an array.
Speed-wise, the function is identical to sybase_fetch_array(), and almost
as quick as sybase_fetch_row() (the difference is insignificant).
Parameters
result
object
Use the second object to specify the type of object you want to
return. If this parameter is omitted, the object will be of type
stdClass.
Return Values
Returns an object with properties that correspond to the fetched row, or
FALSE if there are no more rows.
Changelog
Version Description
This function will no longer return numeric object members. Old
behaviour:
object(stdclass)(3) {
[0]=>
string(3) "foo"
["foo"]=>
string(3) "foo"
[1]=>
string(3) "bar"
4.3.0 ["bar"]=>
string(3) "bar"
}
New behaviour:
object(stdclass)(3) {
["foo"]=>
string(3) "foo"
["bar"]=>
string(3) "bar"
}
Examples
Example #1 sybase_fetch_object() return as Foo
See Also
* sybase_fetch_array() - Fetch row as array
* sybase_fetch_row() - Get a result row as an enumerated array
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_fetch_row
(PHP 4, PHP 5)
sybase_fetch_row - Get a result row as an enumerated array
Description
array sybase_fetch_row ( resource $result )
sybase_fetch_row() fetches one row of data from the result associated with
the specified result identifier.
Subsequent call to sybase_fetch_row() would return the next row in the
result set, or FALSE if there are no more rows.
Parameters
result
Return Values
Returns an array that corresponds to the fetched row, or FALSE if there
are no more rows. Each result column is stored in an array offset,
starting at offset 0.
Data types
PHP Sybase
string VARCHAR, TEXT, CHAR, IMAGE, BINARY, VARBINARY, DATETIME
int NUMERIC (w/o precision), DECIMAL (w/o precision), INT, BIT,
TINYINT, SMALLINT
float NUMERIC (w/ precision), DECIMAL (w/ precision), REAL, FLOAT, MONEY
NULL NULL
See Also
* sybase_fetch_array() - Fetch row as array
* sybase_fetch_assoc() - Fetch a result row as an associative array
* sybase_fetch_object() - Fetch a row as an object
* sybase_data_seek() - Moves internal row pointer
* sybase_result() - Get result data
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_field_seek
(PHP 4, PHP 5)
sybase_field_seek - Sets field offset
Description
bool sybase_field_seek ( resource $result , int $field_offset )
Seeks to the specified field offset. If the next call to
sybase_fetch_field() won't include a field offset, this field would be
returned.
Parameters
result
field_offset
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* sybase_fetch_field() - Get field information from a result
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_free_result
(PHP 4, PHP 5)
sybase_free_result - Frees result memory
Description
bool sybase_free_result ( resource $result )
sybase_free_result() only needs to be called if you are worried about
using too much memory while your script is running. All result memory will
automatically be freed when the script ends. You may call
sybase_free_result() with the result identifier as an argument and the
associated result memory will be freed.
Parameters
result
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_get_last_message
(PHP 4, PHP 5)
sybase_get_last_message - Returns the last message from the server
Description
string sybase_get_last_message ( void )
sybase_get_last_message() returns the last message reported by the server.
Return Values
Returns the message as a string.
See Also
* sybase_min_message_severity() - Sets minimum message severity
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_min_client_severity
(PHP 4, PHP 5)
sybase_min_client_severity - Sets minimum client severity
Description
void sybase_min_client_severity ( int $severity )
sybase_min_client_severity() sets the minimum client severity level.
Parameters
severity
Return Values
No value is returned.
Notes
Note: This function is only available when using the CT library
interface to Sybase, and not with the DB library.
See Also
* sybase_min_server_severity() - Sets minimum server severity
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_min_error_severity
(PHP 4, PHP 5)
sybase_min_error_severity - Sets minimum error severity
Description
void sybase_min_error_severity ( int $severity )
sybase_min_error_severity() sets the minimum error severity level.
Parameters
severity
Return Values
No value is returned.
Notes
Note: This function is only available when using the CT library
interface to Sybase, and not with the DB library.
See Also
* sybase_min_message_severity() - Sets minimum message severity
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_min_message_severity
(PHP 4, PHP 5)
sybase_min_message_severity - Sets minimum message severity
Description
void sybase_min_message_severity ( int $severity )
sybase_min_message_severity() sets the minimum message severity level.
Parameters
severity
Return Values
No value is returned.
Notes
Note: This function is only available when using the DB library
interface to Sybase, and not with the CT library.
See Also
* sybase_min_error_severity() - Sets minimum error severity
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_min_server_severity
(PHP 4, PHP 5)
sybase_min_server_severity - Sets minimum server severity
Description
void sybase_min_server_severity ( int $severity )
sybase_min_server_severity() sets the minimum server severity level.
Parameters
severity
Return Values
No value is returned.
Notes
Note: This function is only available when using the CT library
interface to Sybase, and not with the DB library.
See Also
* sybase_min_client_severity() - Sets minimum client severity
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_num_fields
(PHP 4, PHP 5)
sybase_num_fields - Gets the number of fields in a result set
Description
int sybase_num_fields ( resource $result )
sybase_num_fields() returns the number of fields in a result set.
Parameters
result
Return Values
Returns the number of fields as an integer.
See Also
* sybase_query() - Sends a Sybase query
* sybase_fetch_field() - Get field information from a result
* sybase_num_rows() - Get number of rows in a result set
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_num_rows
(PHP 4, PHP 5)
sybase_num_rows - Get number of rows in a result set
Description
int sybase_num_rows ( resource $result )
sybase_num_rows() returns the number of rows in a result set.
Parameters
result
Return Values
Returns the number of rows as an integer.
See Also
* sybase_num_fields() - Gets the number of fields in a result set
* sybase_query() - Sends a Sybase query
* sybase_fetch_row() - Get a result row as an enumerated array
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_pconnect
(PHP 4, PHP 5)
sybase_pconnect - Open persistent Sybase connection
Description
resource sybase_pconnect ([ string $servername [, string $username [,
string $password [, string $charset [, string $appname ]]]]] )
sybase_pconnect() acts very much like sybase_connect() with two major
differences.
First, when connecting, the function would first try to find a
(persistent) link that's already open with the same host, username and
password. If one is found, an identifier for it will be returned instead
of opening a new connection.
Second, the connection to the SQL server will not be closed when the
execution of the script ends. Instead, the link will remain open for
future use (sybase_close() will not close links established by
sybase_pconnect()).
This type of links is therefore called 'persistent'.
Parameters
servername
The servername argument has to be a valid servername that is
defined in the 'interfaces' file.
username
Sybase user name
password
Password associated with username.
charset
Specifies the charset for the connection
appname
Specifies an appname for the Sybase connection. This allow you to
make separate connections in the same script to the same database.
This may come handy when you have started a transaction in your
current connection, and you need to be able to do a separate query
which cannot be performed inside this transaction.
Return Values
Returns a positive Sybase persistent link identifier on success, or FALSE
on error.
Changelog
Version Description
4.2.0 The appname parameter was added.
4.0.2 The charset parameter was added.
See Also
* sybase_connect() - Opens a Sybase server connection
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_query
(PHP 4, PHP 5)
sybase_query - Sends a Sybase query
Description
mixed sybase_query ( string $query [, resource $link_identifier ] )
sybase_query() sends a query to the currently active database on the
server that's associated with the specified link identifier.
Parameters
query
link_identifier
If the link identifier isn't specified, the last opened link is
assumed. If no link is open, the function tries to establish a
link as if sybase_connect() was called, and use it.
Return Values
Returns a positive Sybase result identifier on success, FALSE on error, or
TRUE if the query was successful but didn't return any columns.
See Also
* sybase_select_db() - Selects a Sybase database
* sybase_connect() - Opens a Sybase server connection
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_result
(PHP 4, PHP 5)
sybase_result - Get result data
Description
string sybase_result ( resource $result , int $row , mixed $field )
Returns the contents of the cell at the row and offset in the specified
Sybase result set.
When working on large result sets, you should consider using one of the
functions that fetch an entire row (specified below). As these functions
return the contents of multiple cells in one function call, they're MUCH
quicker than sybase_result(). Also, note that specifying a numeric offset
for the field argument is much quicker than specifying a fieldname or
tablename.fieldname argument.
Recommended high-performance alternatives: sybase_fetch_row(),
sybase_fetch_array() and sybase_fetch_object().
Parameters
result
row
field
The field argument can be the field's offset, or the field's name,
or the field's table dot field's name (tablename.fieldname). If
the column name has been aliased ('select foo as bar from...'),
use the alias instead of the column name.
Return Values
sybase_result() returns the contents of one cell from a Sybase result set.
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_select_db
(PHP 4, PHP 5)
sybase_select_db - Selects a Sybase database
Description
bool sybase_select_db ( string $database_name [, resource $link_identifier
] )
sybase_select_db() sets the current active database on the server that's
associated with the specified link identifier.
Every subsequent call to sybase_query() will be made on the active
database.
Parameters
database_name
link_identifier
If no link identifier is specified, the last opened link is
assumed. If no link is open, the function will try to establish a
link as if sybase_connect() was called, and use it.
Return Values
Returns TRUE on success or FALSE on failure.
See Also
* sybase_connect() - Opens a Sybase server connection
* sybase_pconnect() - Open persistent Sybase connection
* sybase_query() - Sends a Sybase query
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_set_message_handler
(PHP 4 >= 4.3.0, PHP 5)
sybase_set_message_handler - Sets the handler called when a server message
is raised
Description
bool sybase_set_message_handler ( callback $handler [, resource
$link_identifier ] )
sybase_set_message_handler() sets a user function to handle messages
generated by the server. You may specify the name of a global function, or
use an array to specify an object reference and a method name.
Parameters
handler
The handler expects five arguments in the following order: message
number, severity, state, line number and description. The first
four are integers. The last is a string. If the function returns
FALSE, PHP generates an ordinary error message.
link_identifier
If the link identifier isn't specified, the last opened link is
assumed.
Return Values
Returns TRUE on success or FALSE on failure.
Changelog
Version Description
4.3.5 The link_identifier parameter was added.
Examples
Example #1 sybase_set_message_handler() callback function
Example #2 sybase_set_message_handler() callback to a class
Example #3 sybase_set_message_handler() unhandled messages
Notes
Note: This function is only available when using the CT library
interface to Sybase, and not with the DB library.
----------------------------------------------------------------------
----------------------------------------------------------------------
sybase_unbuffered_query
(PHP 4 >= 4.3.0, PHP 5)
sybase_unbuffered_query - Send a Sybase query and do not block
Description
resource sybase_unbuffered_query ( string $query , resource
$link_identifier [, bool $store_result ] )
sybase_unbuffered_query() sends a query to the currently active database
on the server that's associated with the specified link identifier. If the
link identifier isn't specified, the last opened link is assumed. If no
link is open, the function tries to establish a link as if
sybase_connect() was called, and use it.
Unlike sybase_query(), sybase_unbuffered_query() reads only the first row
of the result set. sybase_fetch_array() and similar function read more
rows as needed. sybase_data_seek() reads up to the target row. The
behavior may produce better performance for large result sets.
sybase_num_rows() will only return the correct number of rows if all
result sets have been read. To Sybase, the number of rows is not known and
is therefore computed by the client implementation.
Note:
If you don't read all of the resultsets prior to executing the next
query, PHP will raise a warning and cancel all of the pending results.
To get rid of this, use sybase_free_result() which will cancel pending
results of an unbuffered query.
Parameters
query
link_identifier
store_result
The optional store_result can be FALSE to indicate the resultsets
shouldn't be fetched into memory, thus minimizing memory usage
which is particularly interesting with very large resultsets.
Return Values
Returns a positive Sybase result identifier on success, or FALSE on error.
Examples
Example #1 sybase_unbuffered_query() example
';
if ($i++ > 40000) {
break;
}
}
sybase_free_result($q);
sybase_close($dbh);
?>
Notes
Note: This function is only available when using the CT library
interface to Sybase, and not with the DB library.
See Also
* sybase_query() - Sends a Sybase query
----------------------------------------------------------------------
Table of Contents
* sybase_affected_rows - Gets number of affected rows in last query
* sybase_close - Closes a Sybase connection
* sybase_connect - Opens a Sybase server connection
* sybase_data_seek - Moves internal row pointer
* sybase_deadlock_retry_count - Sets the deadlock retry count
* sybase_fetch_array - Fetch row as array
* sybase_fetch_assoc - Fetch a result row as an associative array
* sybase_fetch_field - Get field information from a result
* sybase_fetch_object - Fetch a row as an object
* sybase_fetch_row - Get a result row as an enumerated array
* sybase_field_seek - Sets field offset
* sybase_free_result - Frees result memory
* sybase_get_last_message - Returns the last message from the server
* sybase_min_client_severity - Sets minimum client severity
* sybase_min_error_severity - Sets minimum error severity
* sybase_min_message_severity - Sets minimum message severity
* sybase_min_server_severity - Sets minimum server severity
* sybase_num_fields - Gets the number of fields in a result set
* sybase_num_rows - Get number of rows in a result set
* sybase_pconnect - Open persistent Sybase connection
* sybase_query - Sends a Sybase query
* sybase_result - Get result data
* sybase_select_db - Selects a Sybase database
* sybase_set_message_handler - Sets the handler called when a server
message is raised
* sybase_unbuffered_query - Send a Sybase query and do not block
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Sybase Functions
* sybase_affected_rows - Gets number of affected rows in last query
* sybase_close - Closes a Sybase connection
* sybase_connect - Opens a Sybase server connection
* sybase_data_seek - Moves internal row pointer
* sybase_deadlock_retry_count - Sets the deadlock retry count
* sybase_fetch_array - Fetch row as array
* sybase_fetch_assoc - Fetch a result row as an associative array
* sybase_fetch_field - Get field information from a result
* sybase_fetch_object - Fetch a row as an object
* sybase_fetch_row - Get a result row as an enumerated array
* sybase_field_seek - Sets field offset
* sybase_free_result - Frees result memory
* sybase_get_last_message - Returns the last message from the
server
* sybase_min_client_severity - Sets minimum client severity
* sybase_min_error_severity - Sets minimum error severity
* sybase_min_message_severity - Sets minimum message severity
* sybase_min_server_severity - Sets minimum server severity
* sybase_num_fields - Gets the number of fields in a result set
* sybase_num_rows - Get number of rows in a result set
* sybase_pconnect - Open persistent Sybase connection
* sybase_query - Sends a Sybase query
* sybase_result - Get result data
* sybase_select_db - Selects a Sybase database
* sybase_set_message_handler - Sets the handler called when a
server message is raised
* sybase_unbuffered_query - Send a Sybase query and do not block
----------------------------------------------------------------------
----------------------------------------------------------------------
tokyo_tyrant
----------------------------------------------------------------------
Introduction
tokyo_tyrant extension provides a wrapper for Tokyo Tyrant client
libraries. The extension contains the normal key-value API and the table
API.
"Tokyo Tyrant is a package of network interface to the DBM called Tokyo
Cabinet. Though the DBM has high performance, you might bother in case
that multiple processes share the same database, or remote processes
access the database. Thus, Tokyo Tyrant is provided for concurrent and
remote connections to Tokyo Cabinet. It is composed of the server process
managing a database and its access library for client applications."
--Tokyo Tyrant documentation
Tokyo Tyrant is written by Mikio Hirabayashi and is licensed under GNU
Lesser General Public License.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
Before using this extension Tokyo Cabinet and Tokyo Tyrant must be
installed.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here:
>> http://pecl.php.net/package/tokyo_tyrant
Configure options
* --with-tokyo-tyrant[=DIR] DIR is the prefix to the Tokyo Tyrant
installation
* --with-tokyo-cabinet-dir[=DIR] DIR is the prefix to the Tokyo Cabinet
installation
* --disable-tokyo-tyrant-session Disable Tokyo Tyrant session handler
support
Enabling the extension
The extension can be enabled by adding extension=tokyo_tyrant.so to the
INI-configuration
Running Tokyo Tyrant for the session handler
ttserver -port 2000 -ext /path/to/expire.lua -extpc expire 30.0
'/tmp/sessions.tct#idx=ts:dec'
Note: expire.lua is included in the tokyo_tyrant extension source
distribution
Configuring session handler
* tokyo_tyrant.session_salt="randomlongstring"
* session.save_handler=tokyo_tyrant
* session.save_path="tcp://hostname1:2000,tcp://hostname2:2000"
Note: It is important to make sure that tokyo_tyrant.session_salt
matches on all servers.
How it works?
The session handler creates a session id like the following:
8b0e27a823fa4a6cf7246945b82c1d51-a5eadbbed1f2075952900628456bfd6830541629-0-5460
The parts from left to right:
* Session id - Generated session id
* Checksum - Checksum of session salt, session id, node id and primary
key
* Node id - The id of the node where the session maps to
* Primary key - The primary key of the row where the session is stored
The checksum contains SHA1 sum of the node id, primary key, session id and
the salt which is known only on the server side. This allows quick mapping
of session id to node and primary key since there is no need to do an
additional search. During session id regeneration only the parts 1 and 2
change but the mapping to the node and primary key stays constant.
In case some of the nodes fail tokyo_tyrant.allow_failover,
tokyo_tyrant.fail_threshold and tokyo_tyrant.health_check_divisor
INI-settings control the behavior during failover. If failover is allowed
the session handler will map the session to a healthy node and creates a
new empty session.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
tokyo_tyrant Configure Options
Name Default Changeable Changelog
tokyo_tyrant.default_timeout 2.0 PHP_INI_ALL
tokyo_tyrant.session_salt NULL PHP_INI_ALL
tokyo_tyrant.key_prefix NULL PHP_INI_ALL
tokyo_tyrant.allow_failover 1 PHP_INI_ALL
tokyo_tyrant.fail_threshold 5 PHP_INI_ALL
tokyo_tyrant.health_check_divisor 1000 PHP_INI_ALL
tokyo_tyrant.php_expiration 0 PHP_INI_ALL
Here's a short explanation of the configuration directives.
tokyo_tyrant.default_timeout integer
Default timeout when connecting to databases
tokyo_tyrant.session_salt string
The secret that is used to salt session id
tokyo_tyrant.key_prefix string
Prefix all keys with this string. The prefix is transparent to the
developer but helps making sure that keys won't collide if
multiple applications are using the same database.
tokyo_tyrant.allow_failover integer
Whether to allow session failover in case a server dies.
tokyo_tyrant.fail_threshold integer
How many read/write or connection failures is allowed before
server is marked as failed.
tokyo_tyrant.health_check_divisor integer
Defines the divisor for the health check probability. If there are
failed servers and the probability matches, the servers are health
checked and in case the server seems healthy, it will be added
back to the pool.
tokyo_tyrant.php_expiration integer
Whether to use built in session expiration mechanism or delegate
the expiration to a lua-script on the server-side.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
TokyoTyrant constants
----------------------------------------------------------------------
----------------------------------------------------------------------
Examples
Basic usage
Example #1 Putting and getting a key-value pair
put("key", "value");
echo $tt->get("key");
?>
The above example will output:
value
----------------------------------------------------------------------
----------------------------------------------------------------------
The TokyoTyrant class
Introduction
The main Tokyo Tyrant class
Class synopsis
TokyoTyrant {
/* Constants */
const integer RDBDEF_PORT = 1978 ;
const integer RDBQC_STREQ = 0 ;
const integer RDBQC_STRINC = 1 ;
const integer RDBQC_STRBW = 2 ;
const integer RDBQC_STREW = 3 ;
const integer RDBQC_STRAND = 4 ;
const integer RDBQC_STROR = 5 ;
const integer RDBQC_STROREQ = 6 ;
const integer RDBQC_STRRX = 7 ;
const integer RDBQC_NUMEQ = 8 ;
const integer RDBQC_NUMGT = 9 ;
const integer RDBQC_NUMGE = 10 ;
const integer RDBQC_NUMLT = 11 ;
const integer RDBQC_NUMLE = 12 ;
const integer RDBQC_NUMBT = 13 ;
const integer RDBQC_NUMOREQ = 14 ;
const integer RDBQC_NEGATE = 16777216 ;
const integer RDBQC_NOIDX = 33554432 ;
const integer RDBQO_STRASC = 0 ;
const integer RDBQO_STRDESC = 1 ;
const integer RDBQO_NUMASC = 2 ;
const integer RDBQO_NUMDESC = 3 ;
const integer RDBIT_LEXICAL = 0 ;
const integer RDBIT_DECIMAL = 1 ;
const integer RDBIT_TOKEN = 2 ;
const integer RDBIT_QGRAM = 3 ;
const integer RDBIT_OPT = 9998 ;
const integer RDBIT_VOID = 9999 ;
const integer RDBIT_KEEP = 16777216 ;
const integer RDBQCFTS_PH = 15 ;
const integer RDBQCFTS_AND = 16 ;
const integer RDBQCFTS_OR = 17 ;
const integer RDBQCFTS_EX = 18 ;
const integer RDBXO_LCKREC = 1 ;
const integer RDBXOLCK_GLB = 2 ;
const integer RDBREC_INT = 1 ;
const integer RDBREC_DBL = 2 ;
const integer RDBMS_UNION = 0 ;
const integer RDBMS_ISECT = 1 ;
const integer RDBMS_DIFF = 2 ;
const integer RDBT_RECON = 1 ;
/* Methods */
public number add ( string $key , number $increment [, int $type = 0 ] )
public TokyoTyrant connect ( string $host [, int $port =
TokyoTyrant::RDBDEF_PORT [, array $options ]] )
public TokyoTyrant connectUri ( string $uri )
__construct ([ string $host [, int $port = TokyoTyrant::RDBDEF_PORT [,
array $options ]]] )
public TokyoTyrant copy ( string $path )
public string ext ( string $name , int $options , string $key , string
$value )
public array fwmKeys ( string $prefix , int $max_recs )
public mixed get ( mixed $keys )
public TokyoTyrantIterator getIterator ( void )
public int num ( void )
public TokyoTyrant out ( mixed $keys )
public TokyoTyrant put ( mixed $keys [, string $value = NULL ] )
public TokyoTyrant putCat ( mixed $keys [, string $value ] )
public TokyoTyrant putKeep ( mixed $keys [, string $value ] )
public TokyoTyrant putNr ( mixed $keys [, string $value = NULL ] )
public mixed putShl ( string $key , string $value , int $width )
public mixed restore ( string $log_dir , int $timestamp [, bool
$check_consistency = true ] )
public mixed setMaster ( string $host , int $port , int $timestamp [, bool
$check_consistency = true ] )
public int size ( string $key )
public array stat ( void )
public mixed sync ( void )
public TokyoTyrant tune ( float $timeout [, int $options =
TokyoTyrant::RDBT_RECON ] )
public mixed vanish ( void )
}
Predefined Constants
TokyoTyrant Constants
TokyoTyrant::RDBDEF_PORT
The default port of the Tokyo Tyrant database
TokyoTyrant::RDBQC_STREQ
string is equal to
TokyoTyrant::RDBQC_STRINC
string is included in
TokyoTyrant::RDBQC_STRBW
string begins with
TokyoTyrant::RDBQC_STREW
string ends with
TokyoTyrant::RDBQC_STRAND
string includes all tokens in
TokyoTyrant::RDBQC_STROR
string includes at least one token in
TokyoTyrant::RDBQC_STROREQ
string is equal to at least one token in
TokyoTyrant::RDBQC_STRRX
string matches regular expressions of
TokyoTyrant::RDBQC_NUMEQ
number is equal to
TokyoTyrant::RDBQC_NUMGT
number is greater than
TokyoTyrant::RDBQC_NUMGE
number is greater than or equal to
TokyoTyrant::RDBQC_NUMLT
number is less than
TokyoTyrant::RDBQC_NUMLE
number is less than or equal to
TokyoTyrant::RDBQC_NUMBT
number is between two tokens of
TokyoTyrant::RDBQC_NUMOREQ
number is equal to at least one token in
TokyoTyrant::RDBQC_NEGATE
negation flag
TokyoTyrant::RDBQC_NOIDX
no index flag
TokyoTyrant::RDBQO_STRASC
string ascending
TokyoTyrant::RDBQO_STRDESC
string descending
TokyoTyrant::RDBQO_NUMASC
number ascending
TokyoTyrant::RDBQO_NUMDESC
number descending
TokyoTyrant::RDBIT_LEXICAL
lexical string
TokyoTyrant::RDBIT_DECIMAL
decimal string
TokyoTyrant::RDBIT_TOKEN
token inverted index (Tokyo Tyrant >= 1.1.29)
TokyoTyrant::RDBIT_QGRAM
QGRAM inverted index (Tokyo Tyrant >= 1.1.29)
TokyoTyrant::RDBIT_OPT
optimize
TokyoTyrant::RDBIT_VOID
void
TokyoTyrant::RDBIT_KEEP
keep existing index
TokyoTyrant::RDBQCFTS_PH
full-text search with the phrase of (Tokyo Tyrant >= 1.1.29)
TokyoTyrant::RDBQCFTS_AND
full-text search with all tokens in (Tokyo Tyrant >= 1.1.29)
TokyoTyrant::RDBQCFTS_OR
full-text search with at least one token in (Tokyo Tyrant >=
1.1.29)
TokyoTyrant::RDBQCFTS_EX
full-text search with the compound expression of (Tokyo Tyrant >=
1.1.29)
TokyoTyrant::RDBQCFTS_AND
Metasearch union between records (Tokyo Tyrant >= 1.1.33)
TokyoTyrant::RDBQCFTS_OR
Metasearch intersection between records (Tokyo Tyrant >= 1.1.33)
TokyoTyrant::RDBQCFTS_EX
Metasearch difference between records (Tokyo Tyrant >= 1.1.33)
TokyoTyrant::RDBT_RECON
Whether to reconnect on connection failure. It is recommended to
have this parameter on for persistent connections
TokyoTyrant::RDBXOLCK_REC
record locking
TokyoTyrant::RDBXOLCK_GLB
global locking
TokyoTyrant::RDBREC_INT
record type int
TokyoTyrant::RDBREC_DBL
record type float (double)
TokyoTyrant::TTE_SUCCESS
success
TokyoTyrant::TTE_INVALID
invalid operation
TokyoTyrant::TTE_NOHOST
host not found
TokyoTyrant::TTE_REFUSED
connection refused
TokyoTyrant::TTE_SEND
send error
TokyoTyrant::TTE_RECV
recv error
TokyoTyrant::TTE_KEEP
record exist
TokyoTyrant::TTE_NOREC
no record found
TokyoTyrant::TTE_MISC
miscellaneous error
----------------------------------------------------------------------
TokyoTyrant::add
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::add - Adds to a numeric key
Description
public number TokyoTyrant::add ( string $key , number $increment [, int
$type = 0 ] )
Adds to an int or double value. This increments the value by the given
amount and returns the new value. If the key does not exist a new key is
created with initial value of the increment parameter.
Parameters
key
The string key
increment
The amount to increment
type
TokyoTyrant::RDBREC_INT or TokyoTyrant::RDBREC_DBL constant. If
this parameter is omitted the type is guessed from the increment
parameters type.
Return Values
Returns the new value on success
Examples
Example #1 TokyoTyrant::add() example
add("test", 3);
/* String value is converted to double */
echo $tt->add("test", "3.5", TokyoTyrant::RDBREC_DBL);
?>
The above example will output something similar to:
6.5
See Also
* TokyoTyrant::put() - Puts values
* TokyoTyrant::putcat() - Concatenates to a record
* TokyoTyrant::putkeep() - Puts a record
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrant::connect
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::connect - Connect to a database
Description
public TokyoTyrant TokyoTyrant::connect ( string $host [, int $port =
TokyoTyrant::RDBDEF_PORT [, array $options ]] )
Connects to a remote database
Parameters
host
The hostname
port
The port. Default: 1978
options
Connection options: timeout (default: 5.0), reconnect (default:
TRUE) and persistent (default: TRUE)
Return Values
This method returns the current object and throws TokyoTyrantException on
failure.
Examples
Example #1 TokyoTyrant::connect() example
connect("localhost", TokyoTyrant::RDBDEF_PORT)->put("test", "value");
?>
See Also
* TokyoTyrant::connectUri() - Connects to a database
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrant::connectUri
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::connectUri - Connects to a database
Description
public TokyoTyrant TokyoTyrant::connectUri ( string $uri )
Connects to a database using an uri
Parameters
uri
An URI to the database. For example tcp://localhost:1979/
Return Values
This method returns the current object and throws TokyoTyrantException on
failure.
Examples
Example #1 TokyoTyrant::connectUri() example
connectUri("tcp://localhost:1978/")->put("test", "hi");
?>
See Also
* TokyoTyrant::connect() - Connect to a database
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrant::__construct
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::__construct - Construct a new TokyoTyrant object
Description
TokyoTyrant::__construct ([ string $host [, int $port =
TokyoTyrant::RDBDEF_PORT [, array $options ]]] )
Constructs a new TokyoTyrant object and optionally connects to the
database
Parameters
host
The hostname. Default: NULL
port
port number. Default: 1978
options
Connection options: timeout (default: 5.0), reconnect (default:
TRUE) and persistent (default: TRUE)
Return Values
Throws TokyoTyrantException if connection to database fails
See Also
* TokyoTyrant::connect() - Connect to a database
* TokyoTyrant::connectUri() - Connects to a database
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrant::copy
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::copy - Copies the database
Description
public TokyoTyrant TokyoTyrant::copy ( string $path )
Makes a copy of the current database
Parameters
path
Path to where to copy the database. The user running the remote
database must have a write access to the directory.
Return Values
This method returns the current object and throws TokyoTyrantException on
failure.
Examples
Example #1 TokyoTyrant::copy() example
copy("/tmp/foobar.tct");
?>
See Also
* TokyoTyrant::restore() - Restore the database
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrant::ext
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::ext - Execute a remote script
Description
public string TokyoTyrant::ext ( string $name , int $options , string $key
, string $value )
Executes a remote script extension.
Parameters
name
Name of the function to execute
options
Either TokyoTyrant::RDBXO_LCKREC for record locking and
TokyoTyrant::RDBXO_LCKGLB for global locking.
key
The key to pass to the function
value
The value to pass to the function
Return Values
Returns the result of the script function
Examples
Example #1 TokyoTyrant::ext() example
ext("somefunc", TokyoTyrant::RDBXO_LCKREC, "some_key", "some_value");
?>
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrant::fwmKeys
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::fwmKeys - Returns the forward matching keys
Description
public array TokyoTyrant::fwmKeys ( string $prefix , int $max_recs )
Returns the forward matching keys from the database
Parameters
prefix
Prefix of the keys
max_recs
Maximum records to return
Return Values
Returns an array of matching keys. The values are not returned
Examples
Example #1 TokyoTyrant::fwmKeys() example
put("key_" . $i, "value_" . $i);
}
/* Create 20 non-macthing keys */
for ($i = 0; $i < 20; $i++) {
$tt->put("something_" . $i, "data_" . $i);
}
/* Get five matching keys */
var_dump($tt->fwmKeys("key_", 5));
?>
The above example will output something similar to:
array(5) {
[0]=>
string(5) "key_5"
[1]=>
string(6) "key_14"
[2]=>
string(5) "key_6"
[3]=>
string(6) "key_15"
[4]=>
string(5) "key_7"
}
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrant::get
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::get - The get purpose
Description
public mixed TokyoTyrant::get ( mixed $keys )
This method is used to return a value or multiple values. This method
accepts a string or an array as a value.
Parameters
keys
A string key or an array of string keys
Return Values
Returns a string or an array based on the given parameters. Throws a
TokyoTyrantException on error. If string is passed null is returned if the
key is not found. In case an array is given as an parameter only existing
keys will be returned. It is not an error to pass a key that does not
exist.
Examples
Example #1 TokyoTyrant::get() example
put("key1", "value1");
$tt->put("key2", "value2");
var_dump($tt->get(array("key1", "key2")));
var_dump($tt->get("key1"));
?>
The above example will output:
array(2) {
["key1"]=>
string(6) "value1"
["key2"]=>
string(6) "value2"
}
string(6) "value1"
See Also
* TokyoTyrant::put() - Puts values
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrant::getIterator
(No version information available, might only be in SVN)
TokyoTyrant::getIterator - Get an iterator
Description
public TokyoTyrantIterator TokyoTyrant::getIterator ( void )
Gets an iterator for iterating all keys / values in the database.
Parameters
This function has no parameters.
Return Values
This method returns TokyoTyrantIterator object and throws
TokyoTyrantException on failure.
Examples
Example #1 TokyoTyrant::getIterator() example
getIterator();
foreach ($it as $k => $v) {
}
?>
See Also
* TokyoTyrantTable::getQuery() - Get a query object
* TokyoTyrantTable::getIterator() - Get an iterator
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrant::num
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::num - Number of records in the database
Description
public int TokyoTyrant::num ( void )
Returns the number of records in the database
Parameters
This function has no parameters.
Return Values
Returns number of records in the database
Examples
Example #1 TokyoTyrant::num() example
num();
?>
The above example will output something similar to:
1234
See Also
* TokyoTyrant::stat() - Get statistics
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrant::out
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::out - Removes records
Description
public TokyoTyrant TokyoTyrant::out ( mixed $keys )
Removes a record or multiple records. This method accepts a string for a
single key or an array of keys for multiple records.
Parameters
keys
A string key or an array of string keys
Return Values
This method returns the current object and throws TokyoTyrantException on
failure.
Examples
Example #1 TokyoTyrant::out() example
put("test1", "value1");
$tt->put("test2", "value2");
$tt->out(array("test1", "test2"));
?>
See Also
* TokyoTyrant::put() - Puts values
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrant::put
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::put - Puts values
Description
public TokyoTyrant TokyoTyrant::put ( mixed $keys [, string $value = NULL
] )
Puts a key-value pair into the database or multiple key-value pairs. If
keys is string then the second parameter value defines the value. The
second parameter is mandatory if keys is a string. If the key exists the
value will be replaced with new value.
Parameters
keys
A string key or an array of key-value pairs
value
The value in case a string key is used
Return Values
This method returns a reference to the current object and throws
TokyoTyrantException on failure.
Examples
Example #1 TokyoTyrant::put() example
put("key", "value");
/* Put key-value pairs, new value overwrites the old */
$tt->put(array("key1" => "value1", "key" => "value2"));
/* Get back one key */
echo $tt->get("key");
?>
The above example will output:
value2
See Also
* TokyoTyrant::putKeep() - Puts a record
* TokyoTyrant::putCat() - Concatenates to a record
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrant::putCat
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::putCat - Concatenates to a record
Description
public TokyoTyrant TokyoTyrant::putCat ( mixed $keys [, string $value ] )
Appends a value into existing key or multiple values if keys is an array.
The second parameter is mandatory if keys is a string. If the record does
not exist a new record is created.
Parameters
keys
A string key or an array of key-value pairs
value
The value in case a string key is used
Return Values
This method returns a reference to the current object and throws
TokyoTyrantException on failure.
Examples
Example #1 TokyoTyrant::putCat() example
put("key", "value");
/* Concatenate single key-value pair */
$tt->putCat("key", " has more data");
/* Echo the key */
echo $tt->get("key");
?>
The above example will output:
value has more data
See Also
* TokyoTyrant::put() - Puts values
* TokyoTyrant::putKeep() - Puts a record
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrant::putKeep
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::putKeep - Puts a record
Description
public TokyoTyrant TokyoTyrant::putKeep ( mixed $keys [, string $value ] )
Puts a key-value pair into the database or multiple key-value pairs. If
keys is string then the second parameter value defines the value. The
second parameter is mandatory if keys is a string. If the key already
exists this method throws an exception indicating that the records exists.
Parameters
keys
A string key or an array of key-value pairs
value
The string value
Return Values
This method returns a reference to the current object and throws
TokyoTyrantException on failure.
Examples
Example #1 tokyotyrant::putKeep() example
put("key", "value");
try {
$tt->putKeep("key", "new value");
} catch (TokyoTyrantException $e) {
if ($e->getCode() === TokyoTyrant::TTE_KEEP) {
echo "Existing record! Not modified\n";
} else {
echo "Error: " , $e->getMessage() , "\n";
}
}
echo $tt->get("key");
?>
The above example will output:
Existing record! Not modified
value
See Also
* TokyoTyrant::put() - Puts values
* TokyoTyrant::putCat() - Concatenates to a record
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrant::putNr
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::putNr - Puts value
Description
public TokyoTyrant TokyoTyrant::putNr ( mixed $keys [, string $value =
NULL ] )
Puts a key-value pair into the database or multiple key-value pairs. If
keys is string then the second parameter value defines the value. The
second parameter is mandatory if keys is a string. This method does not
wait for the response from the server.
Parameters
keys
A string key or an array of key-value pairs
value
The value in case a string key is used
Return Values
This method returns a reference to the current object and throws
TokyoTyrantException on failure.
Examples
Example #1 TokyoTyrant::putNr() example
putNr("key", "value");
/* Put key-value pairs */
$tt->putNr(array("key1" => "value1", "key2" => "value2"));
/* Get back one key */
echo $tt->get("key1");
?>
The above example will output:
value1
See Also
* TokyoTyrant::putNr()
* TokyoTyrant::putKeep() - Puts a record
* TokyoTyrant::putCat() - Concatenates to a record
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrant::putShl
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::putShl - Concatenates to a record
Description
public mixed TokyoTyrant::putShl ( string $key , string $value , int
$width )
Concatenate to a record and shift to left.
Parameters
key
A string key
value
The value to concatenate
width
The width of the record
Return Values
This method returns a reference to the current object and throws
TokyoTyrantException on failure.
Examples
Example #1 TokyoTyrant::putShl() example
put("key", "just a long piece of data");
/* Concatenate and shift to left */
$tt->putShl("key", " and string", 15);
/* Echo the key */
echo $tt->get("key");
?>
The above example will output:
data and string
See Also
* TokyoTyrant::put() - Puts values
* TokyoTyrant::putKeep() - Puts a record
* TokyoTyrant::putCat() - Concatenates to a record
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrant::restore
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::restore - Restore the database
Description
public mixed TokyoTyrant::restore ( string $log_dir , int $timestamp [,
bool $check_consistency = true ] )
Restore the database from the update log.
Warning
This method is not supported on 32bit platforms.
Parameters
log_dir
Directory where the log is
timestamp
Beginning timestamp with microseconds
check_consistency
Whether to check consistency: Default: TRUE
Return Values
This method returns the current object and throws TokyoTyrantException on
failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrant::setMaster
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::setMaster - Set the replication master
Description
public mixed TokyoTyrant::setMaster ( string $host , int $port , int
$timestamp [, bool $check_consistency = true ] )
Sets the replication master of the database
Warning
This method is not supported on 32bit platforms.
Parameters
host
Hostname of the replication master. If NULL the replication is
disabled.
port
Port of the replication master
timestamp
Beginning timestamp with microseconds
check_consistency
Whether to check consistency.
Return Values
This method returns the current object and throws TokyoTyrantException on
failure.
Examples
Example #1 TokyoTyrant::setMaster() example
setMaster(NULL, 0, 0);
?>
See Also
* Classname::Method()
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrant::size
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::size - Returns the size of the value
Description
public int TokyoTyrant::size ( string $key )
Returns the size of a value by key
Parameters
key
The key of which size to fetch
Return Values
Returns the size of the key or throw TokyoTyrantException on error
Examples
Example #1 TokyoTyrant::size() example
put("test_key", "12345");
echo $tt->size("test_key");
?>
The above example will output:
5
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrant::stat
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::stat - Get statistics
Description
public array TokyoTyrant::stat ( void )
Returns statistics of the remote database
Parameters
This function has no parameters.
Return Values
Returns an array of key value pairs describing the statistics
Examples
Example #1 TokyoTyrant::stat() example
stat());
?>
The above example will output something similar to:
array(19) {
["version"]=>
string(6) "1.1.28"
["libver"]=>
string(3) "311"
["protver"]=>
string(4) "0.91"
["os"]=>
string(5) "Linux"
["time"]=>
string(17) "1247358357.665630"
["pid"]=>
string(5) "14348"
["sid"]=>
string(8) "59025947"
["type"]=>
string(9) "on-memory"
["path"]=>
string(1) "*"
["rnum"]=>
string(1) "4"
["size"]=>
string(6) "262856"
["bigend"]=>
string(1) "0"
["fd"]=>
string(1) "5"
["loadavg"]=>
string(8) "0.000000"
["memsize"]=>
string(8) "77328384"
["memrss"]=>
string(7) "1183744"
["ru_real"]=>
string(13) "162776.042152"
["ru_user"]=>
string(8) "0.476029"
["ru_sys"]=>
string(8) "8.652540"
}
See Also
* Classname::Method()
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrant::sync
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::sync - Synchronize the database
Description
public mixed TokyoTyrant::sync ( void )
Synchronizes the database on to the physical device
Parameters
This function has no parameters.
Return Values
This method returns the current object and throws TokyoTyrantException on
failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrant::tune
(PECL tokyo_tyrant >= 0.2.0)
TokyoTyrant::tune - Tunes connection values
Description
public TokyoTyrant TokyoTyrant::tune ( float $timeout [, int $options =
TokyoTyrant::RDBT_RECON ] )
Tunes database connection options.
Parameters
timeout
The objects timeout value (default: 5.0)
options
Bitmask of options to tune. This can be either 0 or
TokyoTyrant::RDBT_RECON. It is recommended not to change the
second parameter.
Return Values
This method returns a reference to the current object and throws
TokyoTyrantException on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrant::vanish
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::vanish - Empties the database
Description
public mixed TokyoTyrant::vanish ( void )
Empties a remote database
Parameters
This function has no parameters.
Return Values
This method returns the current object and throws TokyoTyrantException on
failure.
Examples
Example #1 TokyoTyrant::vanish() example
vanish();
?>
See Also
* TokyoTyrant::out() - Removes records
----------------------------------------------------------------------
Table of Contents
* TokyoTyrant::add - Adds to a numeric key
* TokyoTyrant::connect - Connect to a database
* TokyoTyrant::connectUri - Connects to a database
* TokyoTyrant::__construct - Construct a new TokyoTyrant object
* TokyoTyrant::copy - Copies the database
* TokyoTyrant::ext - Execute a remote script
* TokyoTyrant::fwmKeys - Returns the forward matching keys
* TokyoTyrant::get - The get purpose
* TokyoTyrant::getIterator - Get an iterator
* TokyoTyrant::num - Number of records in the database
* TokyoTyrant::out - Removes records
* TokyoTyrant::put - Puts values
* TokyoTyrant::putCat - Concatenates to a record
* TokyoTyrant::putKeep - Puts a record
* TokyoTyrant::putNr - Puts value
* TokyoTyrant::putShl - Concatenates to a record
* TokyoTyrant::restore - Restore the database
* TokyoTyrant::setMaster - Set the replication master
* TokyoTyrant::size - Returns the size of the value
* TokyoTyrant::stat - Get statistics
* TokyoTyrant::sync - Synchronize the database
* TokyoTyrant::tune - Tunes connection values
* TokyoTyrant::vanish - Empties the database
----------------------------------------------------------------------
----------------------------------------------------------------------
The TokyoTyrantTable class
Introduction
Provides an API to the table databases. A table database can be create
using the following command: ttserver -port 1979 /tmp/tt_table.tct. In
Tokyo Tyrant the table API is a schemaless database which can store
arbitrary amount of key-value pairs under a single primary key.
Class synopsis
TokyoTyrantTable extends TokyoTyrant {
/* Methods */
public void add ( string $key , mixed $increment [, string $type ] )
public int genUid ( void )
public void get ( mixed $keys )
public TokyoTyrantIterator getIterator ( void )
public TokyoTyrantQuery getQuery ( void )
public void out ( mixed $keys )
public int put ( string $key , array $columns )
public void putCat ( string $key , array $columns )
public void putKeep ( string $key , array $columns )
public void putNr ( mixed $keys [, string $value ] )
public void putShl ( string $key , string $value , int $width )
public mixed setIndex ( string $column , int $type )
/* Inherited methods */
public number TokyoTyrant::add ( string $key , number $increment [, int
$type = 0 ] )
public TokyoTyrant TokyoTyrant::connect ( string $host [, int $port =
TokyoTyrant::RDBDEF_PORT [, array $options ]] )
public TokyoTyrant TokyoTyrant::connectUri ( string $uri )
TokyoTyrant::__construct ([ string $host [, int $port =
TokyoTyrant::RDBDEF_PORT [, array $options ]]] )
public TokyoTyrant TokyoTyrant::copy ( string $path )
public string TokyoTyrant::ext ( string $name , int $options , string $key
, string $value )
public array TokyoTyrant::fwmKeys ( string $prefix , int $max_recs )
public mixed TokyoTyrant::get ( mixed $keys )
public TokyoTyrantIterator TokyoTyrant::getIterator ( void )
public int TokyoTyrant::num ( void )
public TokyoTyrant TokyoTyrant::out ( mixed $keys )
public TokyoTyrant TokyoTyrant::put ( mixed $keys [, string $value = NULL
] )
public TokyoTyrant TokyoTyrant::putCat ( mixed $keys [, string $value ] )
public TokyoTyrant TokyoTyrant::putKeep ( mixed $keys [, string $value ] )
public TokyoTyrant TokyoTyrant::putNr ( mixed $keys [, string $value =
NULL ] )
public mixed TokyoTyrant::putShl ( string $key , string $value , int
$width )
public mixed TokyoTyrant::restore ( string $log_dir , int $timestamp [,
bool $check_consistency = true ] )
public mixed TokyoTyrant::setMaster ( string $host , int $port , int
$timestamp [, bool $check_consistency = true ] )
public int TokyoTyrant::size ( string $key )
public array TokyoTyrant::stat ( void )
public mixed TokyoTyrant::sync ( void )
public TokyoTyrant TokyoTyrant::tune ( float $timeout [, int $options =
TokyoTyrant::RDBT_RECON ] )
public mixed TokyoTyrant::vanish ( void )
}
----------------------------------------------------------------------
TokyoTyrantTable::add
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantTable::add - Adds a record
Description
public void TokyoTyrantTable::add ( string $key , mixed $increment [,
string $type ] )
This method is not supported with table databases.
Parameters
key
The string key
increment
The amount to increment
type
TokyoTyrant::RDB_RECINT or TokyoTyrant::RDB_RECDBL constant. If
this parameter is omitted the type is guessed from the increment
parameters type.
Return Values
This method throws an TokyoTyrantException if used through this class.
See Also
* TokyoTyrant::add() - Adds to a numeric key
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantTable::genUid
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantTable::genUid - Generate unique id
Description
public int TokyoTyrantTable::genUid ( void )
Generates an unique id inside the table database. In table databases rows
are referenced using a numeric primary key.
Parameters
This function has no parameters.
Return Values
Returns an unique id or throws TokyoTyrantException on error
Examples
Example #1 TokyoTyrantTable::genUid() example
genUid();
?>
The above example will output something similar to:
4
See Also
* TokyoTyrantTable::put() - Store a row
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantTable::get
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantTable::get - Get a row
Description
public void TokyoTyrantTable::get ( mixed $keys )
Gets a row from table database. keys is a single integer for the primary
key of the row or an array of integers for multiple rows.
Parameters
keys
The primary key, can be a string or an integer
Return Values
Returns the row as an array
Examples
Example #1 TokyoTyrantTable::get() example
put(null, array("column1" => "some data", "column2" => "more data"));
/* Get the row back */
var_dump($tt->get($index));
?>
The above example will output:
array(2) {
["column1"]=>
string(9) "some data"
["column2"]=>
string(9) "more data"
}
Notes
Note:
Starting from version 0.3.0 this method accepts array as parameter.
Please note that multi-get on tables is not binary-safe.
See Also
* TokyoTyrantTable::put() - Store a row
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantTable::getIterator
(No version information available, might only be in SVN)
TokyoTyrantTable::getIterator - Get an iterator
Description
public TokyoTyrantIterator TokyoTyrantTable::getIterator ( void )
Gets an iterator for iterating all keys / values in the database.
Parameters
This function has no parameters.
Return Values
This method returns TokyoTyrantIterator object and throws
TokyoTyrantException on failure.
Examples
Example #1 TokyoTyrantTable::getIterator() example
getIterator();
foreach ($it as $k => $v) {
var_dump($k, $v);
}
?>
See Also
* TokyoTyrantTable::getQuery() - Get a query object
* TokyoTyrant::getIterator() - Get an iterator
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantTable::getQuery
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantTable::getQuery - Get a query object
Description
public TokyoTyrantQuery TokyoTyrantTable::getQuery ( void )
Get a query object to execute searches on the database
Parameters
This function has no parameters.
Return Values
Returns TokyoTyrantQuery on success and throws TokyoTyrantException on
error
Examples
Example #1 TokyoTyrantTable::getQuery() example
put(null, array("column1" => "some data", "column2" => "more data"));
$table->put(null, array("something" => "value", "data" => "good data"));
/* Get query object */
$query = $table->getQuery();
/* Add condition to query */
$query->addCond('data', TokyoTyrant::RDBQC_STREQ, 'good data');
/* Get matching rows */
var_dump($query->search());
?>
The above example will output something similar to:
array(1) {
[11]=>
array(2) {
["something"]=>
string(5) "value"
["data"]=>
string(9) "good data"
}
}
See Also
* TokyoTyrantQuery::search() - Searches records
* TokyoTyrantQuery::out() - Removes records based on query
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantTable::out
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantTable::out - Remove records
Description
public void TokyoTyrantTable::out ( mixed $keys )
Removes records from a table database.
Parameters
keys
A single integer key or an array of integers
Return Values
This method returns the current object and throws TokyoTyrantException on
failure.
Examples
Example #1 TokyoTyrantTable::out() example
put(null, array("column1" => "some data", "column2" => "more data"));
/* Delete the row */
$tt->out($index);
?>
See Also
* TokyoTyrantTable::put() - Store a row
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantTable::put
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantTable::put - Store a row
Description
public int TokyoTyrantTable::put ( string $key , array $columns )
Puts a new row into the database. This method parameters are key which is
the primary key of the row, passing NULL will generate a new unique id.
value is an array containing the row contents which is usually key value
pairs.
Parameters
key
The primary key of the row
columns
The row contents
Return Values
Returns the primary key on success and throws TokyoTyrantException on
error
Examples
Example #1 TokyoTyrantTable::put() example
put(null, array("column1" => "some data", "column2" => "more data"));
/* Get the row back */
var_dump($tt->get($index));
/* Modify an existing row */
$tt->put($index, array("column1" => "other data", "column2" => "better data"));
/* Get the row back */
var_dump($tt->get($index));
?>
The above example will output:
array(2) {
["column1"]=>
string(9) "some data"
["column2"]=>
string(9) "more data"
}
array(2) {
["column1"]=>
string(10) "other data"
["column2"]=>
string(11) "better data"
}
See Also
* TokyoTyrantTable::get() - Get a row
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantTable::putCat
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantTable::putCat - Concatenates to a row
Description
public void TokyoTyrantTable::putCat ( string $key , array $columns )
This method can be used to add new columns to existing records. Existing
keys will be left unmodified but any new columns will be appended to the
row. Passing null as key will generate a new row.
Parameters
key
The primary key of the row or NULL
columns
Array of row contents
Return Values
Returns the primary key and throws TokyoTyrantException on error.
Examples
Example #1 TokyoTyrantTable::putCat() example
put(null, array("column1" => "some data", "column2" => "more data"));
/* Get the row back */
var_dump($tt->get($index));
/* Modify an existing row */
$tt->putcat($index, array("column1" => "something new", "new_column" => "other data"));
/* Get the row back */
var_dump($tt->get($index));
?>
The above example will output:
array(2) {
["column1"]=>
string(9) "some data"
["column2"]=>
string(9) "more data"
}
array(3) {
["column1"]=>
string(9) "some data"
["column2"]=>
string(9) "more data"
["new_column"]=>
string(10) "other data"
}
See Also
* TokyoTyrantTable::put() - Store a row
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantTable::putKeep
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantTable::putKeep - Put a new record
Description
public void TokyoTyrantTable::putKeep ( string $key , array $columns )
Puts a new record into the database. If the key already exists this method
throws an exception indicating that the records exists.
Parameters
key
The primary key of the row or NULL
columns
Array of the row contents
Return Values
Returns the primary key and throws TokyoTyrantException on error.
Examples
Example #1 TokyoTyrantTable::putKeep() example
put(null, array("column1" => "some data", "column2" => "more data"));
/* Get the row back */
var_dump($tt->get($index));
try {
$tt->putKeep($index, array("column1" => "something new", "new_column" => "other data"));
} catch (TokyoTyrantException $e) {
if ($e->getCode() === TokyoTyrant::TTE_KEEP) {
echo "Existing record! Not modified\n";
} else {
echo "Error: " , $e->getMessage() , "\n";
}
}
/* Get the row back */
var_dump($tt->get($index));
?>
The above example will output something similar to:
array(2) {
["column1"]=>
string(9) "some data"
["column2"]=>
string(9) "more data"
}
Existing record! Not modified
array(2) {
["column1"]=>
string(9) "some data"
["column2"]=>
string(9) "more data"
}
See Also
* TokyoTyrantTable::put() - Store a row
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantTable::putNr
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantTable::putNr - Puts value
Description
public void TokyoTyrantTable::putNr ( mixed $keys [, string $value ] )
This method is not supported on table databases. Calling this method
through TokyoTyrantTable is considered an error and an
TokyoTyrantException will be thrown.
Parameters
keys
A string key or an array of key-value pairs
value
The value in case a string key is used
Return Values
This method is not supported on table databases. Calling this method
through TokyoTyrantTable is considered an error and an
TokyoTyrantException will be thrown.
See Also
* TokyoTyrant::putNr() - Puts value
* TokyoTyrant::putKeep() - Puts a record
* TokyoTyrant::putCat() - Concatenates to a record
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantTable::putShl
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantTable::putShl - Concatenates to a record
Description
public void TokyoTyrantTable::putShl ( string $key , string $value , int
$width )
This method is not supported on table databases. Calling this method
through TokyoTyrantTable is considered an error and an
TokyoTyrantException will be thrown.
Parameters
key
A string key
value
The value to concatenate
width
The width of the record
Return Values
This method is not supported on table databases.
See Also
* TokyoTyrant::put() - Puts values
* TokyoTyrant::putKeep() - Puts a record
* TokyoTyrant::putCat() - Concatenates to a record
* TokyoTyrantTable::put() - Store a row
* TokyoTyrantTable::putKeep() - Put a new record
* TokyoTyrantTable::putCat() - Concatenates to a row
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantTable::setIndex
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantTable::setIndex - Sets index
Description
public mixed TokyoTyrantTable::setIndex ( string $column , int $type )
Sets an index on a specified column. The index type is one of the
TokyoTyrant::RDBIT_* constants. Passing TokyoTyrant::RDBIT_VOID removes
the index.
Parameters
column
The name of the column
type
The index type
Return Values
This method returns the current object and throws TokyoTyrantException on
failure.
----------------------------------------------------------------------
Table of Contents
* TokyoTyrantTable::add - Adds a record
* TokyoTyrantTable::genUid - Generate unique id
* TokyoTyrantTable::get - Get a row
* TokyoTyrantTable::getIterator - Get an iterator
* TokyoTyrantTable::getQuery - Get a query object
* TokyoTyrantTable::out - Remove records
* TokyoTyrantTable::put - Store a row
* TokyoTyrantTable::putCat - Concatenates to a row
* TokyoTyrantTable::putKeep - Put a new record
* TokyoTyrantTable::putNr - Puts value
* TokyoTyrantTable::putShl - Concatenates to a record
* TokyoTyrantTable::setIndex - Sets index
----------------------------------------------------------------------
----------------------------------------------------------------------
The TokyoTyrantQuery class
Introduction
This class is used to query the table databases
Class synopsis
TokyoTyrantQuery implements Iterator , Traversable {
/* Methods */
public mixed addCond ( string $name , int $op , string $expr )
__construct ( TokyoTyrantTable $table )
public int count ( void )
public array current ( void )
public string hint ( void )
public string key ( void )
public array metaSearch ( array $queries , int $type )
public array next ( void )
public TokyoTyrantQuery out ( void )
public bool rewind ( void )
public array search ( void )
public mixed setLimit ([ int $max [, int $skip ]] )
public mixed setOrder ( string $name , int $type )
public bool valid ( void )
}
----------------------------------------------------------------------
TokyoTyrantQuery::addCond
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantQuery::addCond - Adds a condition to the query
Description
public mixed TokyoTyrantQuery::addCond ( string $name , int $op , string
$expr )
Adds a condition to the query. Condition can be something like: get all
keys which value matches expr.
Parameters
name
Name of the column in the condition
op
The operator. One of the TokyoTyrant::RDBQC_* constants
expr
The expression
Return Values
This method returns the current object and throws TokyoTyrantException on
failure.
Examples
Example #1 TokyoTyrantQuery::addCond() example
put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "not here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));
/* Get a new query object */
$query = $tt->getQuery();
/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");
/* Dump the search results */
var_dump($query->search());
?>
The above example will output:
array(2) {
[1]=>
array(2) {
["column1"]=>
string(9) "some data"
["column2"]=>
string(14) "something here"
}
[4]=>
array(2) {
["column45"]=>
string(11) "random data"
["column2"]=>
string(25) "something along the lines"
}
}
See Also
* Classname::Method()
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantQuery::__construct
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantQuery::__construct - Construct a new query
Description
TokyoTyrantQuery::__construct ( TokyoTyrantTable $table )
Construct a new query object
Parameters
table
TokyoTyrantTable object with active database connection
Return Values
Returns a new TokyoTyrantQuery object and throws TokyoTyrantException on
error
Examples
Example #1 TokyoTyrantQuery::__construct() example
See Also
* TokyoTyrantTable::getQuery() - Get a query object
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantQuery::count
(No version information available, might only be in SVN)
TokyoTyrantQuery::count - Counts records
Description
public int TokyoTyrantQuery::count ( void )
Returns a count of how many records a query returns.
Parameters
This function has no parameters.
Return Values
Returns a count of matching rows and throws TokyoTyrantException on error
Examples
Example #1 TokyoTyrantQuery::count() example
put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "not here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));
/* Get a new query object */
$query = $tt->getQuery();
/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");
/* Count the results */
var_dump($query->count());
?>
The above example will output:
int(2)
See Also
* TokyoTyrantQuery::out() - Removes records based on query
* TokyoTyrantQuery::search() - Searches records
* TokyoTyrantQuery::metaSearch() - Retrieve records with multiple
queries
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantQuery::current
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantQuery::current - Returns the current element
Description
public array TokyoTyrantQuery::current ( void )
Returns the current element. Part of Iterator interface
Parameters
This function has no parameters.
Return Values
Returns the current row
Examples
Example #1 TokyoTyrantQuery iterator example
put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));
/* Get a new query object */
$query = $tt->getQuery();
/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");
/* Iterate the results */
foreach ($query as $key => $value) {
echo "pk: $key, columns: ", count($value) ,"\n";
}
?>
The above example will output something similar to:
pk: 1, columns: 2
pk: 4, columns: 2
See Also
* TokyoTyrantQuery::addCond() - Adds a condition to the query
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantQuery::hint
(No version information available, might only be in SVN)
TokyoTyrantQuery::hint - Get the hint string of the query
Description
public string TokyoTyrantQuery::hint ( void )
Get the hint string of the query. The hint string contains information
about an executed query and it could be compared to for example MySQL
EXPLAIN statement.
Parameters
This function has no parameters.
Return Values
This method always returns a string
Examples
Example #1 TokyoTyrantQuery::hint example
vanish();
for ($i = 0; $i < 11; $i++) {
$tt->put(null, array('a_col' => 'a' . $i, 'b_col' => 'b' . $i));
}
$query = $tt->getQuery();
$query->addCond('a_col', TokyoTyrant::RDBQC_STRBW, 'a');
$query->search();
var_dump($query->hint());
?>
The above example will output something similar to:
string(72) "
scanning the whole table
result set size: 11
leaving the natural order
"
See Also
* TokyoTyrantQuery::addCond() - Adds a condition to the query
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantQuery::key
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantQuery::key - Returns the current key
Description
public string TokyoTyrantQuery::key ( void )
Returns the current key. Part of the Iterator interface
Parameters
This function has no parameters.
Return Values
Returns the current key and throws TokyoTyrantException on error
Examples
Example #1 TokyoTyrantQuery iterator example
put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));
/* Get a new query object */
$query = $tt->getQuery();
/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");
/* Iterate the results */
foreach ($query as $key => $value) {
echo "pk: $key, columns: ", count($value) ,"\n";
}
?>
The above example will output something similar to:
pk: 1, columns: 2
pk: 4, columns: 2
See Also
* TokyoTyrantQuery::addCond() - Adds a condition to the query
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantQuery::metaSearch
(No version information available, might only be in SVN)
TokyoTyrantQuery::metaSearch - Retrieve records with multiple queries
Description
public array TokyoTyrantQuery::metaSearch ( array $queries , int $type )
Executes multiple queries on a database and returns matching records. The
current object is always the left most object in the search.
Parameters
queries
Array of TokyoTyrantQuery objects
type
One of the TokyoTyrant::RDBMS_* constants
Return Values
Returns the matching rows and throws TokyoTyrantException on error
Examples
Example #1 TokyoTyrantQuery::metaSearch() example
put('cherry', array('color' => 'red'));
$tt->put('strawberry', array('color' => 'red'));
$tt->put('apple', array('color' => 'green'));
$tt->put('lemon', array('color' => 'yellow'));
/* First query */
$query = $tt->getQuery();
$query->addCond('color', TokyoTyrant::RDBQC_STREQ, 'red')->setOrder('color', TokyoTyrant::RDBQO_STRASC);
/* Second query */
$query1 = $tt->getQuery();
$query1->addCond('color', TokyoTyrant::RDBQC_STREQ, 'yellow');
/* Get union between the queries */
var_dump($query->metaSearch(array($query1), TokyoTyrant::RDBMS_UNION));
?>
The above example will output:
array(3) {
["cherry"]=>
array(1) {
["color"]=>
string(3) "red"
}
["strawberry"]=>
array(1) {
["color"]=>
string(3) "red"
}
["lemon"]=>
array(1) {
["color"]=>
string(6) "yellow"
}
}
See Also
* TokyoTyrantQuery::search() - Searches records
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantQuery::next
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantQuery::next - Moves the iterator to next entry
Description
public array TokyoTyrantQuery::next ( void )
Returns the next result in the resultset. Part of the Iterator interface.
Parameters
This function has no parameters.
Return Values
Returns the next row and throws TokyoTyrantException on error.
Examples
Example #1 TokyoTyrantQuery iterator example
put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));
/* Get a new query object */
$query = $tt->getQuery();
/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");
/* Iterate the results */
foreach ($query as $key => $value) {
echo "pk: $key, columns: ", count($value) ,"\n";
}
?>
The above example will output something similar to:
pk: 1, columns: 2
pk: 4, columns: 2
See Also
* TokyoTyrantQuery::addCond() - Adds a condition to the query
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantQuery::out
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantQuery::out - Removes records based on query
Description
public TokyoTyrantQuery TokyoTyrantQuery::out ( void )
Removes all records that match the query. Works exactly like search but
removes the records instead of returning them.
Parameters
This function has no parameters.
Return Values
This method returns the current object and throws TokyoTyrantException on
failure.
Examples
Example #1 TokyoTyrantQuery::out() example
put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));
/* Get a new query object */
$query = $tt->getQuery();
/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");
/* Remove matching records */
$query->out();
?>
See Also
* TokyoTyrantQuery::addCond() - Adds a condition to the query
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantQuery::rewind
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantQuery::rewind - Rewinds the iterator
Description
public bool TokyoTyrantQuery::rewind ( void )
Rewind the resultset and executes the query if it has not been executed.
Part of the Iterator interface.
Parameters
This function has no parameters.
Return Values
Returns TRUE
Examples
Example #1 TokyoTyrantQuery iterator example
put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));
/* Get a new query object */
$query = $tt->getQuery();
/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");
/* Iterate the results */
foreach ($query as $key => $value) {
echo "pk: $key, columns: ", count($value) ,"\n";
}
?>
The above example will output something similar to:
pk: 1, columns: 2
pk: 4, columns: 2
See Also
* TokyoTyrantQuery::addCond() - Adds a condition to the query
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantQuery::search
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantQuery::search - Searches records
Description
public array TokyoTyrantQuery::search ( void )
Executes a search on the table database. Returns an array of arrays
containing the matching records. In the returned array the first level is
the primary key of the data and the second level is the row data.
Parameters
This function has no parameters.
Return Values
Returns the matching rows and throws TokyoTyrantException on error
Examples
Example #1 TokyoTyrantQuery::search() example
put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "not here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));
/* Get a new query object */
$query = $tt->getQuery();
/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");
/* Dump the search results */
var_dump($query->search());
?>
The above example will output:
array(2) {
[1]=>
array(2) {
["column1"]=>
string(9) "some data"
["column2"]=>
string(14) "something here"
}
[4]=>
array(2) {
["column45"]=>
string(11) "random data"
["column2"]=>
string(25) "something along the lines"
}
}
See Also
* TokyoTyrantQuery::out() - Removes records based on query
* TokyoTyrantQuery::metaSearch() - Retrieve records with multiple
queries
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantQuery::setLimit
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantQuery::setLimit - Limit results
Description
public mixed TokyoTyrantQuery::setLimit ([ int $max [, int $skip ]] )
Set the maximum amount of records to return on a query.
Parameters
max
Maximum amount of records. Default: -1
skip
How many records to skip from the start. Default: -1
Return Values
This method returns the current object and throws TokyoTyrantException on
failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantQuery::setOrder
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantQuery::setOrder - Orders results
Description
public mixed TokyoTyrantQuery::setOrder ( string $name , int $type )
Sets the order of a query
Parameters
name
The column name to apply the ordering on.
type
The type can be one of the following constants:
* TokyoTyrant::RDBQO_STRASC - String ascending
* TokyoTyrant::RDBQO_STRDESC - String descending
* TokyoTyrant::RDBQO_NUMASC - Numberic ascending
* TokyoTyrant::RDBQO_NUMDESC - String descending
Return Values
This method returns the current object.
----------------------------------------------------------------------
----------------------------------------------------------------------
TokyoTyrantQuery::valid
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantQuery::valid - Checks the validity of current item
Description
public bool TokyoTyrantQuery::valid ( void )
Checks if the current item is valid. Part of the Iterator interface
Parameters
This function has no parameters.
Return Values
Returns TRUE if the current item is valid and FALSE if not.
Examples
Example #1 TokyoTyrantQuery iterator example
put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));
/* Get a new query object */
$query = $tt->getQuery();
/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");
/* Iterate the results */
foreach ($query as $key => $value) {
echo "pk: $key, columns: ", count($value) ,"\n";
}
?>
The above example will output something similar to:
pk: 1, columns: 2
pk: 4, columns: 2
See Also
* TokyoTyrantQuery::addCond() - Adds a condition to the query
----------------------------------------------------------------------
Table of Contents
* TokyoTyrantQuery::addCond - Adds a condition to the query
* TokyoTyrantQuery::__construct - Construct a new query
* TokyoTyrantQuery::count - Counts records
* TokyoTyrantQuery::current - Returns the current element
* TokyoTyrantQuery::hint - Get the hint string of the query
* TokyoTyrantQuery::key - Returns the current key
* TokyoTyrantQuery::metaSearch - Retrieve records with multiple queries
* TokyoTyrantQuery::next - Moves the iterator to next entry
* TokyoTyrantQuery::out - Removes records based on query
* TokyoTyrantQuery::rewind - Rewinds the iterator
* TokyoTyrantQuery::search - Searches records
* TokyoTyrantQuery::setLimit - Limit results
* TokyoTyrantQuery::setOrder - Orders results
* TokyoTyrantQuery::valid - Checks the validity of current item
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Examples
* TokyoTyrant - The TokyoTyrant class
* TokyoTyrant::add - Adds to a numeric key
* TokyoTyrant::connect - Connect to a database
* TokyoTyrant::connectUri - Connects to a database
* TokyoTyrant::__construct - Construct a new TokyoTyrant object
* TokyoTyrant::copy - Copies the database
* TokyoTyrant::ext - Execute a remote script
* TokyoTyrant::fwmKeys - Returns the forward matching keys
* TokyoTyrant::get - The get purpose
* TokyoTyrant::getIterator - Get an iterator
* TokyoTyrant::num - Number of records in the database
* TokyoTyrant::out - Removes records
* TokyoTyrant::put - Puts values
* TokyoTyrant::putCat - Concatenates to a record
* TokyoTyrant::putKeep - Puts a record
* TokyoTyrant::putNr - Puts value
* TokyoTyrant::putShl - Concatenates to a record
* TokyoTyrant::restore - Restore the database
* TokyoTyrant::setMaster - Set the replication master
* TokyoTyrant::size - Returns the size of the value
* TokyoTyrant::stat - Get statistics
* TokyoTyrant::sync - Synchronize the database
* TokyoTyrant::tune - Tunes connection values
* TokyoTyrant::vanish - Empties the database
* TokyoTyrantTable - The TokyoTyrantTable class
* TokyoTyrantTable::add - Adds a record
* TokyoTyrantTable::genUid - Generate unique id
* TokyoTyrantTable::get - Get a row
* TokyoTyrantTable::getIterator - Get an iterator
* TokyoTyrantTable::getQuery - Get a query object
* TokyoTyrantTable::out - Remove records
* TokyoTyrantTable::put - Store a row
* TokyoTyrantTable::putCat - Concatenates to a row
* TokyoTyrantTable::putKeep - Put a new record
* TokyoTyrantTable::putNr - Puts value
* TokyoTyrantTable::putShl - Concatenates to a record
* TokyoTyrantTable::setIndex - Sets index
* TokyoTyrantQuery - The TokyoTyrantQuery class
* TokyoTyrantQuery::addCond - Adds a condition to the query
* TokyoTyrantQuery::__construct - Construct a new query
* TokyoTyrantQuery::count - Counts records
* TokyoTyrantQuery::current - Returns the current element
* TokyoTyrantQuery::hint - Get the hint string of the query
* TokyoTyrantQuery::key - Returns the current key
* TokyoTyrantQuery::metaSearch - Retrieve records with multiple
queries
* TokyoTyrantQuery::next - Moves the iterator to next entry
* TokyoTyrantQuery::out - Removes records based on query
* TokyoTyrantQuery::rewind - Rewinds the iterator
* TokyoTyrantQuery::search - Searches records
* TokyoTyrantQuery::setLimit - Limit results
* TokyoTyrantQuery::setOrder - Orders results
* TokyoTyrantQuery::valid - Checks the validity of current item
----------------------------------------------------------------------
* CUBRID
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* CUBRID Functions
* CUBRID MySQL Compatibility Functions
* CUBRID Obsolete Aliases and Functions
* dBase
* Introduction
* Installing/Configuring
* Predefined Constants
* dBase Functions
* DB++
* Introduction
* Installing/Configuring
* Predefined Constants
* DB++ Functions
* FrontBase
* Introduction
* Installing/Configuring
* Predefined Constants
* FrontBase Functions
* filePro
* Introduction
* Installing/Configuring
* Predefined Constants
* filePro Functions
* Firebird/InterBase
* Introduction
* Installing/Configuring
* Predefined Constants
* Firebird/InterBase Functions
* Informix
* Introduction
* Installing/Configuring
* Predefined Constants
* Informix Functions
* IBM DB2 - IBM DB2, Cloudscape and Apache Derby
* Introduction
* Installing/Configuring
* Predefined Constants
* IBM DB2 Functions
* Ingres - Ingres DBMS, EDBC, and Enterprise Access Gateways
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* Ingres Functions
* MaxDB
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* MaxDB Functions
* Mongo - MongoDB Native Driver
* Manual
* Core Classes
* Types
* GridFS Classes
* Functions
* Exceptions
* mSQL
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* mSQL Functions
* Mssql - Microsoft SQL Server
* Introduction
* Installing/Configuring
* Predefined Constants
* Mssql Functions
* MySQL
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* MySQL Functions
* Mysqli - MySQL Improved Extension
* Introduction
* Overview
* Installing/Configuring
* The mysqli Extension and Persistent Connections
* Predefined Constants
* Notes
* The MySQLi Extension Function Summary
* MySQLi - The MySQLi class
* MySQLi_STMT - The MySQLi_STMT class
* MySQLi_Result - The MySQLi_Result class
* MySQLi_Driver - The MySQLi_Driver class
* MySQLi_Warning - The MySQLi_Warning class
* Aliases and deprecated Mysqli Functions
* Mysqlnd - MySQL Native Driver
* Introduction
* Overview
* Installation
* Runtime Configuration
* Persistent Connections
* Statistics
* Notes
* MySQL Native Driver Plugin API
* mysqlnd_ms - Mysqlnd replication and load balancing plugin
* Introduction
* Quickstart and Examples
* Concepts
* Installing/Configuring
* Predefined Constants
* Mysqlnd_ms Functions
* mysqlnd_qc - Mysqlnd query result cache plugin
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* mysqlnd_qc Functions
* OCI8 - Oracle OCI8
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* Connection Handling
* Supported Datatypes
* OCI8 Functions
* OCI8 Obsolete Aliases and Functions
* Ovrimos SQL
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* Ovrimos SQL Functions
* Paradox - Paradox File Access
* Introduction
* Installing/Configuring
* Predefined Constants
* Paradox Functions
* PostgreSQL
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* PostgreSQL Functions
* SQLite
* Introduction
* Installing/Configuring
* Predefined Constants
* SQLite Functions
* SQLite3
* Introduction
* Installing/Configuring
* Predefined Constants
* SQLite3 - The SQLite3 class
* SQLite3Stmt - The SQLite3Stmt class
* SQLite3Result - The SQLite3Result class
* SQLSRV - Microsoft SQL Server Driver for PHP
* Introduction
* Installing/Configuring
* Predefined Constants
* SQLSRV Functions
* Sybase
* Introduction
* Installing/Configuring
* Predefined Constants
* Sybase Functions
* tokyo_tyrant
* Introduction
* Installing/Configuring
* Predefined Constants
* Examples
* TokyoTyrant - The TokyoTyrant class
* TokyoTyrantTable - The TokyoTyrantTable class
* TokyoTyrantQuery - The TokyoTyrantQuery class
----------------------------------------------------------------------
* Abstraction Layers
* DBA - Database (dbm-style) Abstraction Layer
* dbx
* ODBC - ODBC (Unified)
* PDO - PHP Data Objects
* Vendor Specific Database Extensions
* CUBRID
* dBase
* DB++
* FrontBase
* filePro
* Firebird/InterBase
* Informix
* IBM DB2 - IBM DB2, Cloudscape and Apache Derby
* Ingres - Ingres DBMS, EDBC, and Enterprise Access Gateways
* MaxDB
* Mongo - MongoDB Native Driver
* mSQL
* Mssql - Microsoft SQL Server
* MySQL
* Mysqli - MySQL Improved Extension
* Mysqlnd - MySQL Native Driver
* mysqlnd_ms - Mysqlnd replication and load balancing plugin
* mysqlnd_qc - Mysqlnd query result cache plugin
* OCI8 - Oracle OCI8
* Ovrimos SQL
* Paradox - Paradox File Access
* PostgreSQL
* SQLite
* SQLite3
* SQLSRV - Microsoft SQL Server Driver for PHP
* Sybase
* tokyo_tyrant
----------------------------------------------------------------------
----------------------------------------------------------------------
File System Related Extensions
----------------------------------------------------------------------
Direct IO
----------------------------------------------------------------------
Introduction
PHP supports the direct io functions as described in the Posix Standard
(Section 6) for performing I/O functions at a lower level than the
C-Language stream I/O functions (fopen(), fread(),..). The use of the DIO
functions should be considered only when direct control of a device is
needed. In all other cases, the standard filesystem functions are more
than adequate.
Note:
This extension has been moved to the >> PECL repository and is no longer
bundled with PHP as of PHP 5.1.0.
This extension is only available on Windows Platforms as of PHP 5.0.0
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
This >> PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual
chapter titled Installation of PECL extensions. Additional information
such as new releases, downloads, source files, maintainer information, and
a CHANGELOG, can be located here: >> http://pecl.php.net/package/dio.
A DLL for this PECL extension is currently unavailable. See also the
building on Windows section.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
One resource type is defined by this extension: a file descriptor returned
by dio_open().
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
F_DUPFD (integer)
F_GETFD (integer)
F_GETFL (integer)
F_GETLK (integer)
F_GETOWN (integer)
F_RDLCK (integer)
F_SETFL (integer)
F_SETLK (integer)
F_SETLKW (integer)
F_SETOWN (integer)
F_UNLCK (integer)
F_WRLCK (integer)
O_APPEND (integer)
O_ASYNC (integer)
O_CREAT (integer)
O_EXCL (integer)
O_NDELAY (integer)
O_NOCTTY (integer)
O_NONBLOCK (integer)
O_RDONLY (integer)
O_RDWR (integer)
O_SYNC (integer)
O_TRUNC (integer)
O_WRONLY (integer)
S_IRGRP (integer)
S_IROTH (integer)
S_IRUSR (integer)
S_IRWXG (integer)
S_IRWXO (integer)
S_IRWXU (integer)
S_IWGRP (integer)
S_IWOTH (integer)
S_IWUSR (integer)
S_IXGRP (integer)
S_IXOTH (integer)
S_IXUSR (integer)
----------------------------------------------------------------------
----------------------------------------------------------------------
Direct IO Functions
----------------------------------------------------------------------
dio_close
(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)
dio_close - Closes the file descriptor given by fd
Description
void dio_close ( resource $fd )
The function dio_close() closes the file descriptor fd.
Parameters
fd
The file descriptor returned by dio_open().
Return Values
No value is returned.
Examples
Example #1 Closing an open file descriptor
See Also
* dio_open() - Opens a file (creating it if necessary) at a lower level
than the C library input/ouput stream functions allow.
----------------------------------------------------------------------
----------------------------------------------------------------------
dio_fcntl
(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)
dio_fcntl - Performs a c library fcntl on fd
Description
mixed dio_fcntl ( resource $fd , int $cmd [, mixed $args ] )
The dio_fcntl() function performs the operation specified by cmd on the
file descriptor fd. Some commands require additional arguments args to be
supplied.
Parameters
fd
The file descriptor returned by dio_open().
cmd
Can be one of the following operations:
* F_SETLK - Lock is set or cleared. If the lock is held by
someone else dio_fcntl() returns -1.
* F_SETLKW - like F_SETLK, but in case the lock is held by
someone else, dio_fcntl() waits until the lock is released.
* F_GETLK - dio_fcntl() returns an associative array (as
described above) if someone else prevents lock. If there is
no obstruction key "type" will set to F_UNLCK.
* F_DUPFD - finds the lowest numbered available file descriptor
greater than or equal to args and returns them.
* F_SETFL - Sets the file descriptors flags to the value
specified by args, which can be O_APPEND, O_NONBLOCK or
O_ASYNC. To use O_ASYNC you will need to use the PCNTL
extension.
args
args is an associative array, when cmd is F_SETLK or F_SETLLW,
with the following keys:
* "start" - offset where lock begins
* "length" - size of locked area. zero means to end of file
* "wenth" - Where l_start is relative to: can be SEEK_SET,
SEEK_END and SEEK_CUR
* "type" - type of lock: can be F_RDLCK (read lock), F_WRLCK
(write lock) or F_UNLCK (unlock)
Return Values
Returns the result of the C call.
Examples
Example #1 Setting and clearing a lock
F_WRLCK)) == -1) {
// the file descriptor appears locked
echo "The lock can not be cleared. It is held by someone else.";
} else {
echo "Lock succesfully set/cleared";
}
dio_close($fd);
?>
Notes
Note: This function is not implemented on Windows platforms.
----------------------------------------------------------------------
----------------------------------------------------------------------
dio_open
(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)
dio_open - Opens a file (creating it if necessary) at a lower level than
the C library input/ouput stream functions allow.
Description
resource dio_open ( string $filename , int $flags [, int $mode = 0 ] )
dio_open() opens a file and returns a new file descriptor for it.
Parameters
filename
The pathname of the file to open.
flags
The flags parameter is a bitwise-ORed value comprising flags from
the following list. This value must include one of O_RDONLY,
O_WRONLY, or O_RDWR. Additionally, it may include any combination
of the other flags from this list.
* O_RDONLY - opens the file for read access.
* O_WRONLY - opens the file for write access.
* O_RDWR - opens the file for both reading and writing.
* O_CREAT - creates the file, if it doesn't already exist.
* O_EXCL - if both O_CREAT and O_EXCL are set and the file
already exists, causes dio_open() to fail.
* O_TRUNC - if the file exists and is opened for write access,
the file will be truncated to zero length.
* O_APPEND - write operations write data at the end of the
file.
* O_NONBLOCK - sets non blocking mode.
* O_NOCTTY - prevent the OS from assigning the opened file as
the process's controlling terminal when opening a TTY device
file.
mode
If flags contains O_CREAT, mode will set the permissions of the
file (creation permissions). Mode is required for correct
operation when O_CREAT is specified in mode and is ignored
otherwise.
The actual permissions assigned to the created file will be
affected by the process's umask setting as per usual.
Return Values
A file descriptor or FALSE on error.
Examples
Example #1 Opening a file descriptor
See Also
* dio_close() - Closes the file descriptor given by fd
----------------------------------------------------------------------
----------------------------------------------------------------------
dio_read
(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)
dio_read - Reads bytes from a file descriptor
Description
string dio_read ( resource $fd [, int $len = 1024 ] )
The function dio_read() reads and returns len bytes from file with
descriptor fd.
Parameters
fd
The file descriptor returned by dio_open().
len
The number of bytes to read. If not specified, dio_read() reads 1K
sized block.
Return Values
The bytes read from fd.
See Also
* dio_write() - Writes data to fd with optional truncation at length
----------------------------------------------------------------------
----------------------------------------------------------------------
dio_seek
(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)
dio_seek - Seeks to pos on fd from whence
Description
int dio_seek ( resource $fd , int $pos [, int $whence = SEEK_SET ] )
The function dio_seek() is used to change the file position of the given
file descriptor.
Parameters
fd
The file descriptor returned by dio_open().
pos
The new position.
whence
Specifies how the position pos should be interpreted:
* SEEK_SET (default) - specifies that pos is specified from the
beginning of the file.
* SEEK_CUR - Specifies that pos is a count of characters from
the current file position. This count may be positive or
negative.
* SEEK_END - Specifies that pos is a count of characters from
the end of the file. A negative count specifies a position
within the current extent of the file; a positive count
specifies a position past the current end. If you set the
position past the current end, and actually write data, you
will extend the file with zeros up to that position.
Return Values
Examples
Example #1 Positioning in a file
----------------------------------------------------------------------
----------------------------------------------------------------------
dio_stat
(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)
dio_stat - Gets stat information about the file descriptor fd
Description
array dio_stat ( resource $fd )
dio_stat() returns information about the given file descriptor.
Parameters
fd
The file descriptor returned by dio_open().
Return Values
Returns an associative array with the following keys:
* "device" - device
* "inode" - inode
* "mode" - mode
* "nlink" - number of hard links
* "uid" - user id
* "gid" - group id
* "device_type" - device type (if inode device)
* "size" - total size in bytes
* "blocksize" - blocksize
* "blocks" - number of blocks allocated
* "atime" - time of last access
* "mtime" - time of last modification
* "ctime" - time of last change
On error dio_stat() returns NULL.
----------------------------------------------------------------------
----------------------------------------------------------------------
dio_tcsetattr
(PHP 4 >= 4.3.0, PHP 5 <= 5.0.5)
dio_tcsetattr - Sets terminal attributes and baud rate for a serial port
Description
bool dio_tcsetattr ( resource $fd , array $options )
dio_tcsetattr() sets the terminal attributes and baud rate of the open fd.
Parameters
fd
The file descriptor returned by dio_open().
options
The currently available options are:
* 'baud' - baud rate of the port - can be
38400,19200,9600,4800,2400,1800,
1200,600,300,200,150,134,110,75 or 50, default value is 9600.
* 'bits' - data bits - can be 8,7,6 or 5. Default value is 8.
* 'stop' - stop bits - can be 1 or 2. Default value is 1.
* 'parity' - can be 0,1 or 2. Default value is 0.
Return Values
No value is returned.
Examples
Example #1 Setting the baud rate on a serial port
9600,
'bits' => 8,
'stop' => 1,
'parity' => 0
));
while (1) {
$data = dio_read($fd, 256);
if ($data) {
echo $data;
}
}
?>
Notes
Note: This function is not implemented on Windows platforms.
----------------------------------------------------------------------
----------------------------------------------------------------------
dio_truncate
(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)
dio_truncate - Truncates file descriptor fd to offset bytes
Description
bool dio_truncate ( resource $fd , int $offset )
dio_truncate() truncates a file to at most offset bytes in size.
If the file previously was larger than this size, the extra data is lost.
If the file previously was shorter, it is unspecified whether the file is
left unchanged or is extended. In the latter case the extended part reads
as zero bytes.
Parameters
fd
The file descriptor returned by dio_open().
offset
The offset in bytes.
Return Values
Returns TRUE on success or FALSE on failure.
Notes
Note: This function is not implemented on Windows platforms.
----------------------------------------------------------------------
----------------------------------------------------------------------
dio_write
(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)
dio_write - Writes data to fd with optional truncation at length
Description
int dio_write ( resource $fd , string $data [, int $len = 0 ] )
dio_write() writes up to len bytes from data to file fd.
Parameters
fd
The file descriptor returned by dio_open().
data
The written data.
len
The length of data to write in bytes. If not specified, the
function writes all the data to the specified file.
Return Values
Returns the number of bytes written to fd.
See Also
* dio_read() - Reads bytes from a file descriptor
----------------------------------------------------------------------
Table of Contents
* dio_close - Closes the file descriptor given by fd
* dio_fcntl - Performs a c library fcntl on fd
* dio_open - Opens a file (creating it if necessary) at a lower level
than the C library input/ouput stream functions allow.
* dio_read - Reads bytes from a file descriptor
* dio_seek - Seeks to pos on fd from whence
* dio_stat - Gets stat information about the file descriptor fd
* dio_tcsetattr - Sets terminal attributes and baud rate for a serial
port
* dio_truncate - Truncates file descriptor fd to offset bytes
* dio_write - Writes data to fd with optional truncation at length
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Direct IO Functions
* dio_close - Closes the file descriptor given by fd
* dio_fcntl - Performs a c library fcntl on fd
* dio_open - Opens a file (creating it if necessary) at a lower
level than the C library input/ouput stream functions allow.
* dio_read - Reads bytes from a file descriptor
* dio_seek - Seeks to pos on fd from whence
* dio_stat - Gets stat information about the file descriptor fd
* dio_tcsetattr - Sets terminal attributes and baud rate for a
serial port
* dio_truncate - Truncates file descriptor fd to offset bytes
* dio_write - Writes data to fd with optional truncation at length
----------------------------------------------------------------------
----------------------------------------------------------------------
Directories
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
There is no installation needed to use these functions; they are part of
the PHP core.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
This extension has no resource types defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
DIRECTORY_SEPARATOR (string)
PATH_SEPARATOR (string)
Available since PHP 4.3.0.
SCANDIR_SORT_ASCENDING (integer)
Available since PHP 5.4.0.
SCANDIR_SORT_DESCENDING (integer)
Available since PHP 5.4.0.
SCANDIR_SORT_NONE (integer)
Available since PHP 5.4.0.
----------------------------------------------------------------------
----------------------------------------------------------------------
Directory Functions
See Also
For related functions such as dirname(), is_dir(), mkdir(), and rmdir(),
see the Filesystem section.
----------------------------------------------------------------------
chdir
(PHP 4, PHP 5)
chdir - Change directory
Description
bool chdir ( string $directory )
Changes PHP's current directory to directory.
Parameters
directory
The new current directory
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 chdir() example
The above example will output something similar to:
/home/vincent
/home/vincent/public_html
Notes
Note: When safe mode is enabled, PHP checks whether the directory in
which the script is operating has the same UID (owner) as the script
that is being executed.
See Also
* getcwd() - Gets the current working directory
----------------------------------------------------------------------
----------------------------------------------------------------------
chroot
(PHP 4 >= 4.0.5, PHP 5)
chroot - Change the root directory
Description
bool chroot ( string $directory )
Changes the root directory of the current process to directory, and
changes the current working directory to "/".
This function is only available to GNU and BSD systems, and only when
using the CLI, CGI or Embed SAPI. Also, this function requires root
privileges.
Parameters
directory
The path to change the root directory to.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 chroot() example
The above example will output:
/
Notes
Note: This function is not implemented on Windows platforms.
----------------------------------------------------------------------
----------------------------------------------------------------------
dir
(PHP 4, PHP 5)
dir - Return an instance of the Directory class
Description
Directory {
string $Directory->path ;
resource $handle ;
string Directory::read ( void )
void Directory::rewind ( void )
void Directory::close ( void )
}
A pseudo-object oriented mechanism for reading a directory. The given
directory is opened. Two properties are available once the directory has
been opened. The handle property can be used with other directory
functions such as readdir(), rewinddir() and closedir(). The path property
is set to path the directory that was opened. Three methods are available:
read, rewind and close.
Examples
Example #1 dir() example
Please note the fashion in which dir::read()'s return value is checked in
the example below. We are explicitly testing whether the return value is
identical to (equal to and of the same type as - see Comparison Operators
for more information) FALSE since otherwise, any directory entry whose
name evaluates to FALSE will stop the loop.
handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
echo $entry."\n";
}
$d->close();
?>
The above example will output something similar to:
Handle: Resource id #2
Path: /etc/php5
.
..
apache
cgi
cli
Notes
Note:
The order in which directory entries are returned by the read method is
system-dependent.
----------------------------------------------------------------------
----------------------------------------------------------------------
closedir
(PHP 4, PHP 5)
closedir - Close directory handle
Description
void closedir ([ resource $dir_handle ] )
Closes the directory stream indicated by dir_handle. The stream must have
previously been opened by opendir().
Parameters
dir_handle
The directory handle resource previously opened with opendir(). If
the directory handle is not specified, the last link opened by
opendir() is assumed.
Examples
Example #1 closedir() example
----------------------------------------------------------------------
----------------------------------------------------------------------
getcwd
(PHP 4, PHP 5)
getcwd - Gets the current working directory
Description
string getcwd ( void )
Gets the current working directory.
Return Values
Returns the current working directory on success, or FALSE on failure.
On some Unix variants, getcwd() will return FALSE if any one of the parent
directories does not have the readable or search mode set, even if the
current directory does. See chmod() for more information on modes and
permissions.
Examples
Example #1 getcwd() example
The above example will output something similar to:
/home/didou
/home/didou/cvs
See Also
* chdir() - Change directory
* chmod() - Changes file mode
----------------------------------------------------------------------
----------------------------------------------------------------------
opendir
(PHP 4, PHP 5)
opendir - Open directory handle
Description
resource opendir ( string $path [, resource $context ] )
Opens up a directory handle to be used in subsequent closedir(),
readdir(), and rewinddir() calls.
Parameters
path
The directory path that is to be opened
context
For a description of the context parameter, refer to the streams
section of the manual.
Return Values
Returns a directory handle resource on success, or FALSE on failure.
If path is not a valid directory or the directory can not be opened due to
permission restrictions or filesystem errors, opendir() returns FALSE and
generates a PHP error of level E_WARNING. You can suppress the error
output of opendir() by prepending '@' to the front of the function name.
Changelog
Version Description
5.0.0 path supports the ftp:// URL wrapper.
4.3.0 path can also be any URL which supports directory listing, however
only the file:// URL wrapper supports this in PHP 4
Examples
Example #1 opendir() example
The above example will output something similar to:
filename: . : filetype: dir
filename: .. : filetype: dir
filename: apache : filetype: dir
filename: cgi : filetype: dir
filename: cli : filetype: dir
See Also
* is_dir() - Tells whether the filename is a directory
* readdir() - Read entry from directory handle
* Dir
----------------------------------------------------------------------
----------------------------------------------------------------------
readdir
(PHP 4, PHP 5)
readdir - Read entry from directory handle
Description
string readdir ([ resource $dir_handle ] )
Returns the filename of the next file from the directory. The filenames
are returned in the order in which they are stored by the filesystem.
Parameters
dir_handle
The directory handle resource previously opened with opendir(). If
the directory handle is not specified, the last link opened by
opendir() is assumed.
Return Values
Returns the filename on success or FALSE on failure.
Warning
This function may return Boolean FALSE, but may also return a non-Boolean
value which evaluates to FALSE, such as 0 or "". Please read the section
on Booleans for more information. Use the === operator for testing the
return value of this function.
Examples
Example #1 List all files in a directory
Please note the fashion in which readdir()'s return value is checked in
the examples below. We are explicitly testing whether the return value is
identical to (equal to and of the same type as--see Comparison Operators
for more information) FALSE since otherwise, any directory entry whose
name evaluates to FALSE will stop the loop (e.g. a directory named "0").
Example #2 List all files in the current directory and strip out . and ..
See Also
* is_dir() - Tells whether the filename is a directory
* glob() - Find pathnames matching a pattern
* opendir() - Open directory handle
* scandir() - List files and directories inside the specified path
----------------------------------------------------------------------
----------------------------------------------------------------------
rewinddir
(PHP 4, PHP 5)
rewinddir - Rewind directory handle
Description
void rewinddir ([ resource $dir_handle ] )
Resets the directory stream indicated by dir_handle to the beginning of
the directory.
Parameters
dir_handle
The directory handle resource previously opened with opendir(). If
the directory handle is not specified, the last link opened by
opendir() is assumed.
----------------------------------------------------------------------
----------------------------------------------------------------------
scandir
(PHP 5)
scandir - List files and directories inside the specified path
Description
array scandir ( string $directory [, int $sorting_order =
SCANDIR_SORT_ASCENDING [, resource $context ]] )
Returns an array of files and directories from the directory.
Parameters
directory
The directory that will be scanned.
sorting_order
By default, the sorted order is alphabetical in ascending order.
If the optional sorting_order is set to SCANDIR_SORT_DESCENDING,
then the sort order is alphabetical in descending order. If it is
set to SCANDIR_SORT_NONE then the result is unsorted.
context
For a description of the context parameter, refer to the streams
section of the manual.
Return Values
Returns an array of filenames on success, or FALSE on failure. If
directory is not a directory, then boolean FALSE is returned, and an error
of level E_WARNING is generated.
Changelog
Version Description
5.4.0 sorting_order now accepts constants. Any nonzero value caused
descending order in previous versions.
Examples
Example #1 A simple scandir() example
The above example will output something similar to:
Array
(
[0] => .
[1] => ..
[2] => bar.php
[3] => foo.txt
[4] => somedir
)
Array
(
[0] => somedir
[1] => foo.txt
[2] => bar.php
[3] => ..
[4] => .
)
Example #2 PHP 4 alternatives to scandir()
The above example will output something similar to:
Array
(
[0] => .
[1] => ..
[2] => bar.php
[3] => foo.txt
[4] => somedir
)
Array
(
[0] => somedir
[1] => foo.txt
[2] => bar.php
[3] => ..
[4] => .
)
Notes
Tip
A URL can be used as a filename with this function if the fopen wrappers
have been enabled. See fopen() for more details on how to specify the
filename. See the Supported Protocols and Wrappers for links to
information about what abilities the various wrappers have, notes on their
usage, and information on any predefined variables they may provide.
See Also
* opendir() - Open directory handle
* readdir() - Read entry from directory handle
* glob() - Find pathnames matching a pattern
* is_dir() - Tells whether the filename is a directory
* sort() - Sort an array
----------------------------------------------------------------------
Table of Contents
* chdir - Change directory
* chroot - Change the root directory
* dir - Return an instance of the Directory class
* closedir - Close directory handle
* getcwd - Gets the current working directory
* opendir - Open directory handle
* readdir - Read entry from directory handle
* rewinddir - Rewind directory handle
* scandir - List files and directories inside the specified path
----------------------------------------------------------------------
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Directory Functions
* chdir - Change directory
* chroot - Change the root directory
* dir - Return an instance of the Directory class
* closedir - Close directory handle
* getcwd - Gets the current working directory
* opendir - Open directory handle
* readdir - Read entry from directory handle
* rewinddir - Rewind directory handle
* scandir - List files and directories inside the specified path
----------------------------------------------------------------------
----------------------------------------------------------------------
File Information
----------------------------------------------------------------------
Introduction
The functions in this module try to guess the content type and encoding of
a file by looking for certain magic byte sequences at specific positions
within the file. While this is not a bullet proof approach the heuristics
used do a very good job.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
Before PHP 5.3.0, the magic_open library is needed to build this
extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
This extension is enabled by default as of PHP 5.3.0. Before this time,
fileinfo was a PECL extension but is no longer maintained there. However,
versions prior to 5.3+ may use the >> discontinued PECL extension.
Windows users must include the bundled php_fileinfo.dll DLL file in
php.ini to enable this extension.
The libmagic library is bundled with PHP, but includes PHP specific
changes. A patch against libmagic named libmagic.patch is maintained and
may be found within the PHP fileinfo extensions source.
Upgrade history of the bundled libmagic library
PHP Version Updated libmagic Version Notes
5.3.2 5.03
5.3.0 5.02
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
This extension has no configuration directives defined in php.ini.
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
There is one resource used in Fileinfo extension: a magic database
descriptor returned by finfo_open().
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
FILEINFO_NONE (integer)
No special handling.
FILEINFO_SYMLINK (integer)
Follow symlinks.
FILEINFO_MIME_TYPE (integer)
Return the mime type. Available since PHP 5.3.0.
FILEINFO_MIME_ENCODING (integer)
Return the mime encoding of the file. Available since PHP 5.3.0.
FILEINFO_MIME (integer)
Return the mime type and mime encoding as defined by RFC 2045.
FILEINFO_COMPRESS (integer)
Decompress compressed files. Disabled since PHP 5.3.0 due to
thread safety issues.
FILEINFO_DEVICES (integer)
Look at the contents of blocks or character special devices.
FILEINFO_CONTINUE (integer)
Return all matches, not just the first.
FILEINFO_PRESERVE_ATIME (integer)
If possible preserve the original access time.
FILEINFO_RAW (integer)
Don't translate unprintable characters to a \ooo octal
representation.
----------------------------------------------------------------------
----------------------------------------------------------------------
Fileinfo Functions
----------------------------------------------------------------------
finfo_buffer
finfo::buffer
(PHP 5 >= 5.3.0, PECL fileinfo >= 0.1.0)
finfo_buffer -- finfo::buffer - Return information about a string buffer
Description
Procedural style
string finfo_buffer ( resource $finfo , string $string = NULL [, int
$options = FILEINFO_NONE [, resource $context = NULL ]] )
Object oriented style
string finfo::buffer ( string $string = NULL [, int $options =
FILEINFO_NONE [, resource $context = NULL ]] )
This function is used to get information about binary data in a string.
Parameters
finfo
Fileinfo resource returned by finfo_open().
string
Content of a file to be checked.
options
One or disjunction of more Fileinfo constants.
context
Return Values
Returns a textual description of the string argument, or FALSE if an error
occurred.
Examples
Example #1 A finfo_buffer() example
buffer($_POST["script"]) . "\n";
?>
The above example will output something similar to:
application/x-sh; charset=us-ascii
See Also
* finfo_file() - Return information about a file
----------------------------------------------------------------------
----------------------------------------------------------------------
finfo_close
finfo::__destruct
(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)
finfo_close -- finfo::__destruct - Close fileinfo resource
Description
Procedural style
bool finfo_close ( resource $finfo )
Object oriented style
finfo::__destruct ( void )
This function closes the resource opened by finfo_open().
Parameters
finfo
Fileinfo resource returned by finfo_open().
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
finfo_file
finfo::file
(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)
finfo_file -- finfo::file - Return information about a file
Description
Procedural style
string finfo_file ( resource $finfo , string $file_name = NULL [, int
$options = FILEINFO_NONE [, resource $context = NULL ]] )
Object oriented style
string finfo::file ( string $file_name = NULL [, int $options =
FILEINFO_NONE [, resource $context = NULL ]] )
This function is used to get information about a file.
Parameters
finfo
Fileinfo resource returned by finfo_open().
file_name
Name of a file to be checked.
options
One or disjunction of more Fileinfo constants.
context
For a description of contexts, refer to Stream Functions.
Return Values
Returns a textual description of the contents of the filename argument, or
FALSE if an error occurred.
Examples
Example #1 A finfo_file() example
The above example will output something similar to:
text/html
image/gif
application/vnd.ms-excel
See Also
* finfo_buffer() - Return information about a string buffer
----------------------------------------------------------------------
----------------------------------------------------------------------
finfo_open
finfo->__construct
(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)
finfo_open -- finfo->__construct - Create a new fileinfo resource
Description
Procedural style
resource finfo_open ([ int $options = FILEINFO_NONE [, string $magic_file
= NULL ]] )
Object oriented style (constructor):
finfo::__construct ([ int $options = FILEINFO_NONE [, string $magic_file =
NULL ]] )
This function opens a magic database and returns its resource.
Parameters
options
One or disjunction of more Fileinfo constants.
magic_file
Name of a magic database file, usually something like
/path/to/magic.mime. If not specified, the MAGIC environment
variable is used. If this variable is not set either,
/usr/share/misc/magic is used by default. A .mime and/or .mgc
suffix is added if needed.
Passing NULL or an empty string will be equivalent to the default
value.
Return Values
Returns a magic database resource on success or FALSE on failure.
Examples
Example #1 Object oriented style
file($filename);
?>
Example #2 Procedural style
The above example will output:
text/plain; charset=us-ascii
See Also
* finfo_close() - Close fileinfo resource
----------------------------------------------------------------------
----------------------------------------------------------------------
finfo_set_flags
finfo::set_flags
(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)
finfo_set_flags -- finfo::set_flags - Set libmagic configuration options
Description
Procedural style
bool finfo_set_flags ( resource $finfo , int $options )
Object oriented style
bool finfo::set_flags ( int $options )
This function sets various Fileinfo options. Options can be set also
directly in finfo_open() or other Fileinfo functions.
Parameters
finfo
Fileinfo resource returned by finfo_open().
options
One or disjunction of more Fileinfo constants.
Return Values
Returns TRUE on success or FALSE on failure.
----------------------------------------------------------------------
----------------------------------------------------------------------
mime_content_type
(PHP 4 >= 4.3.0, PHP 5)
mime_content_type - Detect MIME Content-type for a file (deprecated)
Description
string mime_content_type ( string $filename )
Returns the MIME content type for a file as determined by using
information from the magic.mime file.
Parameters
filename
Path to the tested file.
Return Values
Returns the content type in MIME format, like text/plain or
application/octet-stream.
Notes
Warning
This function has been deprecated as the PECL extension Fileinfo provides
the same functionality (and more) in a much cleaner way.
Examples
Example #1 mime_content_type() Example
The above example will output:
image/gif
text/plain
See Also
* Fileinfo for a replacement
----------------------------------------------------------------------
Table of Contents
* finfo_buffer - Return information about a string buffer
* finfo_close - Close fileinfo resource
* finfo_file - Return information about a file
* finfo_open - Create a new fileinfo resource
* finfo_set_flags - Set libmagic configuration options
* mime_content_type - Detect MIME Content-type for a file (deprecated)
----------------------------------------------------------------------
* Introduction
* Installing/Configuring
* Requirements
* Installation
* Runtime Configuration
* Resource Types
* Predefined Constants
* Fileinfo Functions
* finfo_buffer - Return information about a string buffer
* finfo_close - Close fileinfo resource
* finfo_file - Return information about a file
* finfo_open - Create a new fileinfo resource
* finfo_set_flags - Set libmagic configuration options
* mime_content_type - Detect MIME Content-type for a file
(deprecated)
----------------------------------------------------------------------
----------------------------------------------------------------------
Filesystem
----------------------------------------------------------------------
Introduction
No external libraries are needed to build this extension, but if you want
PHP to support LFS (large files) on Linux, then you need to have a recent
glibc and you need compile PHP with the following compiler flags:
-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installing/Configuring
Table of Contents
* Requirements
* Installation
* Runtime Configuration
* Resource Types
----------------------------------------------------------------------
Requirements
No external libraries are needed to build this extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Installation
There is no installation needed to use these functions; they are part of
the PHP core.
----------------------------------------------------------------------
----------------------------------------------------------------------
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Filesystem and Streams Configuration Options
Name Default Changeable Changelog
PHP_INI_ALL in PHP <= 4.3.4.
allow_url_fopen "1" PHP_INI_ALL PHP_INI_SYSTEM in PHP < 6.
Available since PHP 4.0.4.
allow_url_include "0" PHP_INI_ALL PHP_INI_SYSTEM in PHP 5.
Available since PHP 5.2.0.
user_agent NULL PHP_INI_ALL Available since PHP 4.3.0.
default_socket_timeout "60" PHP_INI_ALL Available since PHP 4.3.0.
from "" PHP_INI_ALL
auto_detect_line_endings "0" PHP_INI_ALL Available since PHP 4.3.0.
Here's a short explanation of the configuration directives.
allow_url_fopen boolean
This option enables the URL-aware fopen wrappers that enable
accessing URL object like files. Default wrappers are provided for
the access of remote files using the ftp or http protocol, some
extensions like zlib may register additional wrappers.
Note:
This setting can only be set in php.ini due to security reasons.
Note:
This option was introduced immediately after the release of
version 4.0.3. For versions up to and including 4.0.3 you can
only disable this feature at compile time by using the
configuration switch --disable-url-fopen-wrapper.
Warning
On Windows versions prior to PHP 4.3.0, the following functions do
not support remote file accessing: include(), include_once(),
require(), require_once() and the imagecreatefromXXX functions in
the GD and Image Functions extension.
allow_url_include boolean
This option allows the use of URL-aware fopen wrappers with the
following functions: include(), include_once(), require(),
require_once().
Note:
This setting requires allow_url_fopen to be on.
user_agent string
Define the user agent for PHP to send.
default_socket_timeout integer
Default timeout (in seconds) for socket based streams.
Note: This configuration option was introduced in PHP 4.3.0
from string
The email address to be used on unauthenticated FTP connections
and as the value of From header for HTTP connections, when using
the ftp and http wrappers, respectively.
auto_detect_line_endings boolean
When turned on, PHP will examine the data read by fgets() and
file() to see if it is using Unix, MS-Dos or Macintosh line-ending
conventions.
This enables PHP to interoperate with Macintosh systems, but
defaults to Off, as there is a very small performance penalty when
detecting the EOL conventions for the first line, and also because
people using carriage-returns as item separators under Unix
systems would experience non-backwards-compatible behaviour.
Note: This configuration option was introduced in PHP 4.3.0
----------------------------------------------------------------------
----------------------------------------------------------------------
Resource Types
The file system uses streams as their resource type. Streams are
documented in its own reference chapter, Streams.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Predefined Constants
The constants below are defined by this extension, and will only be
available when the extension has either been compiled into PHP or
dynamically loaded at runtime.
GLOB_BRACE (integer)
GLOB_ONLYDIR (integer)
GLOB_MARK (integer)
GLOB_NOSORT (integer)
GLOB_NOCHECK (integer)
GLOB_NOESCAPE (integer)
GLOB_AVAILABLE_FLAGS (integer)
PATHINFO_DIRNAME (integer)
PATHINFO_BASENAME (integer)
PATHINFO_EXTENSION (integer)
PATHINFO_FILENAME (integer)
Since PHP 5.2.0.
FILE_USE_INCLUDE_PATH (integer)
Search for filename in include_path (since PHP 5).
FILE_NO_DEFAULT_CONTEXT (integer)
FILE_APPEND (integer)
Append content to existing file.
FILE_IGNORE_NEW_LINES (integer)
Strip EOL characters (since PHP 5).
FILE_SKIP_EMPTY_LINES (integer)
Skip empty lines (since PHP 5).
FILE_BINARY (integer)
Binary mode (since PHP 5.2.7).
Note:
This constant has no effect, and is only available for forward
compatibility.
FILE_TEXT (integer)
Text mode (since PHP 5.2.7).
Note:
This constant has no effect, and is only available for forward
compatibility.
INI_SCANNER_NORMAL (integer)
Normal INI scanner mode (since PHP 5.3).
INI_SCANNER_RAW (integer)
Raw INI scanner mode (since PHP 5.3).
FNM_NOESCAPE (integer)
Disable backslash escaping.
FNM_PATHNAME (integer)
Slash in string only matches slash in the given pattern.
FNM_PERIOD (integer)
Leading period in string must be exactly matched by period in the
given pattern.
FNM_CASEFOLD (integer)
Caseless match. Part of the GNU extension.
----------------------------------------------------------------------
----------------------------------------------------------------------
Filesystem Functions
See Also
For related functions, see also the Directory and Program Execution
sections.
For a list and explanation of the various URL wrappers that can be used as
remote files, see also Supported Protocols and Wrappers.
----------------------------------------------------------------------
basename
(PHP 4, PHP 5)
basename - Returns trailing name component of path
Description
string basename ( string $path [, string $suffix ] )
Given a string containing the path to a file or directory, this function
will return the trailing name component.
Parameters
path
A path.
On Windows, both slash (/) and backslash (\) are used as directory
separator character. In other environments, it is the forward
slash (/).
suffix
If the name component ends in suffix this will also be cut off.
Return Values
Returns the base name of the given path.
Changelog
Version Description
4.1.0 The suffix parameter was added
Examples
Example #1 basename() example
The above example will output:
1) sudoers
2) passwd
3) etc
4) .
5)
Notes
Note:
basename() operates naively on the input string, and is not aware of the
actual filesystem, or path components such as "..".
Note:
basename() is locale aware, so for it to see the correct basename with
multibyte character paths, the matching locale must be set using the
setlocale() function.
See Also
* dirname() - Returns parent directory's path
* pathinfo() - Returns information about a file path
----------------------------------------------------------------------
----------------------------------------------------------------------
chgrp
(PHP 4, PHP 5)
chgrp - Changes file group
Description
bool chgrp ( string $filename , mixed $group )
Attempts to change the group of the file filename to group.
Only the superuser may change the group of a file arbitrarily; other users
may change the group of a file to any group of which that user is a
member.
Parameters
filename
Path to the file.
group
A group name or number.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Changing a file's group
Notes
Note: This function will not work on remote files as the file to be
examined must be accessible via the server's filesystem.
Note: When safe mode is enabled, PHP checks whether the files or
directories being operated upon have the same UID (owner) as the script
that is being executed.
See Also
* chown() - Changes file owner
* chmod() - Changes file mode
----------------------------------------------------------------------
----------------------------------------------------------------------
chmod
(PHP 4, PHP 5)
chmod - Changes file mode
Description
bool chmod ( string $filename , int $mode )
Attempts to change the mode of the specified file to that given in mode.
Parameters
filename
Path to the file.
mode
Note that mode is not automatically assumed to be an octal value,
so strings (such as "g+w") will not work properly. To ensure the
expected operation, you need to prefix mode with a zero (0):
The mode parameter consists of three octal number components
specifying access restrictions for the owner, the user group in
which the owner is in, and to everybody else in this order. One
component can be computed by adding up the needed permissions for
that target user base. Number 1 means that you grant execute
rights, number 2 means that you make the file writeable, number 4
means that you make the file readable. Add up these numbers to
specify needed rights. You can also read more about modes on Unix
systems with 'man 1 chmod' and 'man 2 chmod'.
Return Values
Returns TRUE on success or FALSE on failure.
Notes
Note:
The current user is the user under which PHP runs. It is probably not
the same user you use for normal shell or FTP access. The mode can be
changed only by user who owns the file on most systems.
Note: This function will not work on remote files as the file to be
examined must be accessible via the server's filesystem.
Note:
When safe mode is enabled, PHP checks whether the files or directories
you are about to operate on have the same UID (owner) as the script that
is being executed. In addition, you cannot set the SUID, SGID and sticky
bits.
See Also
* chown() - Changes file owner
* chgrp() - Changes file group
* fileperms() - Gets file permissions
* stat() - Gives information about a file
----------------------------------------------------------------------
----------------------------------------------------------------------
chown
(PHP 4, PHP 5)
chown - Changes file owner
Description
bool chown ( string $filename , mixed $user )
Attempts to change the owner of the file filename to user user. Only the
superuser may change the owner of a file.
Parameters
filename
Path to the file.
user
A user name or number.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 Simple chown() usage
The above example will output something similar to:
Array
(
[name] => root
[passwd] => x
[uid] => 0
[gid] => 0
[gecos] => root
[dir] => /root
[shell] => /bin/bash
)
Notes
Note: This function will not work on remote files as the file to be
examined must be accessible via the server's filesystem.
Note: When safe mode is enabled, PHP checks whether the files or
directories being operated upon have the same UID (owner) as the script
that is being executed.
See Also
* chmod() - Changes file mode
----------------------------------------------------------------------
----------------------------------------------------------------------
clearstatcache
(PHP 4, PHP 5)
clearstatcache - Clears file status cache
Description
void clearstatcache ([ bool $clear_realpath_cache = false [, string
$filename ]] )
When you use stat(), lstat(), or any of the other functions listed in the
affected functions list (below), PHP caches the information those
functions return in order to provide faster performance. However, in
certain cases, you may want to clear the cached information. For instance,
if the same file is being checked multiple times within a single script,
and that file is in danger of being removed or changed during that
script's operation, you may elect to clear the status cache. In these
cases, you can use the clearstatcache() function to clear the information
that PHP caches about a file.
You should also note that PHP doesn't cache information about non-existent
files. So, if you call file_exists() on a file that doesn't exist, it will
return FALSE until you create the file. If you create the file, it will
return TRUE even if you then delete the file. However unlink() clears the
cache automatically.
Note:
This function caches information about specific filenames, so you only
need to call clearstatcache() if you are performing multiple operations
on the same filename and require the information about that particular
file to not be cached.
Affected functions include stat(), lstat(), file_exists(), is_writable(),
is_readable(), is_executable(), is_file(), is_dir(), is_link(),
filectime(), fileatime(), filemtime(), fileinode(), filegroup(),
fileowner(), filesize(), filetype(), and fileperms().
Parameters
clear_realpath_cache
Whether to clear the realpath cache or not.
filename
Clear the realpath cache for a specific filename; only used if
clear_realpath_cache is TRUE.
Return Values
No value is returned.
Changelog
Version Description
5.3.0 Added optional clear_realpath_cache and filename parameters.
Examples
Example #1 clearstatcache() example
The above example will output something similar to:
UID @ Sun, 12 Oct 2008 20:48:28 +0100: root
UID @ Sun, 12 Oct 2008 20:48:28 +0100: root
UID @ Sun, 12 Oct 2008 20:48:28 +0100: ross
----------------------------------------------------------------------
----------------------------------------------------------------------
copy
(PHP 4, PHP 5)
copy - Copies file
Description
bool copy ( string $source , string $dest [, resource $context ] )
Makes a copy of the file source to dest.
If you wish to move a file, use the rename() function.
Parameters
source
Path to the source file.
dest
The destination path. If dest is a URL, the copy operation may
fail if the wrapper does not support overwriting of existing
files.
Warning
If the destination file already exists, it will be overwritten.
context
A valid context resource created with stream_context_create().
Return Values
Returns TRUE on success or FALSE on failure.
Changelog
Version Description
5.3.0 Added context support.
4.3.0 Both source and dest may now be URLs if the "fopen wrappers" have
been enabled. See fopen() for more details.
Examples
Example #1 copy() example
See Also
* move_uploaded_file() - Moves an uploaded file to a new location
* rename() - Renames a file or directory
* The section of the manual about handling file uploads
----------------------------------------------------------------------
----------------------------------------------------------------------
delete
delete - See unlink() or unset()
Description
void delete ( void )
This is a dummy manual entry to satisfy those people who are looking for
unlink() or unset() in the wrong place.
Return Values
No value is returned.
See Also
* unlink() - Deletes a file
* unset() - Unset a given variable
----------------------------------------------------------------------
----------------------------------------------------------------------
dirname
(PHP 4, PHP 5)
dirname - Returns parent directory's path
Description
string dirname ( string $path )
Given a string containing the path of a file or directory, this function
will return the parent directory's path.
Parameters
path
A path.
On Windows, both slash (/) and backslash (\) are used as directory
separator character. In other environments, it is the forward
slash (/).
Return Values
Returns the path of the parent directory. If there are no slashes in path,
a dot ('.') is returned, indicating the current directory. Otherwise, the
returned string is path with any trailing /component removed.
Changelog
Version Description
5.0.0 dirname() is now binary safe
4.0.3 dirname() was fixed to be POSIX-compliant.
Examples
Example #1 dirname() example
Notes
Note:
dirname() operates naively on the input string, and is not aware of the
actual filesystem, or path components such as "..".
Note:
dirname() is locale aware, so for it to see the correct directory name
with multibyte character paths, the matching locale must be set using
the setlocale() function.
Note:
Since PHP 4.3.0, you will often get a slash or a dot back from dirname()
in situations where the older functionality would have given you the
empty string.
Check the following change example:
See Also
* basename() - Returns trailing name component of path
* pathinfo() - Returns information about a file path
* realpath() - Returns canonicalized absolute pathname
----------------------------------------------------------------------
----------------------------------------------------------------------
disk_free_space
(PHP 4 >= 4.1.0, PHP 5)
disk_free_space - Returns available space on filesystem or disk partition
Description
float disk_free_space ( string $directory )
Given a string containing a directory, this function will return the
number of bytes available on the corresponding filesystem or disk
partition.
Parameters
directory
A directory of the filesystem or disk partition.
Note:
Given a file name instead of a directory, the behaviour of the
function is unspecified and may differ between operating systems
and PHP versions.
Return Values
Returns the number of available bytes as a float or FALSE on failure.
Examples
Example #1 disk_free_space() example
Notes
Note: This function will not work on remote files as the file to be
examined must be accessible via the server's filesystem.
See Also
* disk_total_space() - Returns the total size of a filesystem or disk
partition
----------------------------------------------------------------------
----------------------------------------------------------------------
disk_total_space
(PHP 4 >= 4.1.0, PHP 5)
disk_total_space - Returns the total size of a filesystem or disk
partition
Description
float disk_total_space ( string $directory )
Given a string containing a directory, this function will return the total
number of bytes on the corresponding filesystem or disk partition.
Parameters
directory
A directory of the filesystem or disk partition.
Return Values
Returns the total number of bytes as a float or FALSE on failure.
Examples
Example #1 disk_total_space() example
Notes
Note: This function will not work on remote files as the file to be
examined must be accessible via the server's filesystem.
See Also
* disk_free_space() - Returns available space on filesystem or disk
partition
----------------------------------------------------------------------
----------------------------------------------------------------------
diskfreespace
(PHP 4, PHP 5)
diskfreespace - Alias of disk_free_space()
Description
This function is an alias of: disk_free_space().
----------------------------------------------------------------------
----------------------------------------------------------------------
fclose
(PHP 4, PHP 5)
fclose - Closes an open file pointer
Description
bool fclose ( resource $handle )
The file pointed to by handle is closed.
Parameters
handle
The file pointer must be valid, and must point to a file
successfully opened by fopen() or fsockopen().
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 A simple fclose() example
See Also
* fopen() - Opens file or URL
* fsockopen() - Open Internet or Unix domain socket connection
----------------------------------------------------------------------
----------------------------------------------------------------------
feof
(PHP 4, PHP 5)
feof - Tests for end-of-file on a file pointer
Description
bool feof ( resource $handle )
Tests for end-of-file on a file pointer.
Parameters
handle
The file pointer must be valid, and must point to a file
successfully opened by fopen() or fsockopen() (and not yet closed
by fclose()).
Return Values
Returns TRUE if the file pointer is at EOF or an error occurs (including
socket timeout); otherwise returns FALSE.
Notes
Warning
If a connection opened by fsockopen() wasn't closed by the server, feof()
will hang. To workaround this, see below example:
Example #1 Handling timeouts with feof()
Warning
If the passed file pointer is not valid you may get an infinite loop,
because feof() fails to return TRUE.
Example #2 feof() example with an invalid file pointer
----------------------------------------------------------------------
----------------------------------------------------------------------
fflush
(PHP 4 >= 4.0.1, PHP 5)
fflush - Flushes the output to a file
Description
bool fflush ( resource $handle )
This function forces a write of all buffered output to the resource
pointed to by the file handle.
Parameters
handle
The file pointer must be valid, and must point to a file
successfully opened by fopen() or fsockopen() (and not yet closed
by fclose()).
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 File write example using fflush()
See Also
* clearstatcache() - Clears file status cache
* fwrite() - Binary-safe file write
----------------------------------------------------------------------
----------------------------------------------------------------------
fgetc
(PHP 4, PHP 5)
fgetc - Gets character from file pointer
Description
string fgetc ( resource $handle )
Gets a character from the given file pointer.
Parameters
handle
The file pointer must be valid, and must point to a file
successfully opened by fopen() or fsockopen() (and not yet closed
by fclose()).
Return Values
Returns a string containing a single character read from the file pointed
to by handle. Returns FALSE on EOF.
Warning
This function may return Boolean FALSE, but may also return a non-Boolean
value which evaluates to FALSE, such as 0 or "". Please read the section
on Booleans for more information. Use the === operator for testing the
return value of this function.
Examples
Example #1 A fgetc() example
Notes
Note: This function is binary-safe.
See Also
* fread() - Binary-safe file read
* fopen() - Opens file or URL
* popen() - Opens process file pointer
* fsockopen() - Open Internet or Unix domain socket connection
* fgets() - Gets line from file pointer
----------------------------------------------------------------------
----------------------------------------------------------------------
fgetcsv
(PHP 4, PHP 5)
fgetcsv - Gets line from file pointer and parse for CSV fields
Description
array fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter =
',' [, string $enclosure = '"' [, string $escape = '\\' ]]]] )
Similar to fgets() except that fgetcsv() parses the line it reads for
fields in CSV format and returns an array containing the fields read.
Parameters
handle
A valid file pointer to a file successfully opened by fopen(),
popen(), or fsockopen().
length
Must be greater than the longest line (in characters) to be found
in the CSV file (allowing for trailing line-end characters). It
became optional in PHP 5. Omitting this parameter (or setting it
to 0 in PHP 5.0.4 and later) the maximum line length is not
limited, which is slightly slower.
delimiter
Set the field delimiter (one character only).
enclosure
Set the field enclosure character (one character only).
escape
Set the escape character (one character only). Defaults as a
backslash.
Return Values
Returns an indexed array containing the fields read.
Note:
A blank line in a CSV file will be returned as an array comprising a
single null field, and will not be treated as an error.
Note: If PHP is not properly recognizing the line endings when reading
files either on or created by a Macintosh computer, enabling the
auto_detect_line_endings run-time configuration option may help resolve
the problem.
fgetcsv() returns NULL if an invalid handle is supplied or FALSE on other
errors, including end of file.
Changelog
Version Description
5.3.0 The escape parameter was added
4.3.5 fgetcsv() is now binary safe
4.3.0 The enclosure parameter was added
Examples
Example #1 Read and print the entire contents of a CSV file
$num fields in line $row: \n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . " \n";
}
}
fclose($handle);
}
?>
Notes
Note:
Locale setting is taken into account by this function. If LANG is e.g.
en_US.UTF-8, files in one-byte encoding are read wrong by this function.
See Also
* str_getcsv() - Parse a CSV string into an array
* explode() - Split a string by string
* file() - Reads entire file into an array
* pack() - Pack data into binary string
* fputcsv() - Format line as CSV and write to file pointer
----------------------------------------------------------------------
----------------------------------------------------------------------
fgets
(PHP 4, PHP 5)
fgets - Gets line from file pointer
Description
string fgets ( resource $handle [, int $length ] )
Gets a line from file pointer.
Parameters
handle
The file pointer must be valid, and must point to a file
successfully opened by fopen() or fsockopen() (and not yet closed
by fclose()).
length
Reading ends when length - 1 bytes have been read, on a newline
(which is included in the return value), or on EOF (whichever
comes first). If no length is specified, it will keep reading from
the stream until it reaches the end of the line.
Note:
Until PHP 4.3.0, omitting it would assume 1024 as the line
length. If the majority of the lines in the file are all larger
than 8KB, it is more resource efficient for your script to
specify the maximum line length.
Return Values
Returns a string of up to length - 1 bytes read from the file pointed to
by handle. If there is no more data to read in the file pointer, then
FALSE is returned.
If an error occurs, FALSE is returned.
Changelog
Version Description
4.3.0 fgets() is now binary safe
4.2.0 The length parameter became optional
Examples
Example #1 Reading a file line by line
Notes
Note: If PHP is not properly recognizing the line endings when reading
files either on or created by a Macintosh computer, enabling the
auto_detect_line_endings run-time configuration option may help resolve
the problem.
Note:
People used to the 'C' semantics of fgets() should note the difference
in how EOF is returned.
See Also
* fgetss() - Gets line from file pointer and strip HTML tags
* fread() - Binary-safe file read
* fgetc() - Gets character from file pointer
* stream_get_line() - Gets line from stream resource up to a given
delimiter
* fopen() - Opens file or URL
* popen() - Opens process file pointer
* fsockopen() - Open Internet or Unix domain socket connection
* stream_set_timeout() - Set timeout period on a stream
----------------------------------------------------------------------
----------------------------------------------------------------------
fgetss
(PHP 4, PHP 5)
fgetss - Gets line from file pointer and strip HTML tags
Description
string fgetss ( resource $handle [, int $length [, string $allowable_tags
]] )
Identical to fgets(), except that fgetss() attempts to strip any NUL
bytes, HTML and PHP tags from the text it reads.
Parameters
handle
The file pointer must be valid, and must point to a file
successfully opened by fopen() or fsockopen() (and not yet closed
by fclose()).
length
Length of the data to be retrieved.
allowable_tags
You can use the optional third parameter to specify tags which
should not be stripped.
Return Values
Returns a string of up to length - 1 bytes read from the file pointed to
by handle, with all HTML and PHP code stripped.
If an error occurs, returns FALSE.
Changelog
Version Description
5.0.0 The length parameter is optional
Example #1 Reading a PHP file line-by-line
Welcome! Today is the of = date('F'); ?>.